Search in sources :

Example 56 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project midpoint by Evolveum.

the class MidpointRequestHeaderAuthenticationFilter method doAuthenticate.

private void doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    Authentication authResult;
    Object principal = getPreAuthenticatedPrincipal(request);
    Object credentials = getPreAuthenticatedCredentials(request);
    if (principal == null) {
        AuthenticationException failed = new AuthenticationCredentialsNotFoundException("web.security.provider.invalid.credentials");
        unsuccessfulAuthentication(request, response, failed);
        return;
    }
    try {
        PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(principal, credentials);
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        authResult = authenticationManager.authenticate(authRequest);
        if (sessionRegistry != null) {
            sessionRegistry.registerNewSession(request.getSession().getId(), authResult.getPrincipal());
        }
        successfulAuthentication(request, response, authResult);
    } catch (AuthenticationException failed) {
        unsuccessfulAuthentication(request, response, failed);
    }
}
Also used : AuthenticationCredentialsNotFoundException(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException) AuthenticationException(org.springframework.security.core.AuthenticationException) ModuleAuthentication(com.evolveum.midpoint.authentication.api.config.ModuleAuthentication) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

Example 57 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project midpoint by Evolveum.

the class SecurityContextManagerImpl method setupPreAuthenticatedSecurityContext.

@Override
public void setupPreAuthenticatedSecurityContext(MidPointPrincipal principal) {
    // Make sure that constructor with authorities is used. Otherwise the context will not be authenticated.
    Authentication authentication = new PreAuthenticatedAuthenticationToken(principal, null, principal.getAuthorities());
    setupPreAuthenticatedSecurityContext(authentication);
}
Also used : Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

Example 58 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project midpoint by Evolveum.

the class PasswordProvider method internalAuthentication.

@Override
protected Authentication internalAuthentication(Authentication authentication, List<ObjectReferenceType> requireAssignment, AuthenticationChannel channel, Class<? extends FocusType> focusType) throws AuthenticationException {
    if (authentication.isAuthenticated() && authentication.getPrincipal() instanceof GuiProfiledPrincipal) {
        return authentication;
    }
    String enteredUsername = (String) authentication.getPrincipal();
    LOGGER.trace("Authenticating username '{}'", enteredUsername);
    ConnectionEnvironment connEnv = createEnvironment(channel);
    try {
        Authentication token;
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            String enteredPassword = (String) authentication.getCredentials();
            PasswordAuthenticationContext authContext = new PasswordAuthenticationContext(enteredUsername, enteredPassword, focusType, requireAssignment);
            if (channel != null) {
                authContext.setSupportActivationByChannel(channel.isSupportActivationByChannel());
            }
            token = getEvaluator().authenticate(connEnv, authContext);
        } else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
            token = getEvaluator().authenticateUserPreAuthenticated(connEnv, new PreAuthenticationContext(enteredUsername, focusType, requireAssignment));
        } else {
            LOGGER.error("Unsupported authentication {}", authentication);
            throw new AuthenticationServiceException("web.security.provider.unavailable");
        }
        MidPointPrincipal principal = (MidPointPrincipal) token.getPrincipal();
        LOGGER.debug("User '{}' authenticated ({}), authorities: {}", authentication.getPrincipal(), authentication.getClass().getSimpleName(), principal.getAuthorities());
        return token;
    } catch (AuthenticationException e) {
        LOGGER.info("Authentication failed for {}: {}", enteredUsername, e.getMessage());
        throw e;
    }
}
Also used : PasswordAuthenticationContext(com.evolveum.midpoint.model.api.context.PasswordAuthenticationContext) GuiProfiledPrincipal(com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) PreAuthenticationContext(com.evolveum.midpoint.model.api.context.PreAuthenticationContext) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Example 59 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project spring-security by spring-projects.

the class PreAuthenticatedAuthenticationTokenMixinTests method deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest.

@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws Exception {
    PreAuthenticatedAuthenticationToken deserialized = this.mapper.readValue(PREAUTH_JSON, PreAuthenticatedAuthenticationToken.class);
    assertThat(deserialized).isNotNull();
    assertThat(deserialized.isAuthenticated()).isTrue();
    assertThat(deserialized.getAuthorities()).isEqualTo(this.expected.getAuthorities());
}
Also used : PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 60 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project webofneeds by researchstudio-sat.

the class WonAclAccessDecisionVoter method vote.

@Override
@Transactional
public int vote(final Authentication authentication, final FilterInvocation filterInvocation, final Collection<ConfigAttribute> configAttributes) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    if (configAttributes.stream().map(Object::toString).anyMatch(x -> x.equals("permitAll"))) {
        // check ACLs
        return ACCESS_GRANTED;
    }
    String webId = null;
    AuthToken authToken = null;
    if (authentication instanceof PreAuthenticatedAuthenticationToken) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof WebIdUserDetails) {
            WebIdUserDetails userDetails = (WebIdUserDetails) principal;
            // check if the WebId was verified successfully, otherwise treat as anonymous
            if (authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).filter(r -> "ROLE_WEBID".equals(r)).findAny().isPresent()) {
                // if the webid was not verified, use none
                webId = userDetails.getUsername();
            }
        }
    } else if (authentication instanceof WonAclTokenAuthentication) {
        authToken = (AuthToken) ((WonAclTokenAuthentication) authentication).getDetails();
    }
    if (webId != null && webId.equals(cryptographyService.getDefaultPrivateKeyAlias())) {
        // if the WoN node itself is the requestor, bypass all checks and allow
        if (logger.isDebugEnabled()) {
            logger.debug("Requestor is WonNode itself, authenticated by its WebID. Bypassing any ACL checks");
        }
        WonAclRequestHelper.setWonAclEvaluationContext(filterInvocation.getRequest(), WonAclEvalContext.allowAll());
        return ACCESS_GRANTED;
    }
    String resource = filterInvocation.getRequest().getRequestURL().toString();
    URI resourceUri = null;
    try {
        resourceUri = uriService.toResourceURIIfPossible(new URI(resource));
    } catch (URISyntaxException e) {
        logger.debug("Cannot process ACL for resource {}", resource);
        return ACCESS_DENIED;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Processing WoN ACL for request to resource {}", resourceUri);
    }
    int result = ACCESS_DENIED;
    // perform our hard coded access control checks
    // prepare the legacy implementation in case the target atom(s) have no acl
    // graph
    final List<String> webids = webId != null ? List.of(webId) : Collections.emptyList();
    Supplier<Integer> legacyImpl = () -> {
        if (defaultAccessControlRules.isAccessPermitted(resource, webids)) {
            return ACCESS_GRANTED;
        }
        return ACCESS_DENIED;
    };
    if (WonMessageUriHelper.isLocalMessageURI(resourceUri, uriService.getMessageResourceURIPrefix())) {
        // handle request for message
        result = voteForMessageRequest(webId, authToken, resourceUri, filterInvocation, legacyImpl);
    } else {
        // handle other requests
        result = voteForNonMessageRequest(webId, authToken, resourceUri, filterInvocation, legacyImpl);
    }
    stopWatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("access control check for {} with webid {}, token {} took {} millis, result: {} ", new Object[] { resourceUri, webId, authToken == null ? "(no token)" : "present", stopWatch.getLastTaskTimeMillis(), (result == ACCESS_GRANTED ? "granted" : (result == ACCESS_DENIED ? "denied" : (result == ACCESS_ABSTAIN ? "abstain" : result))) });
    }
    return result;
}
Also used : PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) StopWatch(org.springframework.util.StopWatch) WebIdUserDetails(won.node.springsecurity.userdetails.WebIdUserDetails) Transactional(javax.transaction.Transactional)

Aggregations

PreAuthenticatedAuthenticationToken (org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)60 Authentication (org.springframework.security.core.Authentication)34 Test (org.junit.Test)11 SecurityContext (org.springframework.security.core.context.SecurityContext)10 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 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 PrismObject (com.evolveum.midpoint.prism.PrismObject)2