我试图在我的春季启动应用程序中使用Keycloak。
我想根据REST方法和用户角色限制对特定网址的访问。
在下面的示例中,具有任何角色view-all
或calendar
的用户可以执行GET,而拥有manage-all
或calendar_manage
的用户可以执行POST,PUT ,或DELETE。
不幸的是,此配置允许任何经过身份验证的用户访问/ api / calendar URL。我做错了什么?
@Configuration
@EnableWebSecurity
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception
{
super.configure(http);
http
.csrf().disable()
.antMatcher("/api/**")
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/calendar/*").hasAnyRole("view-all", "calendar")
.antMatchers(HttpMethod.POST, "/api/calendar/*").hasAnyRole("manage-all", "calendar_manage")
.antMatchers(HttpMethod.PUT, "/api/calendar/*").hasAnyRole("manage-all", "calendar_manage")
.antMatchers(HttpMethod.DELETE, "/api/calendar/*").hasAnyRole("manage-all", "calendar_manage");
}
}
答案 0 :(得分:0)
尝试 isAuthenticated 和 hasAnyAuthority 和权限(" / api / **")
@Configuration
@EnableWebSecurity
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception
{
super.configure(http);
http .authorizeRequests()
.csrf().disable()
.antMatcher("/api/**").permitAll()
.isAuthenticated()
.antMatchers(HttpMethod.GET, "/api/calendar/*").hasAnyAuthority("view-all", "calendar")
.antMatchers(HttpMethod.POST, "/api/calendar/*").hasAnyAuthority("manage-all", "calendar_manage")
.antMatchers(HttpMethod.PUT, "/api/calendar/*").hasAnyAuthority("manage-all", "calendar_manage")
.antMatchers(HttpMethod.DELETE, "/api/calendar/*").hasAnyAuthority("manage-all", "calendar_manage");
}
}
答案 1 :(得分:0)
诀窍是 - 在蚂蚁匹配器的路径末端需要/**
!
(我必须通过spring代码来解决它 - 请参阅Spring Core' s doMatch()
类中的方法AntPathMatcher
.antMatchers(HttpMethod.GET, "/calendar/**")
.hasAnyRole("view-all", "calendar", "calendar_manage")
.antMatchers(HttpMethod.POST, "/calendar/**")
.hasAnyRole("manage-all", "calendar_manage")
.antMatchers(HttpMethod.PUT, "/calendar/**")
.hasAnyRole("manage-all", "calendar_manage")
.antMatchers(HttpMethod.DELETE, "/calendar/**")
.hasAnyRole("manage-all", "calendar_manage")