我有一个只有REST端点的应用程序。我已经通过以下方式启用了OAuth2令牌安全性:
@Configuration
@EnableAuthorizationServer
public class AuthServerOAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("xxx").secret("xxx").accessTokenValiditySeconds(3600)
.authorizedGrantTypes("client_credentials")
.scopes("xxx", "xxx")
.and()
.withClient("xxx").secret("xxx").accessTokenValiditySeconds(3600)
.authorizedGrantTypes("password", "refresh_token")
.scopes("xxx", "xxx");
}
}
现在,如果我尝试访问我的任何端点,我会得到401未经授权的错误,我必须通过
/oauth/token?grant_type=client_credentials
或/oauth/token?grant_type=password
调用首先获取access_token。如果我在前一个调用中返回的令牌中添加正确的Authorization
标头,则REST端点按预期工作。然而,我无法访问swagger-ui页面。我已经通过以下方式启用了swagger:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.basePackage("com.xxx"))
.paths(PathSelectors.regex("/xxx/.*"))
.build();
}
}
如果我访问 localhost:8080/swagger-ui.html
, 我会看到:
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
所以我添加了以下内容,以便能够访问Swagger:
@Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/swagger-ui.html")
.antMatchers("/webjars/springfox-swagger-ui/**")
.antMatchers("/swagger-resources/**")
.antMatchers("/v2/api-docs");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
在
@EnableWebMvc
类中,我添加了以下内容:@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
现在我能够访问Swagger UI页面,但我的REST端点的安全性出了问题。我的意思是,client_credentials端点不再需要令牌,而密码端点无论我做什么都会返回403 Forbidden。
我认为我的方法是错误的,但我不知道错在哪里。基本上我想要:
- 在所有REST端点(例如以/api/*开头)上使用Oauth令牌安全
- 应该可以访问Swagger UI页面
- Swagger页面上的端点应该有一种方式来指定access_token