我似乎无法正确设置我的安全配置。无论我使用hasRole
做什么,我的端点总是返回403。
另外,除非我在antMatchers
和.requestMatchers()
下都复制了.authorizeRequests()
,否则我什么都无法工作。我显然在这里错过了一些东西。
基本上,我希望所有内容都需要身份验证,但是如果用户是某些组的成员(现在仅是admin),则只有几个端点可以访问。
我的安全性配置如下。 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中找到。
最佳答案
您是否尝试过使用“ROLE_ADMIN”而不是“ADMIN”?看一下以供引用:
Spring security added prefix "ROLE_" to all roles name?