Search in sources :

Example 21 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project incubator-atlas by apache.

the class AtlasKnoxSSOAuthenticationFilter method doFilter.

/*
     * doFilter of AtlasKnoxSSOAuthenticationFilter is the first in the filter list so in this it check for the request
     * if the request is from browser and sso is enabled then it process the request against knox sso
     * else if it's ssoenable and the request is with local login string then it show's the appropriate msg
     * else if ssoenable is false then it contiunes with further filters as it was before sso
     */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
    responseWrapper.setHeader("X-Frame-Options", "DENY");
    if (!ssoEnabled) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox doFilter {}", httpRequest.getRequestURI());
    }
    if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) {
        servletRequest.setAttribute("ssoEnabled", false);
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    if (jwtProperties == null || isAuthenticated()) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox ssoEnabled  {} {}", ssoEnabled, httpRequest.getRequestURI());
    }
    // if jwt properties are loaded and is current not authenticated then it will go for sso authentication
    // Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    String serializedJWT = getJWTFromCookie(httpRequest);
    // if we get the hadoop-jwt token from the cookies then will process it further
    if (serializedJWT != null) {
        SignedJWT jwtToken = null;
        try {
            jwtToken = SignedJWT.parse(serializedJWT);
            boolean valid = validateToken(jwtToken);
            // if the public key provide is correct and also token is not expired the process token
            if (valid) {
                String userName = jwtToken.getJWTClaimsSet().getSubject();
                LOG.info("SSO login user : {} ", userName);
                // if we get the userName from the token then log into atlas using the same user
                if (userName != null && !userName.trim().isEmpty()) {
                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    authenticationProvider.setSsoEnabled(ssoEnabled);
                    Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
                filterChain.doFilter(servletRequest, httpServletResponse);
            } else {
                // if the token is not valid then redirect to knox sso
                redirectToKnox(httpRequest, httpServletResponse, filterChain);
            }
        } catch (ParseException e) {
            LOG.warn("Unable to parse the JWT token", e);
            redirectToKnox(httpRequest, httpServletResponse, filterChain);
        }
    } else {
        redirectToKnox(httpRequest, httpServletResponse, filterChain);
    }
}
Also used : User(org.springframework.security.core.userdetails.User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SignedJWT(com.nimbusds.jwt.SignedJWT) HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) ParseException(java.text.ParseException)

Example 22 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationProcessingFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;
    try {
        Authentication authentication = tokenExtractor.extract(request);
        if (authentication == null) {
            if (stateless && isAuthenticated()) {
                if (debug) {
                    logger.debug("Clearing security context.");
                }
                SecurityContextHolder.clearContext();
            }
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
            }
            Authentication authResult = authenticationManager.authenticate(authentication);
            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }
            eventPublisher.publishAuthenticationSuccess(authResult);
            SecurityContextHolder.getContext().setAuthentication(authResult);
        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();
        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed), new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
        authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(failed.getMessage(), failed));
        return;
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 23 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project atlas by apache.

the class AtlasKnoxSSOAuthenticationFilter method doFilter.

/*
     * doFilter of AtlasKnoxSSOAuthenticationFilter is the first in the filter list so in this it check for the request
     * if the request is from browser and sso is enabled then it process the request against knox sso
     * else if it's ssoenable and the request is with local login string then it show's the appropriate msg
     * else if ssoenable is false then it contiunes with further filters as it was before sso
     */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
    responseWrapper.setHeader("X-Frame-Options", "DENY");
    responseWrapper.setHeader("X-Content-Type-Options", "nosniff");
    responseWrapper.setHeader("X-XSS-Protection", "1; mode=block");
    responseWrapper.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    if (!ssoEnabled) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox doFilter {}", httpRequest.getRequestURI());
    }
    if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) {
        servletRequest.setAttribute("ssoEnabled", false);
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    if (jwtProperties == null || isAuthenticated()) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox ssoEnabled  {} {}", ssoEnabled, httpRequest.getRequestURI());
    }
    // if jwt properties are loaded and is current not authenticated then it will go for sso authentication
    // Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    String serializedJWT = getJWTFromCookie(httpRequest);
    // if we get the hadoop-jwt token from the cookies then will process it further
    if (serializedJWT != null) {
        SignedJWT jwtToken = null;
        try {
            jwtToken = SignedJWT.parse(serializedJWT);
            boolean valid = validateToken(jwtToken);
            // if the public key provide is correct and also token is not expired the process token
            if (valid) {
                String userName = jwtToken.getJWTClaimsSet().getSubject();
                LOG.info("SSO login user : {} ", userName);
                // if we get the userName from the token then log into atlas using the same user
                if (userName != null && !userName.trim().isEmpty()) {
                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    authenticationProvider.setSsoEnabled(ssoEnabled);
                    Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
                filterChain.doFilter(servletRequest, httpServletResponse);
            } else {
                // if the token is not valid then redirect to knox sso
                redirectToKnox(httpRequest, httpServletResponse, filterChain);
            }
        } catch (ParseException e) {
            LOG.warn("Unable to parse the JWT token", e);
            redirectToKnox(httpRequest, httpServletResponse, filterChain);
        }
    } else {
        redirectToKnox(httpRequest, httpServletResponse, filterChain);
    }
}
Also used : User(org.springframework.security.core.userdetails.User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SignedJWT(com.nimbusds.jwt.SignedJWT) HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) ParseException(java.text.ParseException)

Example 24 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project webcert by sklintyg.

the class WebCertUserServiceTest method applyUserToThreadLocalCtx.

private void applyUserToThreadLocalCtx(final WebCertUser user) {
    Authentication auth = new AbstractAuthenticationToken(null) {

        @Override
        public Object getCredentials() {
            return null;
        }

        @Override
        public Object getPrincipal() {
            return user;
        }
    };
    SecurityContextHolder.getContext().setAuthentication(auth);
}
Also used : AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) Authentication(org.springframework.security.core.Authentication)

Example 25 with AbstractAuthenticationToken

use of org.springframework.security.authentication.AbstractAuthenticationToken in project motech by motech.

the class UserContextServiceImpl method getToken.

private AbstractAuthenticationToken getToken(Authentication authentication, MotechUser user) {
    AbstractAuthenticationToken token = null;
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken oldToken = (UsernamePasswordAuthenticationToken) authentication;
        token = new UsernamePasswordAuthenticationToken(oldToken.getPrincipal(), oldToken.getCredentials(), authoritiesService.authoritiesFor(user));
    } else if (authentication instanceof OpenIDAuthenticationToken) {
        OpenIDAuthenticationToken oldToken = (OpenIDAuthenticationToken) authentication;
        token = new OpenIDAuthenticationToken(oldToken.getPrincipal(), authoritiesService.authoritiesFor(user), user.getOpenId(), oldToken.getAttributes());
    }
    return token;
}
Also used : AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) OpenIDAuthenticationToken(org.springframework.security.openid.OpenIDAuthenticationToken) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Aggregations

AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)37 GrantedAuthority (org.springframework.security.core.GrantedAuthority)19 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)17 Jwt (org.springframework.security.oauth2.jwt.Jwt)16 Test (org.junit.jupiter.api.Test)15 Authentication (org.springframework.security.core.Authentication)13 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)12 WebAuthenticationDetails (org.springframework.security.web.authentication.WebAuthenticationDetails)10 User (org.springframework.security.core.userdetails.User)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 UserDetails (org.springframework.security.core.userdetails.UserDetails)7 SignedJWT (com.nimbusds.jwt.SignedJWT)3 ParseException (java.text.ParseException)3 ArrayList (java.util.ArrayList)3 RangerAuthenticationProvider (org.apache.ranger.security.handler.RangerAuthenticationProvider)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 Collection (java.util.Collection)2