Search in sources :

Example 36 with PreAuthenticatedAuthenticationToken

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

the class OAuth2AuthenticationManagerTests method testDetailsEnhanced.

@Test
public void testDetailsEnhanced() throws Exception {
    authentication.setDetails("DETAILS");
    Mockito.when(tokenServices.loadAuthentication("FOO")).thenReturn(authentication);
    PreAuthenticatedAuthenticationToken request = new PreAuthenticatedAuthenticationToken("FOO", "");
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, "BAR");
    OAuth2AuthenticationDetails details = new OAuth2AuthenticationDetails(servletRequest);
    request.setDetails(details);
    Authentication result = manager.authenticate(request);
    assertEquals(authentication, result);
    assertEquals("BAR", ((OAuth2AuthenticationDetails) result.getDetails()).getTokenValue());
    assertEquals("DETAILS", ((OAuth2AuthenticationDetails) result.getDetails()).getDecodedDetails());
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Test(org.junit.Test)

Example 37 with PreAuthenticatedAuthenticationToken

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

the class SecurityEnforcerImpl method setupPreAuthenticatedSecurityContext.

@Override
public void setupPreAuthenticatedSecurityContext(PrismObject<UserType> user) throws SchemaException {
    MidPointPrincipal principal;
    if (userProfileService == null) {
        LOGGER.warn("No user profile service set up in SecurityEnforcer. " + "This is OK in low-level tests but it is a serious problem in running system");
        principal = new MidPointPrincipal(user.asObjectable());
    } else {
        principal = userProfileService.getPrincipal(user);
    }
    Authentication authentication = new PreAuthenticatedAuthenticationToken(principal, null);
    setupPreAuthenticatedSecurityContext(authentication);
}
Also used : Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

Example 38 with PreAuthenticatedAuthenticationToken

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

the class SecurityEnforcerImpl method runPrivileged.

@Override
public <T> T runPrivileged(Producer<T> producer) {
    LOGGER.debug("Running {} as privileged", producer);
    Authentication origAuthentication = SecurityContextHolder.getContext().getAuthentication();
    LOGGER.trace("ORIG auth {}", origAuthentication);
    // Try to reuse the original identity as much as possible. All we need to is add AUTZ_ALL
    // to the list of authorities
    Authorization privilegedAuthorization = createPrivilegedAuthorization();
    Object newPrincipal = null;
    if (origAuthentication != null) {
        Object origPrincipal = origAuthentication.getPrincipal();
        if (origAuthentication instanceof AnonymousAuthenticationToken) {
            newPrincipal = origPrincipal;
        } else {
            LOGGER.trace("ORIG principal {} ({})", origPrincipal, origPrincipal != null ? origPrincipal.getClass() : null);
            if (origPrincipal != null) {
                if (origPrincipal instanceof MidPointPrincipal) {
                    MidPointPrincipal newMidPointPrincipal = ((MidPointPrincipal) origPrincipal).clone();
                    newMidPointPrincipal.getAuthorities().add(privilegedAuthorization);
                    newPrincipal = newMidPointPrincipal;
                }
            }
        }
        Collection<GrantedAuthority> newAuthorities = new ArrayList<>();
        newAuthorities.addAll(origAuthentication.getAuthorities());
        newAuthorities.add(privilegedAuthorization);
        PreAuthenticatedAuthenticationToken newAuthorization = new PreAuthenticatedAuthenticationToken(newPrincipal, null, newAuthorities);
        LOGGER.trace("NEW auth {}", newAuthorization);
        SecurityContextHolder.getContext().setAuthentication(newAuthorization);
    } else {
        LOGGER.debug("No original authentication, do NOT setting any privileged security context");
    }
    try {
        return producer.run();
    } finally {
        SecurityContextHolder.getContext().setAuthentication(origAuthentication);
        LOGGER.debug("Finished running {} as privileged", producer);
        LOGGER.trace("Security context after privileged operation: {}", SecurityContextHolder.getContext());
    }
}
Also used : Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken)

Example 39 with PreAuthenticatedAuthenticationToken

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

the class AuthenticationEvaluatorImpl method authenticateUserPreAuthenticated.

@Override
public PreAuthenticatedAuthenticationToken authenticateUserPreAuthenticated(ConnectionEnvironment connEnv, String enteredUsername) {
    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true);
    // Authorizations
    if (!hasAnyAuthorization(principal)) {
        recordAuthenticationFailure(principal, connEnv, "no authorizations");
        throw new AccessDeniedException("web.security.provider.access.denied");
    }
    PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, null, principal.getAuthorities());
    recordAuthenticationSuccess(principal, connEnv);
    return token;
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

Example 40 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken in project ORCID-Source by ORCID.

the class SocialController method signinHandler.

@RequestMapping(value = { "/access" }, method = RequestMethod.GET)
public ModelAndView signinHandler(HttpServletRequest request, HttpServletResponse response) {
    SocialType connectionType = socialContext.isSignedIn(request, response);
    if (connectionType != null) {
        Map<String, String> userMap = retrieveUserDetails(connectionType);
        String providerId = connectionType.value();
        String userId = socialContext.getUserId();
        UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserId(userMap.get("providerUserId"), providerId);
        if (userConnectionEntity != null) {
            if (userConnectionEntity.isLinked()) {
                ProfileEntity profile = profileEntityCacheManager.retrieve(userConnectionEntity.getOrcid());
                if (profile.getUsing2FA()) {
                    return new ModelAndView("social_2FA");
                }
                UserconnectionPK pk = new UserconnectionPK(userId, providerId, userMap.get("providerUserId"));
                String aCredentials = new StringBuffer(providerId).append(":").append(userMap.get("providerUserId")).toString();
                PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userConnectionEntity.getOrcid(), aCredentials);
                token.setDetails(getOrcidProfileUserDetails(userConnectionEntity.getOrcid()));
                Authentication authentication = authenticationManager.authenticate(token);
                userConnectionManager.updateLoginInformation(pk);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                return new ModelAndView("redirect:" + calculateRedirectUrl(request, response));
            } else {
                ModelAndView mav = new ModelAndView();
                mav.setViewName("social_link_signin");
                mav.addObject("providerId", providerId);
                mav.addObject("accountId", getAccountIdForDisplay(userMap));
                mav.addObject("linkType", "social");
                mav.addObject("emailId", (userMap.get("email") == null) ? "" : userMap.get("email"));
                mav.addObject("firstName", (userMap.get("firstName") == null) ? "" : userMap.get("firstName"));
                mav.addObject("lastName", (userMap.get("lastName") == null) ? "" : userMap.get("lastName"));
                return mav;
            }
        } else {
            throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
        }
    } else {
        throw new UsernameNotFoundException("Could not find an orcid account associated with the email id.");
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Authentication(org.springframework.security.core.Authentication) ModelAndView(org.springframework.web.servlet.ModelAndView) SocialType(org.orcid.frontend.spring.web.social.config.SocialType) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity) UserconnectionPK(org.orcid.persistence.jpa.entities.UserconnectionPK) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

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