Search in sources :

Example 21 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project ma-core-public by infiniteautomation.

the class MangoTokenAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!(authentication instanceof BearerAuthenticationToken)) {
        return null;
    }
    String bearerToken = (String) authentication.getCredentials();
    User user;
    Jws<Claims> jws;
    try {
        jws = tokenAuthenticationService.parse(bearerToken);
        user = tokenAuthenticationService.verify(jws);
    } catch (ExpiredJwtException e) {
        throw new CredentialsExpiredException(e.getMessage(), e);
    } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
        // assume that this is not a JWT, allow the next AuthenticationProvider to process it
        return null;
    } catch (SignatureException | MissingClaimException | IncorrectClaimException e) {
        throw new BadCredentialsException(e.getMessage(), e);
    } catch (NotFoundException e) {
        throw new BadCredentialsException("Invalid username", e);
    } catch (Exception e) {
        throw new InternalAuthenticationServiceException(e.getMessage(), e);
    }
    userDetailsChecker.check(user);
    if (log.isDebugEnabled()) {
        log.debug("Successfully authenticated user using JWT token, header: " + jws.getHeader() + ", body: " + jws.getBody());
    }
    return new PreAuthenticatedAuthenticationToken(user, bearerToken, user.getAuthorities());
}
Also used : User(com.serotonin.m2m2.vo.User) Claims(io.jsonwebtoken.Claims) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) NotFoundException(com.serotonin.m2m2.vo.exception.NotFoundException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) SignatureException(io.jsonwebtoken.SignatureException) IncorrectClaimException(io.jsonwebtoken.IncorrectClaimException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) NotFoundException(com.serotonin.m2m2.vo.exception.NotFoundException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) MissingClaimException(io.jsonwebtoken.MissingClaimException) IncorrectClaimException(io.jsonwebtoken.IncorrectClaimException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) SignatureException(io.jsonwebtoken.SignatureException) AuthenticationException(org.springframework.security.core.AuthenticationException) MissingClaimException(io.jsonwebtoken.MissingClaimException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException)

Example 22 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project ma-core-public by infiniteautomation.

the class MangoWebSocketPublisher method getUser.

/**
 * Gets the Mango user for a WebSocketSession. If there is no user and closeOnLogout is true then the WebSocketSession is closed.
 *
 * Will return null when:
 * <ul>
 *   <li>There never was a user</li>
 *   <li>Session was invalidated (user logged out, admin disabled them or changed their password)</li>
 *   <li>JWT auth token has expired, been revoked or the private/public keys changed</li>
 * </ul>
 *
 * TODO Mango 3.4 store the user and authentication in the WebSocketSession attributes using the handshake intercepter.
 * Use the sessionDestroyed/user modified/JWT key changed events to replace the user in the attributes or close the session as appropriate.
 * If we have a user modified and JWT key changed event we don't have to re-parse and re-validate the JWT token every time.
 *
 * @param session
 * @return user or null
 */
protected User getUser(WebSocketSession session) {
    User user = null;
    Authentication authentication = null;
    // get the user at the time of HTTP -> websocket upgrade
    Principal principal = session.getPrincipal();
    if (principal instanceof Authentication) {
        authentication = (Authentication) principal;
        Object authenticationPrincipal = authentication.getPrincipal();
        if (authenticationPrincipal instanceof User) {
            user = (User) authenticationPrincipal;
        }
    }
    // user should never be null as long as the websocket URLs are protected by Spring Security
    if (user != null) {
        String httpSessionId = httpSessionIdForSession(session);
        if (httpSessionId != null) {
            SessionInformation sessionInformation = sessionRegistry.getSessionInformation(httpSessionId);
            if (sessionInformation != null && !sessionInformation.isExpired()) {
                // we dont have to check if the user is disabled etc as the session would be invalidated if the user was modified
                return user;
            }
        }
        // no valid session, check for an authentication token
        if (authentication instanceof PreAuthenticatedAuthenticationToken) {
            PreAuthenticatedAuthenticationToken token = (PreAuthenticatedAuthenticationToken) authentication;
            Object credentials = token.getCredentials();
            if (credentials instanceof String) {
                String jwtString = (String) credentials;
                BearerAuthenticationToken bearerToken = new BearerAuthenticationToken(jwtString);
                /**
                 * Re-authenticate the token as
                 * a) The user might have been disabled
                 * b) The user's tokens might have been revoked
                 * c) The JWT private key might have changed
                 */
                try {
                    Authentication newAuthentication = this.authenticationManager.authenticate(bearerToken);
                    Object newPrincipal = newAuthentication.getPrincipal();
                    if (newPrincipal instanceof User) {
                        return (User) newPrincipal;
                    }
                } catch (AuthenticationException e) {
                // token is no longer valid
                // do nothing, just return null
                }
            }
        }
    }
    // TODO Mango 3.4 don't close sessions here
    if (this.closeOnLogout) {
        this.closeSession(session, NOT_AUTHENTICATED);
    }
    return null;
}
Also used : SessionInformation(org.springframework.security.core.session.SessionInformation) User(com.serotonin.m2m2.vo.User) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) BearerAuthenticationToken(com.serotonin.m2m2.web.mvc.spring.security.authentication.BearerAuthenticationToken) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Principal(java.security.Principal)

Example 23 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project syndesis by syndesisio.

the class UserHandlerTest method successfulWhoAmIWithoutFullName.

@Test
public void successfulWhoAmIWithoutFullName() {
    openShiftServer.expect().get().withPath("/oapi/v1/users/~").andReturn(200, new UserBuilder().withNewMetadata().withName("testuser").and().build()).once();
    SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken("testuser", "doesn'tmatter"));
    UserHandler userHandler = new UserHandler(null, new OpenShiftServiceImpl(openShiftServer.getOpenshiftClient(), null));
    User user = userHandler.whoAmI();
    Assertions.assertThat(user).isNotNull();
    Assertions.assertThat(user.getUsername()).isEqualTo("testuser");
    Assertions.assertThat(user.getFullName()).isEmpty();
}
Also used : User(io.syndesis.common.model.user.User) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) OpenShiftServiceImpl(io.syndesis.server.openshift.OpenShiftServiceImpl) UserBuilder(io.fabric8.openshift.api.model.UserBuilder) Test(org.junit.Test)

Example 24 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project credhub by cloudfoundry-incubator.

the class OAuth2ExtraValidationFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    Authentication authentication = tokenExtractor.extract(request);
    try {
        if (authentication != null) {
            String token = (String) authentication.getPrincipal();
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
            Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
            String issuer = (String) additionalInformation.getOrDefault("iss", "");
            if (!issuer.equals(oAuth2IssuerService.getIssuer())) {
                tokenStore.removeAccessToken(accessToken);
                String errorMessage = messageSourceAccessor.getMessage("error.oauth.invalid_issuer");
                throw new OAuth2Exception(errorMessage);
            // AuthenticationServiceException authException = new AuthenticationServiceException(errorMessage);
            // oAuth2AuthenticationExceptionHandler.commence(request, response, authException);
            }
        }
        filterChain.doFilter(request, response);
    } catch (OAuth2Exception exception) {
        SecurityContextHolder.clearContext();
        InsufficientAuthenticationException authException = new InsufficientAuthenticationException(exception.getMessage(), exception);
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(exception.getMessage(), exception), new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
        oAuth2AuthenticationExceptionHandler.commence(request, response, authException);
    }
}
Also used : Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 25 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project credhub by cloudfoundry-incubator.

the class UserContextFactoryTest method setupMtlsMock.

private PreAuthenticatedAuthenticationToken setupMtlsMock() {
    X509Certificate certificate = mock(X509Certificate.class);
    Principal principal = mock(Principal.class);
    PreAuthenticatedAuthenticationToken token = mock(PreAuthenticatedAuthenticationToken.class);
    when(certificate.getSubjectDN()).thenReturn(principal);
    when(principal.getName()).thenReturn("CN=test_cn,OU=app:e054393e-c9c3-478b-9047-e6d05c307bf2");
    when(certificate.getNotAfter()).thenReturn(Date.from(Instant.ofEpochSecond(1413538464L)));
    when(certificate.getNotBefore()).thenReturn(Date.from(Instant.ofEpochSecond(1413495264L)));
    when(token.getCredentials()).thenReturn(certificate);
    return token;
}
Also used : PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) X509Certificate(java.security.cert.X509Certificate) Principal(java.security.Principal)

Aggregations

PreAuthenticatedAuthenticationToken (org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)64 Authentication (org.springframework.security.core.Authentication)36 Test (org.junit.Test)14 SecurityContext (org.springframework.security.core.context.SecurityContext)11 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)7 User (ca.corefacility.bioinformatics.irida.model.user.User)6 AuthenticationException (org.springframework.security.core.AuthenticationException)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)5 AnonymousAuthenticationToken (org.springframework.security.authentication.AnonymousAuthenticationToken)4 MidpointAuthentication (com.evolveum.midpoint.authentication.api.config.MidpointAuthentication)3 ModuleAuthentication (com.evolveum.midpoint.authentication.api.config.ModuleAuthentication)3 X509Certificate (java.security.cert.X509Certificate)3 ArrayList (java.util.ArrayList)3 KeycloakRole (org.keycloak.adapters.springsecurity.account.KeycloakRole)3 OrcidProfileUserDetails (org.orcid.core.oauth.OrcidProfileUserDetails)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)3 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)3 PasswordAuthenticationContext (com.evolveum.midpoint.model.api.context.PasswordAuthenticationContext)2