【发布时间】:2017-09-28 00:47:38
【问题描述】:
我似乎无法正确配置我的安全配置。无论我在使用 hasRole 时做什么,我的端点总是返回 403。
除非我在.requestMatchers() 和.authorizeRequests() 下复制我的antMatchers,否则我什么也做不了。我显然在这里遗漏了一些东西。
基本上,我希望所有内容都需要身份验证,但只有当用户是某些组的成员(现在只是管理员)时,才能访问一些端点。
我的安全配置如下。 hasRole 之外的所有内容都可以正常工作。
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.requestMatchers()
.antMatchers(HttpMethod.GET, "/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html")
.antMatchers(HttpMethod.GET, "/users")
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html").permitAll()
.antMatchers(HttpMethod.GET, "/users").hasRole("ADMIN")
.anyRequest().authenticated();
}
// Inspiration: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#comment-2416096114
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**");
}
}
我的AuthenticationConfiguration如下
@Configuration
@EnableResourceServer
public class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {
private final UserDetailsService userService;
private final PasswordEncoder passwordEncoder;
public AuthenticationConfiguration(UserDetailsService userService, PasswordEncoder passwordEncoder) {
this.userService = userService;
this.passwordEncoder = passwordEncoder;
}
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userService)
.passwordEncoder(passwordEncoder);
}
}
我的 AuthorizationServerConfiguration 如下
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private final AuthenticationManager authenticationManager;
public AuthorizationServerConfiguration(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("html5")
.secret("password")
.authorizedGrantTypes("password")
.scopes("openid");
}
}
我很乐意发布我的用户服务和其他内容。但是除了hasRole 和Principal 之外,一切似乎都正常工作,并加载了正确的权限(角色)。但是请让我知道我是否应该发布更多代码。
完整的源代码可以在here找到。
【问题讨论】:
-
@dur - 是的,但我觉得很难理解......显然。
-
@M.Deinum - 我的权限以 ROLE_ 为前缀
-
我正在执行以下命令:http localhost:8080/users "Authorization: Bearer $TOKEN"。客户端称为 httpie,但 curl 或 postman... 一样一样。
-
@dur - gist.github.com/tonsV2/fec750c0f5a26a857caf49659df6dcd6 - 这就是输出。我所收集的只是它被拒绝了。不知道为什么。唯一奇怪的是它说用户是匿名的。
-
@dur - 这很奇怪。主体已填充,并且仅当我将不记名令牌传递到其他地方时才授予访问权限。无论如何,我已经用请求的代码更新了问题。
标签: spring spring-security spring-security-oauth2