# spring-boot-oauth2-swagger **Repository Path**: gitliubo/spring-boot-oauth2-swagger ## Basic Information - **Project Name**: spring-boot-oauth2-swagger - **Description**: Spring Boot + Spring Security Oauth2+ Springfox 实现Swagger API接口 - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2021-08-03 - **Last Updated**: 2021-08-03 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## Spring Boot + Spring Security Oauth2+ Springfox 实现Swagger API接口 ### 运行说明 0.运行`ApiApplication.main`方法 1.访问`hello-controller`的`/hello` `try it out`结果为`{ "Hello": "World"}` ,访问`api-controller`的`/api/hello` `try it out`结果为`{"error": "unauthorized","error_description": "Full authentication is required to access this resource"}` 2.访问`http://localhost:8080/swagger-ui.html` 3.点击界面`Authorize`链接 4.选择`type`选择框中的`Basic auth` 5.填写`ClientId`为`foo`,填写`Secret`为`bar` 6.选择`scope`:`read`,`write` 7.`Authorize`按钮授权 8.再次执行1,,访问`api-controller`的`/api/hello` `try it out`结果为`{"Hello": "API"}` ### oauth2 授权类型是[client_credentials](http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html) ## 遇到的问题 - spring security 登入成功后跳转到之前的页面 通过`http....successHandler()`来配置登入成功后处理器 SimpleUrlAuthenticationSuccessHandler 设置 useReferer 为true就可以跳转到之前的页面 ``` public AuthenticationSuccessHandler successHandler() { SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler(); successHandler.setUseReferer(true);//设为true就会自动跳转到登入页面 return successHandler; } ``` - springfox 使用swagger-ui 添加webjars ``` org.webjars swagger-ui 3.1.4 ``` 添加spring mvc配置 ``` @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("oauth2-redirect.html") .addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/3.1.4/oauth2-redirect.html"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } ``` 添加spring security配置 ``` http.authorizeRequests() .antMatchers("/webjars/**", "/resources/**", "/swagger-ui.html" , "/swagger-resources/**", "/v2/api-docs", "index.html").permitAll() ``` Oauth2模式切换