Example usage for org.springframework.security.openid OpenIDAuthenticationToken OpenIDAuthenticationToken

List of usage examples for org.springframework.security.openid OpenIDAuthenticationToken OpenIDAuthenticationToken

Introduction

In this page you can find the example usage for org.springframework.security.openid OpenIDAuthenticationToken OpenIDAuthenticationToken.

Prototype

public OpenIDAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities,
        String identityUrl, List<OpenIDAttribute> attributes) 

Source Link

Document

Created by the OpenIDAuthenticationProvider on successful authentication.

Usage

From source file:net.triptech.buildulator.service.OpenIdAuthenticationFailureHandler.java

/**
 * Called when an authentication attempt fails.
 *
 * @param request - the request during which the authentication attempt occurred.
 * @param response - the response.//from w w  w  . ja v  a  2 s .  c  om
 * @param exception - the exception which was thrown to reject the authentication
 * request.
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 */
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authenticationException) throws IOException, ServletException {

    if (authenticationException instanceof DisabledException) {
        RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        redirectStrategy.sendRedirect(request, response, "/accountDisabled");
    }

    if (isFailedDueToUserNotRegistered(authenticationException)) {

        OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) authenticationException
                .getAuthentication();

        Person person = Person.findByOpenIdIdentifier(token.getIdentityUrl());

        if (person == null) {

            // The person does not exist, create
            person = createPerson(token);

            // Recreate OpenIDAuthentication token, transfer values from existing
            // token, and assign roles from retrieved user. Since grantedAuthorities
            // is unmodifiable list and no way to update the pre created token.

            OpenIDAuthenticationToken newToken = new OpenIDAuthenticationToken(person, person.getAuthorities(),
                    token.getIdentityUrl(), token.getAttributes());
            newToken.setAuthenticated(true);

            token.setDetails(person);
            SecurityContextHolder.getContext().setAuthentication(newToken);

            // Transfer any previous projects to the new user
            transferProjects(request, person);

            RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
            redirectStrategy.sendRedirect(request, response, "/user");
        }
    }
}

From source file:net.triptech.metahive.service.OpenIdAuthenticationFailureHandler.java

/**
 * Called when an authentication attempt fails.
 *
 * @param request - the request during which the authentication attempt occurred.
 * @param response - the response.//w  ww .  j a va 2  s  . c  o m
 * @param exception - the exception which was thrown to reject the authentication
 * request.
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 */
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authenticationException) throws IOException, ServletException {

    if (authenticationException instanceof DisabledException) {
        RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        redirectStrategy.sendRedirect(request, response, "/accountDisabled");
    }

    if (isFailedDueToUserNotRegistered(authenticationException)) {

        OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) authenticationException
                .getAuthentication();

        String id = token.getIdentityUrl();

        List<Person> people = Person.findPeopleByOpenIdIdentifier(id).getResultList();

        Person person = people.size() == 0 ? null : people.get(0);

        if (person == null) {

            // The person does not exist, create
            person = createPerson(token);

            // Recreate OpenIDAuthentication token, transfer values from existing
            // token, and assign roles from retrieved user. Since grantedAuthorities
            // is unmodifiable list and no way to update the pre created token.

            OpenIDAuthenticationToken newToken = new OpenIDAuthenticationToken(person, person.getAuthorities(),
                    token.getIdentityUrl(), token.getAttributes());
            newToken.setAuthenticated(true);

            token.setDetails(person);
            SecurityContextHolder.getContext().setAuthentication(newToken);

            RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
            redirectStrategy.sendRedirect(request, response, "/user");
        }
    }
}

From source file:org.mitre.provenance.openid.OpenId4JavaProxyConsumer.java

public OpenIDAuthenticationToken endConsumption(HttpServletRequest request) throws OpenIDConsumerException {
    // extract the parameters from the authentication response
    // (which comes in as a HTTP request from the OpenID provider)
    ParameterList openidResp = new ParameterList(request.getParameterMap());

    // retrieve the previously stored discovery information
    DiscoveryInformation discovered = (DiscoveryInformation) request.getSession()
            .getAttribute(DISCOVERY_INFO_KEY);

    if (discovered == null) {
        throw new OpenIDConsumerException(
                "DiscoveryInformation is not available. Possible causes are lost session or replay attack");
    }/*w  w w . java2s  . c om*/

    List<OpenIDAttribute> attributesToFetch = (List<OpenIDAttribute>) request.getSession()
            .getAttribute(ATTRIBUTE_LIST_KEY);

    request.getSession().removeAttribute(DISCOVERY_INFO_KEY);
    request.getSession().removeAttribute(ATTRIBUTE_LIST_KEY);

    // extract the receiving URL from the HTTP request
    StringBuffer receivingURL = request.getRequestURL();
    String queryString = request.getQueryString();

    if (StringUtils.hasLength(queryString)) {
        receivingURL.append("?").append(request.getQueryString());
    }

    // verify the response
    VerificationResult verification;

    try {
        verification = consumerManager.verify(receivingURL.toString(), openidResp, discovered);
    } catch (MessageException e) {
        throw new OpenIDConsumerException("Error verifying openid response", e);
    } catch (DiscoveryException e) {
        throw new OpenIDConsumerException("Error verifying openid response", e);
    } catch (AssociationException e) {
        throw new OpenIDConsumerException("Error verifying openid response", e);
    }

    // examine the verification result and extract the verified identifier
    Identifier verified = verification.getVerifiedId();

    if (verified == null) {
        Identifier id = discovered.getClaimedIdentifier();
        return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE,
                id == null ? "Unknown" : id.getIdentifier(),
                "Verification status message: [" + verification.getStatusMsg() + "]",
                Collections.<OpenIDAttribute>emptyList());
    }

    List<OpenIDAttribute> attributes = fetchAxAttributes(verification.getAuthResponse(), attributesToFetch);

    return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS, verified.getIdentifier(),
            "some message", attributes);
}

From source file:org.opendatakit.common.security.spring.WrappingOpenIDAuthenticationProvider.java

@Override
protected Authentication createSuccessfulAuthentication(UserDetails rawUserDetails,
        OpenIDAuthenticationToken auth) {
    String eMail = null;//from w w  w.  j  ava 2s .c  o m
    List<OpenIDAttribute> oAttrList = auth.getAttributes();
    for (OpenIDAttribute oAttr : oAttrList) {
        if ("email".equals(oAttr.getName())) {
            Object o = oAttr.getValues().get(0);
            if (o != null) {
                eMail = (String) o;
            }
        }
    }
    if (eMail == null) {
        logger.warn("OpenId attributes did not include an e-mail address! ");
        throw new UsernameNotFoundException("email address not supplied in OpenID attributes");
    }
    eMail = WrappingOpenIDAuthenticationProvider.normalizeMailtoAddress(eMail);
    String mailtoDomain = WrappingOpenIDAuthenticationProvider.getMailtoDomain(eMail);

    UserDetails userDetails = rawUserDetails;

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    authorities.addAll(userDetails.getAuthorities());
    // add the AUTH_OPENID granted authority,
    authorities.add(new SimpleGrantedAuthority(GrantedAuthorityName.AUTH_OPENID.toString()));

    // attempt to look user up in registered users table...
    String username = null;
    UserDetails partialDetails = null;
    boolean noRights = false;
    try {
        partialDetails = wrappingUserDetailsService.loadUserByUsername(eMail);
        // found the user in the table -- fold in authorizations and get uriUser.
        authorities.addAll(partialDetails.getAuthorities());
        // users are blacklisted by registering them and giving them no rights.
        noRights = partialDetails.getAuthorities().isEmpty();
        username = partialDetails.getUsername();
    } catch (Exception e) {
        e.printStackTrace();
        logger.warn("OpenId attribute e-mail: " + eMail + " did not match any known e-mail addresses! "
                + e.getMessage());
        throw new UsernameNotFoundException("account not recognized");
    }

    AggregateUser trueUser = new AggregateUser(username, partialDetails.getPassword(),
            UUID.randomUUID().toString(), // junk...
            mailtoDomain, partialDetails.isEnabled(), partialDetails.isAccountNonExpired(),
            partialDetails.isCredentialsNonExpired(), partialDetails.isAccountNonLocked(), authorities);
    if (noRights
            || !(trueUser.isEnabled() && trueUser.isAccountNonExpired() && trueUser.isAccountNonLocked())) {
        logger.warn("OpenId attribute e-mail: " + eMail + " account is blocked! ");
        throw new UsernameNotFoundException("account is blocked");
    }

    return new OpenIDAuthenticationToken(trueUser, trueUser.getAuthorities(), auth.getIdentityUrl(),
            auth.getAttributes());
}