在通过管理服务的端口号向广告服务发送一些请求时,我遇到了问题。
http://localhost:9002/api/v1/admin_role/alladvertisements
http://localhost:9002/api/v1/user_role/alladvertisements上面显示的两个urls被禁止发布403个问题。我使用访问令牌作为用户和管理员的承载令牌。虽然admin负责自己的请求,但用户只能处理它的进程。
以下是两个urls的结果。
{
"timestamp": "2022-08-31T23:58:15.250+00:00",
"status": 403,
"error": "Forbidden",
"path": "/api/v1/admin_role/alladvertisements"
}
{
"timestamp": "2022-08-31T23:58:15.250+00:00",
"status": 403,
"error": "Forbidden",
"path": "/api/v1/user_role/alladvertisements"
}这里是管理服务的web安全部分。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/api/v1/admin_role/*").hasAnyRole("ROLE_ADMIN")
.antMatchers("/api/v1/user_role/*").hasAnyRole("ROLE_USER")
.antMatchers("/actuator/health").hasAnyRole("ROLE_ADMIN")
.antMatchers("/actuator/circuitbreakerevents").hasAnyRole("ROLE_ADMIN")
.anyRequest()
.permitAll();
}
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider provider = keycloakAuthenticationProvider();
provider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(provider);
}
@Override
@Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
}我怎么才能修好它?
这里是我的github存储库:链接
发布于 2022-09-01 07:20:49
如果您没有更改默认的GrantedAuthority前缀- "ROLE_",那么SecurityExpressionRoot的.hasRole()和.hasAnyRole()方法将把这个前缀添加到传递的参数中,您可以读取这里和这里。
此外,作为在javadoc中声明,SimpleAuthorityMapper在映射GrantedAuthority时还向角色添加了"ROLE_“前缀。
这意味着,当您将"ROLE_ADMIN“传递给该方法时,它会将其转换为"ROLE_ROLE_ADMIN",结果得到了403状态。
因此,尝试配置没有前缀的安全性,如下所示:
.antMatchers("/api/v1/admin_role/*").hasRole("ADMIN")
.antMatchers("/api/v1/user_role/*").hasRole("USER")或者您可以使用.hasAuthority()或.hasAnyAuthority()方法代替,哪个不会改变传递的论点
.antMatchers("/api/v1/admin_role/*").hasAuthority("ROLE_ADMIN")
.antMatchers("/api/v1/user_role/*").hasAuthority("ROLE_USER")https://stackoverflow.com/questions/73563072
复制相似问题