Spring 安全过滤器如何与自定义身份验证一起工作,以及如何将其与 Servlet 过滤器结合使用?



所以我有一个关于Spring Security的问题。所以我想使用自定义标头检查身份验证,然后我想检查自定义标头中给出的令牌到 redis 值,并在抽象身份验证令牌的自定义实现中将数据对象设置为凭据。 我已经按照这个 web 中的教程:https://shout.setfive.com/2015/11/02/spring-boot-authentication-with-custom-http-header/,但我无法更新 SecurityContextHolder.getContext() 中的身份验证接口(我在身份验证接口的实现中设置了凭据,但是当我在服务中获取它时,凭据为空)。

我还发现了其他问题,我实际上想像这样订购过滤器:

ExceptionHandlerFilter (to catch exception error in the filter) -> Other filter or CustomWebSecurityConfigurerAdapter. 

但是当 url 与 antMatcher 匹配时,我发现应用程序跳过了 ExceptionHandlerFilter。

我对此感到非常困惑,找不到更好的教程来使用 Spring 安全性实现自定义身份验证。所以我想问一下你们是否可以告诉我Spring Security是如何工作的,以及如何将其与过滤器结合使用?

这是我的第一个过滤器来捕获异常

@Component
@Order(0)
public class ExceptionHandlerFilter extends OncePerRequestFilter {
private JaminExceptionHandler exceptionHandler;
private ObjectMapper objectMapper = new ObjectMapper();
@Autowired
public ExceptionHandlerFilter(JaminExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (Throwable exception) {
ResponseEntity<?> responseEntity = this.exceptionHandler.handleException(exception, request);
response.setStatus(responseEntity.getStatusCode().value());
response.setHeader("Content-Type", "application/json");
response.getWriter().write(this.objectMapper.writeValueAsString(responseEntity.getBody()));
}
}
}

这是我的身份验证过滤器

@Component
public class AuthFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String token = request.getHeader("J-Auth");
if (token != null) {
Authentication auth = new JaminAuthenticationToken(token);
SecurityContextHolder.getContext().setAuthentication(auth);
filterChain.doFilter(request, response);
} else {
throw new JaminException("Not authorized", JaminExceptionType.NOT_AUTHORIZED, HttpStatus.UNAUTHORIZED);
}
}
}

身份验证提供程序

@Component
public class JaminAuthenticationProvider implements AuthenticationProvider {
private RedisTemplate<String, String> authRedis;
private ObjectMapper objectMapper = new ObjectMapper();
@Autowired
public JaminAuthenticationProvider(@Qualifier("authRedis") RedisTemplate<String, String> authRedis) {
this.authRedis = authRedis;
}
private UserDTO getUserDTO(String token) throws IOException {
String userData = this.authRedis.opsForValue().get(token);
if (userData == null) {
throw new JaminException("Not authorized", JaminExceptionType.NOT_AUTHORIZED, HttpStatus.UNAUTHORIZED);
}
return this.objectMapper.readValue(userData, UserDTO.class);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
JaminAuthenticationToken auth = (JaminAuthenticationToken) authentication;
try {
UserDTO userDTO = this.getUserDTO(auth.getToken());
auth.setCredentials(userDTO);
return auth;
} catch (IOException e) {
e.printStackTrace();
}
throw new JaminException("Not authorized", JaminExceptionType.NOT_AUTHORIZED, HttpStatus.UNAUTHORIZED);
}
@Override
public boolean supports(Class<?> authentication) {
return JaminAuthenticationToken.class.isAssignableFrom(authentication);
}
}

WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
@Order(1)
public class JaminSecurityAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private JaminAuthenticationProvider jaminAuthenticationProvider;
private void disableDefaultSecurity(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.csrf().disable();
http.formLogin().disable();
http.logout().disable();
http.httpBasic().disable();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
this.disableDefaultSecurity(http);
http.antMatcher("/auth/check")
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterBefore(new AuthFilter(), BasicAuthenticationFilter.class);
//        http.authorizeRequests().anyRequest().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(jaminAuthenticationProvider);
}
}

Spring Security有一些"之前和之后"的步骤。有一些处理程序可以提供帮助。我不知道你的代码,但如果你可以让你的身份验证正常,也许你只需要扩展一个 SuccessHandler 并在那里设置身份验证,就像我在我的博客项目中所做的那样:

if(checkEmail(authentication)) {
val adminRole = SimpleGrantedAuthority("ROLE_ADMIN")
val oldAuthorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities()
val updateAuthorities = mutableListOf<GrantedAuthority>()
updateAuthorities.add(adminRole)
updateAuthorities.addAll(oldAuthorities)
SecurityContextHolder.getContext().setAuthentication(UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                          authentication.getCredentials(),
                          updateAuthorities))
}

关于过滤器,也许你可以在这里找到答案。我不喜欢使用过滤器和拦截器,但有时它们确实是必要的。

相关内容

  • 没有找到相关文章

最新更新