Spring Security过滤器如何与自定义身份验证一起使用,以及如何与Servlet过滤器结合使用?

时间:2019-07-10 19:10:38

标签: spring spring-boot spring-security

所以我有一个关于Spring Security的问题。因此,我想使用自定义标头检查身份验证,然后我要检查自定义标头中给定的令牌是否为redis值,并在抽象身份验证令牌的自定义实现中将数据对象设置为凭据。 我已经按照以下网址中的教程进行操作: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 Security实现自定义身份验证中找到更好的教程。所以我想问问你们是否可以告诉我Spring Security的工作原理以及如何将其与Filter结合?

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

@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);
    }
}

1 个答案:

答案 0 :(得分:0)

Spring Security具有一些“前后” steps。有一些处理程序可以提供帮助。我不知道您的代码,但是如果您可以通过身份验证,也许您只需要扩展一个SuccessHandler并在那里设置身份验证即可,就像我在blog project中所做的那样:

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))
}

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