加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:46:07 所属栏目:大数据 来源:网络整理
导读:这是我使用SpringBoot制作的API的单一安全配置: @Configuration@EnableWebSecurity@EnableWebMvcSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Autowired private TokenAuthe

这是我使用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安全的一般部分.现在我有以下权衡:

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

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

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

@EnableGlobalMethodSecurity(securedEnabled = true)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读