Spring-引导 REST 安全配置角色无法正常工作
Spring-boot REST security config roles don't work right
只有具有管理员角色的用户才能在 "users/all" 上提出请求,但基本用户也可以。
这是我的安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/users/**").permitAll()
.antMatchers( "/users/all").authenticated().anyRequest().hasAnyRole("ADMIN")
.antMatchers("/users/me").authenticated().anyRequest().hasAnyRole("ADMIN", "BASIC_USER")
.and()
.formLogin().disable()
.httpBasic();
}
This is the request from Postman
为什么我可以用基本用户提出请求?
如果我按这个顺序排列它们:
.antMatchers( "/users/all").authenticated().anyRequest().hasAnyRole("ADMIN")
.antMatchers("/users/me").authenticated().anyRequest().hasAnyRole("ADMIN", "BASIC_USER")
.antMatchers(HttpMethod.POST, "/users/**").permitAll()
同样的事情,但是 /me 请求不再起作用了。
/all request
/me request
现在 /me 请求响应是 403。
你能改变线路吗,管理员限制是上限?
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.user.getRoles().stream().map(role -> new SimpleGrantedAuthority(String.format("ROLE_%s", role.getRole()))).collect(Collectors.toList());
}
我将角色更改为role.getRole()
只有具有管理员角色的用户才能在 "users/all" 上提出请求,但基本用户也可以。 这是我的安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/users/**").permitAll()
.antMatchers( "/users/all").authenticated().anyRequest().hasAnyRole("ADMIN")
.antMatchers("/users/me").authenticated().anyRequest().hasAnyRole("ADMIN", "BASIC_USER")
.and()
.formLogin().disable()
.httpBasic();
}
This is the request from Postman
为什么我可以用基本用户提出请求?
如果我按这个顺序排列它们:
.antMatchers( "/users/all").authenticated().anyRequest().hasAnyRole("ADMIN")
.antMatchers("/users/me").authenticated().anyRequest().hasAnyRole("ADMIN", "BASIC_USER")
.antMatchers(HttpMethod.POST, "/users/**").permitAll()
同样的事情,但是 /me 请求不再起作用了。
/all request /me request
现在 /me 请求响应是 403。
你能改变线路吗,管理员限制是上限?
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.user.getRoles().stream().map(role -> new SimpleGrantedAuthority(String.format("ROLE_%s", role.getRole()))).collect(Collectors.toList());
}
我将角色更改为role.getRole()