因此,在更高级别上,当使用 jwt 作为身份验证时,Spring Security 应用于控制器级别。首先,您需要添加一个将扩展 WebSecurityConfigurerAdapter 的安全配置(这对于基于 http 的安全性很常见),并且在该类中您需要定义配置方法,例如:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().disable()
.csrf().disable() // IF your clients connect without a cookie based, this will be fine
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/register", "/login","/your_open_endpoints_etc").permitAll()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}
然后在扩展OncePerRequestFilter的过滤器类中,你可以像这样定义do过滤器,你必须在Spring认证上下文中设置UsernamePasswordAuthenticationFilter实例:
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
logger.info("do filter...");
String token = jwtProvider.getTokenFromRequest((HttpServletRequest) httpServletRequest);
try{
if (token != null && jwtProvider.validateToken(token)) {
String username = jwtProvider.getUsernameFromToken(token);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null, jwtProvider.getAuthorities(token));
SecurityContextHolder.getContext().setAuthentication(auth);
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
catch (RuntimeException e)
{
// Some general Exception handling that will wrap and send as HTTP Response
}
}
进一步检查扩展过滤器,它们可能会根据您的要求进行更改
最后在休息端点你可以像这样保护:
@PreAuthorize("hasRole('ROLE_YOURROLE')")
@GetMapping(path = "/your_secured_endpoint", consumes = "application/json",
produces = "application/json")
public ResponseEntity<List<SomePOJOObject>> getAllAppointmentsForPatient()
{
return new ResponseEntity<>(thatSomePOJOObjectListYouWant, HttpStatus.OK);
}