【发布时间】:2019-08-02 17:15:14
【问题描述】:
@PreAuthorize 和 isAnonymous() 似乎不适用于 Spring(实际上是 Spring Boot)。
这是我的代码:
@RestController
@RequiredArgsConstructor
public class ValidateCodeController {
private final @NonNull ValidateCodeProcessorHolder validateCodeProcessorHolder;
// @PreAuthorize("permitAll()")
@PreAuthorize("isAnonymous()")
@GetMapping(SecurityConstants.VALIDATE_CODE_URL_PREFIX + "/{type}")
public void creatCode(HttpServletRequest request, HttpServletResponse response,
@PathVariable String type) throws Exception {
validateCodeProcessorHolder.findValidateCodeProcessor(type)
.create(new ServletWebRequest(request, response));
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/test")
public HttpEntity<?> resource() {
return ResponseEntity.ok(123);
}
}
但我收到了 HTTP 403 Forbidden 响应:
{
"timestamp": "2019-08-02T08:36:50.859+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/code/email"
}
和/test
{
"timestamp": "2019-08-02T08:36:48.202+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/test"
}
在我的配置文件中。
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// If use this, it can work.
// .antMatchers("/code/*").permitAll()
.anyRequest()
.authenticated()
.and()
.csrf()
.disable();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
我希望得到资源。
【问题讨论】:
标签: spring spring-boot spring-security spring-security-oauth2