Spring Security custom authentication filter using Java Config

前端 未结 1 1256
花落未央
花落未央 2020-12-23 11:05

I\'m trying to configure Spring Security using Java config in a basic web application to authenticate against an external web service using an encrypted token provided in a

相关标签:
1条回答
  • 2020-12-23 11:30

    I've resolved my issue by performing a check on the authentication status in the filter before involking the authentication provider....

    Config

    .and()
        .addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class)
        .authenticationProvider(tokenAuthenticationProvider)
        .exceptionHandling().authenticationEntryPoint(tokenEntryPoint)
    

    Filter

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {
    
        logger.debug(this + "received authentication request from " + request.getRemoteHost() + " to " + request.getLocalName());
    
        if (request instanceof HttpServletRequest) {
            if (isAuthenticationRequired()) {
                // extract token from header
                OEWebToken token = extractToken(request);
    
                // dump token into security context (for authentication-provider to pick up)
                SecurityContextHolder.getContext().setAuthentication(token);
            } else {
                logger.debug("session already contained valid Authentication - not checking again");
            }
        }
    
        chain.doFilter(request, response);
    }
    
        private boolean isAuthenticationRequired() {
        // apparently filters have to check this themselves.  So make sure they have a proper AuthenticatedAccount in their session.
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if ((existingAuth == null) || !existingAuth.isAuthenticated()) {
            return true;
        }
    
        if (!(existingAuth instanceof AuthenticatedAccount)) {
            return true;
        }
    
        // current session already authenticated
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题