我一直在我的控制器方法上使用带有@PreAuthorize的spring security.我的理由是我希望授权检查在一个层中可预测地发生,并且在请求中尽可能早.但是,我刚刚阅读了spring security 3文档,并看到他们建议在服务层上应用方法级安全性(但他们没有说明原因).
我的问题是:应该在控制器层或服务层应用spring安全方法级别注释吗?(或"两者",或"它取决于"?)更重要的是:为什么?
使用@EnableGlobalMethodSecurity(prePostEnabled = true)它似乎
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
}
Run Code Online (Sandbox Code Playgroud)
@PreAuthorized 没有效果:
@PreAuthorize("permitAll()")
@RequestMapping(value = "/users/change-email", method = RequestMethod.GET)
public void changeEmail() {
// ..
}
Run Code Online (Sandbox Code Playgroud)
我还将注释移到了服务层,结果相同:
@PreAuthorize("permitAll()")
@Transactional
public void changeEmail(HttpServletResponse response, String token) throws IOException {
// ..
}
Run Code Online (Sandbox Code Playgroud)
我不清楚为什么 - 有什么想法吗?
这是我如何配置我的ResourceServerConfigurerAdapter:
@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(new AuthFailureHandler())
.and()
.authorizeRequests()
.anyRequest()
.authenticated(); …Run Code Online (Sandbox Code Playgroud) java spring spring-security spring-boot spring-security-oauth2