我想保护我的端点,因此只有角色为READ
的用户才能访问某个资源。这些是我的配置:
控制器:
@RestController
@RequestMapping("/api/status")
public class StatusController {
@RequestMapping(method = RequestMethod.GET)
@Secured("READ")
Map<String, Object> getSecureStatus() {
Map<String, Object> statusMap = new LinkedHashMap<>();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
statusMap.put("auth", auth);
return statusMap;
}
}
WebSecurityConfigurerAdapter:
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// .antMatchers("/").permitAll()
.antMatchers("/api/**").authenticated()
.and()
.httpBasic();
}
}
GlobalAuthenticationConfigurerAdapter:
@Configuration
public class AuthenticationManagerConfig extends
GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("teddy").password("password").roles("USER");
}
}
我认为Teddy不能访问该资源,因为他的角色是 USER 而不是 READ 。
但是通过这个电话,Teddy无论如何得到了他的信息:
curl -u teddy:password 'http://localhost:8080/api/status/'
:
{
"auth": {
"details": {
"remoteAddress": "127.0.0.1",
"sessionId": null
},
"authorities": [
{
"authority": "ROLE_USER"
}
],
"authenticated": true,
"principal": {
"password": null,
"username": "teddy",
"authorities": [
{
"authority": "ROLE_USER"
}
],
"accountNonExpired": true,
"accountNonLocked": true,
"credentialsNonExpired": true,
"enabled": true
},
"credentials": null,
"name": "teddy"
}
}
我错过了什么?
修改:已移除.antMatchers("/").permitAll()
答案 0 :(得分:1)
可能是因为你正在使用.antMatchers("/").permitAll()
它告诉你,你正在允许每一个请求。
尝试从配置中删除它。
答案 1 :(得分:0)
我发现了错误。我忽略了getSecureStatus()
没有明确定义public
。此代码修复了它:
@RestController
@RequestMapping("/api/status")
public class StatusController {
@RequestMapping(method = RequestMethod.GET)
@Secured("READ")
public Map<String, Object> getSecureStatus() {
Map<String, Object> statusMap = new LinkedHashMap<>();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
statusMap.put("auth", auth);
return statusMap;
}
}