使用@Secured注释保护MVC Controller方法

前端之家收集整理的这篇文章主要介绍了使用@Secured注释保护MVC Controller方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这是我使用SpringBoot制作的API的单一安全配置:

  1. @Configuration
  2. @EnableWebSecurity
  3. @EnableWebMvcSecurity
  4. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  5. @Autowired
  6. private UserService userService;
  7. @Autowired
  8. private TokenAuthenticationService tokenAuthenticationService;
  9. @Override
  10. protected void configure(HttpSecurity http) throws Exception {
  11. http
  12. .csrf().disable()
  13. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
  14. .authorizeRequests()
  15. .antMatchers("/").permitAll()
  16. .antMatchers("/static/**").permitAll()
  17. .antMatchers(HttpMethod.POST,"/api/user/registration").permitAll()
  18. .antMatchers(HttpMethod.POST,"/api/user/authentication").permitAll()
  19. .anyRequest().authenticated().and()
  20. .addFilterBefore(new TokenLoginFilter("/api/user/authentication",authenticationManagerBean(),tokenAuthenticationService),UsernamePasswordAuthenticationFilter.class)
  21. .addFilterBefore(new TokenAuthenticationFilter(tokenAuthenticationService),UsernamePasswordAuthenticationFilter.class);
  22. }
  23. @Override
  24. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  25. auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
  26. }
  27. }

所有URL都映射到spring web mvc控制器,我想手动指定控制器及其方法的访问级别,如下所示:

  1. @RestController
  2. @RequestMapping("/api/resource/")
  3. @Secured("ROLE_ANONYMOUS") //as default role
  4. public class ResourceController {
  5. ...
  6. @Secured("ROLE_USER")
  7. some_method...
  8. }

但是当我以匿名用户身份执行/ api / resource / *请求时,应用程序会响应403状态代码,但我希望方法调用.看起来@Secured注释对授权没有影响,并且所有控制器方法仅允许ROLE_USER.

TokenAuthenticationFilter仅在令牌存在时执行操作,因此我猜它没有任何效果.

  1. @Override
  2. public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException {
  3. HttpServletRequest httpServletRequest = (HttpServletRequest) req;
  4. String token = httpServletRequest.getHeader(TokenAuthenticationService.AUTH_HEADER_NAME);
  5. if (token != null) {
  6. try {
  7. SecurityContextHolder.getContext()
  8. .setAuthentication(tokenAuthenticationService.verifyToken(new TokenAuthentication(token)));
  9. } catch (AuthenticationException e) {
  10. ((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  11. return;
  12. }
  13. }
  14. chain.doFilter(req,res);
  15. }

更新:

考虑到这个问题下面的评论,我意识到@Secured注释是全局方法安全概念的一部分,而不是Web安全的一般部分.现在我有以下权衡:

>使用@Secured注释并将方法访问级别信息分布在Controller类上,这可能导致使用API​​增长的难以确定的方法访问级别.
>将所有方法访问信息保存在同一位置(config),但必须在config中支持@RequestMapping值与url的相等性.

您认为哪种方法最好,或者如果我错过了什么请告诉我?

最佳答案
为了告诉Spring注意@Secured注释,在Security Config上必须添加以下内容

  1. @EnableGlobalMethodSecurity(securedEnabled = true)

猜你在找的Spring相关文章