这是我使用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上必须添加以下内容:
@H_301_47@ 原文链接:https://www.f2er.com/spring/431338.html@EnableGlobalMethodSecurity(securedEnabled = true)