Search in sources :

Example 11 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 = mapper.readValue(PREAUTH_JSON, PreAuthenticatedAuthenticationToken.class);
    assertThat(deserialized).isNotNull();
    assertThat(deserialized.isAuthenticated()).isTrue();
    assertThat(deserialized.getAuthorities()).isEqualTo(expected.getAuthorities());
}
Also used : PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Test(org.junit.Test)

Example 12 with PreAuthenticatedAuthenticationToken

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

the class AuthorizationServerEndpointsConfigurer method addUserDetailsService.

private void addUserDetailsService(DefaultTokenServices tokenServices, UserDetailsService userDetailsService) {
    if (userDetailsService != null) {
        PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
        provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken>(userDetailsService));
        tokenServices.setAuthenticationManager(new ProviderManager(Arrays.<AuthenticationProvider>asList(provider)));
    }
}
Also used : PreAuthenticatedAuthenticationProvider(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider) ProviderManager(org.springframework.security.authentication.ProviderManager) AuthenticationProvider(org.springframework.security.authentication.AuthenticationProvider) PreAuthenticatedAuthenticationProvider(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

Example 13 with PreAuthenticatedAuthenticationToken

use of org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken 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 14 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 15 with PreAuthenticatedAuthenticationToken

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

the class ShibbolethController method signinHandler.

@RequestMapping(value = { "/signin" }, method = RequestMethod.GET)
public ModelAndView signinHandler(HttpServletRequest request, HttpServletResponse response, @RequestHeader Map<String, String> headers, ModelAndView mav) {
    LOGGER.info("Headers for shibboleth sign in: {}", headers);
    checkEnabled();
    mav.setViewName("social_link_signin");
    String shibIdentityProvider = headers.get(InstitutionalSignInManager.SHIB_IDENTITY_PROVIDER_HEADER);
    mav.addObject("providerId", shibIdentityProvider);
    String displayName = institutionalSignInManager.retrieveDisplayName(headers);
    mav.addObject("accountId", displayName);
    RemoteUser remoteUser = institutionalSignInManager.retrieveRemoteUser(headers);
    if (remoteUser == null) {
        LOGGER.info("Failed federated log in for {}", shibIdentityProvider);
        identityProviderManager.incrementFailedCount(shibIdentityProvider);
        mav.addObject("unsupportedInstitution", true);
        mav.addObject("institutionContactEmail", identityProviderManager.retrieveContactEmailByProviderid(shibIdentityProvider));
        return mav;
    }
    // Check if the Shibboleth user is already linked to an ORCID account.
    // If so sign them in automatically.
    UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserIdAndIdType(remoteUser.getUserId(), shibIdentityProvider, remoteUser.getIdType());
    if (userConnectionEntity != null) {
        LOGGER.info("Found existing user connection: {}", userConnectionEntity);
        HeaderCheckResult checkHeadersResult = institutionalSignInManager.checkHeaders(parseOriginalHeaders(userConnectionEntity.getHeadersJson()), headers);
        if (!checkHeadersResult.isSuccess()) {
            mav.addObject("headerCheckFailed", true);
            return mav;
        }
        try {
            // Check if the user has been notified
            if (!UserConnectionStatus.NOTIFIED.equals(userConnectionEntity.getConnectionSatus())) {
                try {
                    institutionalSignInManager.sendNotification(userConnectionEntity.getOrcid(), shibIdentityProvider);
                    userConnectionEntity.setConnectionSatus(UserConnectionStatus.NOTIFIED);
                } catch (UnsupportedEncodingException e) {
                    LOGGER.error("Unable to send institutional sign in notification to user " + userConnectionEntity.getOrcid(), e);
                }
            }
            PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userConnectionEntity.getOrcid(), remoteUser.getUserId());
            token.setDetails(new WebAuthenticationDetails(request));
            Authentication authentication = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            userConnectionEntity.setLastLogin(new Date());
            userConnectionManager.update(userConnectionEntity);
        } catch (AuthenticationException e) {
            // this should never happen
            SecurityContextHolder.getContext().setAuthentication(null);
            LOGGER.warn("User {0} should have been logged-in via Shibboleth, but was unable to due to a problem", remoteUser, e);
        }
        return new ModelAndView("redirect:" + calculateRedirectUrl(request, response));
    } else {
        // To avoid confusion, force the user to login to ORCID again
        mav.addObject("linkType", "shibboleth");
        mav.addObject("firstName", (headers.get(InstitutionalSignInManager.GIVEN_NAME_HEADER) == null) ? "" : headers.get(InstitutionalSignInManager.GIVEN_NAME_HEADER));
        mav.addObject("lastName", (headers.get(InstitutionalSignInManager.SN_HEADER) == null) ? "" : headers.get(InstitutionalSignInManager.SN_HEADER));
    }
    return mav;
}
Also used : HeaderCheckResult(org.orcid.pojo.HeaderCheckResult) RemoteUser(org.orcid.pojo.RemoteUser) AuthenticationException(org.springframework.security.core.AuthenticationException) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) Authentication(org.springframework.security.core.Authentication) ModelAndView(org.springframework.web.servlet.ModelAndView) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) UserconnectionEntity(org.orcid.persistence.jpa.entities.UserconnectionEntity) Date(java.util.Date) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

PreAuthenticatedAuthenticationToken (org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)19 Authentication (org.springframework.security.core.Authentication)13 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)6 Test (org.junit.Test)4 GrantedAuthority (org.springframework.security.core.GrantedAuthority)4 SecurityContext (org.springframework.security.core.context.SecurityContext)3 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 OrcidProfileUserDetails (org.orcid.core.oauth.OrcidProfileUserDetails)2 UserconnectionEntity (org.orcid.persistence.jpa.entities.UserconnectionEntity)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 WebAuthenticationDetails (org.springframework.security.web.authentication.WebAuthenticationDetails)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 ModelAndView (org.springframework.web.servlet.ModelAndView)2 PasswordAuthenticationContext (com.evolveum.midpoint.model.api.context.PasswordAuthenticationContext)1 PrismObject (com.evolveum.midpoint.prism.PrismObject)1 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)1