带有@Secured注释的安全MVC控制器方法



以下是我使用SpringBoot制作的API的单个安全配置:

@Configuration
@EnableWebSecurity
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenAuthenticationService tokenAuthenticationService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/static/**").permitAll()
                .antMatchers(HttpMethod.POST, "/api/user/registration").permitAll()
                .antMatchers(HttpMethod.POST, "/api/user/authentication").permitAll()
                .anyRequest().authenticated().and()
            .addFilterBefore(new TokenLoginFilter("/api/user/authentication", authenticationManagerBean(), tokenAuthenticationService), 
                    UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(new TokenAuthenticationFilter(tokenAuthenticationService),UsernamePasswordAuthenticationFilter.class);
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }
}

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

@RestController
@RequestMapping("/api/resource/")
@Secured("ROLE_ANONYMOUS") //as default role
public class ResourceController {
    ...
    @Secured("ROLE_USER")
    some_method...
}

但是当我作为匿名用户执行/api/resource/*请求时,应用程序响应403状态码,但我期望方法调用。看起来@Secured注释对授权没有影响,并且所有控制器方法只允许ROLE_USER使用。

TokenAuthenticationFilter只在令牌存在时才执行操作,所以我猜它没有作用。

    @Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) req;
    String token = httpServletRequest.getHeader(TokenAuthenticationService.AUTH_HEADER_NAME);
    if (token != null) {
        try {
            SecurityContextHolder.getContext()
                    .setAuthentication(tokenAuthenticationService.verifyToken(new TokenAuthentication(token)));
        } catch (AuthenticationException e) {
            ((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }
    chain.doFilter(req, res);
}

更新:

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

  1. 使用@Secured注释并将方法访问级别信息分散到控制器类中,这可能会导致将来随着API的增长而难以确定方法访问级别的情况。

  2. 保持所有的方法访问信息在同一个地方(配置),但必须支持@RequestMapping值与配置中的url相等

你认为哪一个是最好的方法,或者如果我错过了什么请告诉我?

为了告诉Spring监视@Secured注释,你必须在Security配置中添加以下内容:

@EnableGlobalMethodSecurity(securedEnabled = true)

最新更新