Search in sources :

Example 41 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project herd by FINRAOS.

the class TrustedUserAuthenticationFilter method doHttpFilter.

/**
 * doFilter implementation for an HTTP request and response.
 *
 * @param request the HTTP servlet request.
 * @param response the HTTP servlet response.
 * @param chain the filter chain.
 *
 * @throws IOException if an I/O error occurs.
 * @throws ServletException if a servlet error occurs.
 */
public void doHttpFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    // If security is not enabled, perform allow as trusted user.
    if (!securityHelper.isSecurityEnabled(request)) {
        // If authentication is not there or is not of trusted user type.
        PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(applicationUserBuilder.build(request), "N/A");
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        Authentication authResult = authenticationManager.authenticate(authRequest);
        // The authentication returned so it was successful.
        SecurityContextHolder.getContext().setAuthentication(authResult);
    }
    chain.doFilter(request, response);
}
Also used : Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

Example 42 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project herd by FINRAOS.

the class SecurityHelperTest method testIsGeneratedBy.

@Test
public void testIsGeneratedBy() throws Exception {
    assertFalse(securityHelper.isUserGeneratedByClass(null, null));
    PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(null, null);
    assertFalse(securityHelper.isUserGeneratedByClass(authRequest, null));
}
Also used : PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Test(org.junit.Test) AbstractAppTest(org.finra.herd.app.AbstractAppTest)

Example 43 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project zhcet-web by zhcet-amu.

the class UserDetailService method grantPrivilege.

/**
 * Grants a privilege to user and sets authentication
 * @param user User to be granted a privilege
 * @param privilege String privilege to be granted
 */
void grantPrivilege(User user, String privilege) {
    Authentication auth = new PreAuthenticatedAuthenticationToken(user, null, Collections.singletonList(new SimpleGrantedAuthority(privilege)));
    SecurityContextHolder.getContext().setAuthentication(auth);
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

Example 44 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)

Example 45 with PreAuthenticatedAuthenticationToken

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

the class KeycloakClientRequestFactoryTest method testGetKeycloakSecurityContextInvalidAuthentication.

@Test(expected = IllegalStateException.class)
public void testGetKeycloakSecurityContextInvalidAuthentication() throws Exception {
    SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken("foo", "bar", Collections.singleton(new KeycloakRole("baz"))));
    factory.getKeycloakSecurityContext();
}
Also used : KeycloakRole(org.keycloak.adapters.springsecurity.account.KeycloakRole) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Test(org.junit.Test)

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