Example usage for org.springframework.security.core Authentication getDetails

List of usage examples for org.springframework.security.core Authentication getDetails

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getDetails.

Prototype

Object getDetails();

Source Link

Document

Stores additional details about the authentication request.

Usage

From source file:org.cloudfoundry.identity.uaa.authentication.manager.ChainedAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        return authentication;
    }/* ww  w  .  j  a  va  2 s. c  o m*/
    UsernamePasswordAuthenticationToken output = null;
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        output = (UsernamePasswordAuthenticationToken) authentication;
    } else {
        output = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), authentication.getAuthorities());
        output.setDetails(authentication.getDetails());
    }
    boolean authenticated = false;
    Authentication auth = null;
    AuthenticationException lastException = null;
    boolean lastResult = false;
    boolean shallContinue = true;
    if (delegates == null || delegates.length == 0) {
        throw new ProviderNotFoundException("No available authentication providers.");
    }
    for (int i = 0; shallContinue && i < delegates.length; i++) {

        boolean shallAuthenticate = (i == 0)
                || (lastResult && IF_PREVIOUS_TRUE.equals(delegates[i].getRequired()))
                || ((!lastResult) && IF_PREVIOUS_FALSE.equals(delegates[i].getRequired()));

        if (shallAuthenticate) {
            if (logger.isDebugEnabled()) {
                logger.debug("Attempting chained authentication of " + output + " with manager:"
                        + delegates[i].getAuthenticationManager() + " required:" + delegates[i].getRequired());
            }
            Authentication thisAuth = null;
            try {
                thisAuth = delegates[i].getAuthenticationManager().authenticate(auth != null ? auth : output);
            } catch (AuthenticationException x) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Chained authentication exception:" + x.getMessage() + " at:"
                            + (x.getStackTrace().length > 0 ? x.getStackTrace()[0] : "(no stack trace)"));
                }
                lastException = x;
                if (delegates[i].getStopIf() != null) {
                    for (Class<? extends AuthenticationException> exceptionClass : delegates[i].getStopIf()) {
                        if (exceptionClass.isAssignableFrom(x.getClass())) {
                            shallContinue = false;
                            break;
                        }
                    }
                }
            }
            lastResult = thisAuth != null && thisAuth.isAuthenticated();

            if (lastResult) {
                authenticated = true;
                auth = thisAuth;
            } else {
                authenticated = false;
                auth = null;
            }

        } else {
            shallContinue = false;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Chained Authentication status of " + output + " with manager:" + delegates[i]
                    + "; Authenticated:" + authenticated);
        }
    }
    if (authenticated) {
        return auth;
    } else if (lastException != null) {
        //we had at least one authentication exception, throw it
        throw lastException;
    } else {
        //not authenticated, but return the last of the result
        return auth;
    }
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.ExternalLoginAuthenticationManager.java

@Override
public Authentication authenticate(Authentication request) throws AuthenticationException {
    logger.debug("Starting external authentication for:" + request);
    ExternalAuthenticationDetails authenticationData = getExternalAuthenticationDetails(request);
    UaaUser userFromRequest = getUser(request, authenticationData);
    if (userFromRequest == null) {
        return null;
    }//from  www  .  jav  a 2  s .  c o  m

    UaaUser userFromDb;

    try {
        logger.debug(String.format("Searching for user by (username:%s , origin:%s)",
                userFromRequest.getUsername(), getOrigin()));
        userFromDb = userDatabase.retrieveUserByName(userFromRequest.getUsername(), getOrigin());
    } catch (UsernameNotFoundException e) {
        logger.debug(String.format("Searching for user by (email:%s , origin:%s)", userFromRequest.getEmail(),
                getOrigin()));
        userFromDb = userDatabase.retrieveUserByEmail(userFromRequest.getEmail(), getOrigin());
    }

    // Register new users automatically
    if (userFromDb == null) {
        if (!isAddNewShadowUser()) {
            throw new AccountNotPreCreatedException(
                    "The user account must be pre-created. Please contact your system administrator.");
        }
        publish(new NewUserAuthenticatedEvent(userFromRequest));
        try {
            userFromDb = userDatabase.retrieveUserByName(userFromRequest.getUsername(), getOrigin());
        } catch (UsernameNotFoundException ex) {
            throw new BadCredentialsException("Unable to register user in internal UAA store.");
        }
    }

    //user is authenticated and exists in UAA
    UaaUser user = userAuthenticated(request, userFromRequest, userFromDb);

    UaaAuthenticationDetails uaaAuthenticationDetails;
    if (request.getDetails() instanceof UaaAuthenticationDetails) {
        uaaAuthenticationDetails = (UaaAuthenticationDetails) request.getDetails();
    } else {
        uaaAuthenticationDetails = UaaAuthenticationDetails.UNKNOWN;
    }
    UaaAuthentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(),
            uaaAuthenticationDetails);
    populateAuthenticationAttributes(success, request, authenticationData);
    publish(new UserAuthenticationSuccessEvent(user, success));
    return success;
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.UsernamePasswordExtractingAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        return authentication;
    }//from   ww w.j  ava  2s.  c o  m
    UsernamePasswordAuthenticationToken output = null;
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        output = (UsernamePasswordAuthenticationToken) authentication;
    } else {
        output = new UsernamePasswordAuthenticationToken(authentication, authentication.getCredentials(),
                authentication.getAuthorities());
        output.setAuthenticated(authentication.isAuthenticated());
        output.setDetails(authentication.getDetails());
    }
    return delegate.authenticate(output);
}

From source file:org.cloudfoundry.identity.uaa.login.AutologinAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (!(authentication instanceof AuthzAuthenticationRequest)) {
        return null;
    }/*from   w  ww  .  jav  a2s .c o  m*/

    AuthzAuthenticationRequest request = (AuthzAuthenticationRequest) authentication;
    Map<String, String> info = request.getInfo();
    String code = info.get("code");

    ExpiringCode ec = doRetrieveCode(code);
    SocialClientUserDetails user = null;
    try {
        if (ec != null) {
            user = new ObjectMapper().readValue(ec.getData(), SocialClientUserDetails.class);
        }
    } catch (IOException x) {
        throw new BadCredentialsException("JsonConversion error", x);
    }

    if (user == null) {
        throw new BadCredentialsException("Cannot redeem provided code for user");
    }

    // ensure that we stored clientId
    String clientId = null;
    String origin = null;
    String userId = null;
    Object principal = user.getUsername();
    if (user.getDetails() instanceof String) {
        clientId = (String) user.getDetails();
    } else if (user.getDetails() instanceof Map) {
        Map<String, String> map = (Map<String, String>) user.getDetails();
        clientId = map.get("client_id");
        origin = map.get(Origin.ORIGIN);
        userId = map.get("user_id");
        principal = new UaaPrincipal(userId, user.getUsername(), null, origin, null);
    }
    if (clientId == null) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client id missing");
    }

    // validate the client Id
    if (!(authentication.getDetails() instanceof UaaAuthenticationDetails)) {
        throw new BadCredentialsException("Cannot redeem provided code for user, auth details missing");
    }

    UaaAuthenticationDetails details = (UaaAuthenticationDetails) authentication.getDetails();
    if (!clientId.equals(details.getClientId())) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client mismatch");
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, null,
            user.getAuthorities());
    result.setDetails(authentication.getDetails());
    return result;

}

From source file:org.fao.geonet.kernel.security.ecas.ECasAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }//from w ww.java  2  s.c  o m

    if (authentication instanceof UsernamePasswordAuthenticationToken
            && (!CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER
                    .equals(authentication.getPrincipal().toString())
                    && !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER
                            .equals(authentication.getPrincipal().toString()))) {
        // UsernamePasswordAuthenticationToken not CAS related
        return null;
    }

    // If an existing CasAuthenticationToken, just check we created it
    if (authentication instanceof CasAuthenticationToken) {
        if (this.key.hashCode() == ((CasAuthenticationToken) authentication).getKeyHash()) {
            return authentication;
        } else {
            throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.incorrectKey",
                    "The presented CasAuthenticationToken does not contain the expected key"));
        }
    }

    // Ensure credentials are presented
    if ((authentication.getCredentials() == null) || "".equals(authentication.getCredentials())) {
        throw new BadCredentialsException(messages.getMessage("CasAuthenticationProvider.noServiceTicket",
                "Failed to provide a CAS service ticket to validate"));
    }

    boolean stateless = false;

    if (authentication instanceof UsernamePasswordAuthenticationToken
            && CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER.equals(authentication.getPrincipal())) {
        stateless = true;
    }

    CasAuthenticationToken result = null;

    if (stateless) {
        // Try to obtain from cache
        result = statelessTicketCache.getByTicketId(authentication.getCredentials().toString());
    }

    if (result == null) {
        result = this.authenticateNow(authentication);
        result.setDetails(authentication.getDetails());
    }

    if (stateless) {
        // Add to cache
        statelessTicketCache.putTicketInCache(result);
    }

    return result;
}

From source file:org.jamwiki.authentication.JAMWikiPostAuthenticationFilter.java

/**
 *
 *//*from   w w w.  j a  v a  2  s .co m*/
private void handleAnonymousUser(Authentication auth) {
    if (!this.getUseJAMWikiAnonymousRoles()) {
        // the configuration file indicates that JAMWiki anonymous roles should not be 
        // used, so assume that an external system is providing this information.
        return;
    }
    // get arrays of existing Spring Security roles and JAMWiki anonymous user roles
    Collection<GrantedAuthority> springSecurityAnonymousAuthorities = auth.getAuthorities();
    Collection<GrantedAuthority> jamwikiAnonymousAuthorities = JAMWikiAuthenticationConfiguration
            .getJamwikiAnonymousAuthorities();
    if (springSecurityAnonymousAuthorities == null || jamwikiAnonymousAuthorities == null) {
        return;
    }
    List<GrantedAuthority> anonymousAuthorities = new ArrayList<GrantedAuthority>();
    anonymousAuthorities.addAll(springSecurityAnonymousAuthorities);
    anonymousAuthorities.addAll(jamwikiAnonymousAuthorities);
    // replace the existing anonymous authentication object with the new authentication array
    AnonymousAuthenticationToken jamwikiAuth = new AnonymousAuthenticationToken(this.getKey(),
            auth.getPrincipal(), anonymousAuthorities);
    jamwikiAuth.setDetails(auth.getDetails());
    jamwikiAuth.setAuthenticated(auth.isAuthenticated());
    SecurityContextHolder.getContext().setAuthentication(jamwikiAuth);
}

From source file:org.jwebsocket.plugins.system.SystemPlugIn.java

/**
 * Logon a user given the username and password by using the Spring Security module
 *
 * @param aConnector// w  w w.ja v a 2s.  co  m
 * @param aToken The token with the username and password
 */
void logon(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();
    if (aConnector.getSession().isAuthenticated()) {
        lServer.sendToken(aConnector, lServer.createErrorToken(aToken, -1, "is authenticated"));
        return;
    }

    String lUsername = aToken.getString("username");
    String lPassword = aToken.getString("password");

    if (mLog.isDebugEnabled()) {
        mLog.debug("Starting authentication ...");
    }

    Authentication lAuthRequest = new UsernamePasswordAuthenticationToken(lUsername, lPassword);
    Authentication lAuthResult;
    try {
        lAuthResult = getAuthProvMgr().authenticate(lAuthRequest);
    } catch (AuthenticationException ex) {
        String lMsg = ex.getClass().getSimpleName() + ": " + ex.getMessage();
        Token lResponse = getServer().createErrorToken(aToken, -1, lMsg);
        lResponse.setString("username", lUsername);
        sendToken(aConnector, aConnector, lResponse);
        if (mLog.isDebugEnabled()) {
            mLog.debug(lMsg);
        }
        return; // stop the execution flow
    }

    if (mLog.isDebugEnabled()) {
        mLog.debug("Authentication successful. Updating the user session (id: "
                + (null != aConnector.getSession() ? aConnector.getSession().getSessionId() : "[null]")
                + ", storage: "
                + (null != aConnector.getSession() ? aConnector.getSession().getStorage() : "[null]") + ")...");
    }

    // getting the session
    Map<String, Object> lSession = aConnector.getSession().getStorage();

    // setting the is_authenticated flag
    lSession.put(IS_AUTHENTICATED, lAuthResult.isAuthenticated());

    // setting the connector username
    aConnector.setUsername(lUsername);

    // setting the uuid
    String lUUID;
    Object lDetails = lAuthResult.getDetails();
    if (null != lDetails && lDetails instanceof IUserUniqueIdentifierContainer) {
        lUUID = ((IUserUniqueIdentifierContainer) lDetails).getUUID();
    } else {
        lUUID = lUsername;
    }
    lSession.put(UUID, lUUID);

    // setting the authorities
    String lAuthorities = "";
    for (GrantedAuthority lGA : lAuthResult.getAuthorities()) {
        lAuthorities = lAuthorities.concat(lGA.getAuthority() + " ");
    }

    // storing the user authorities as a string to avoid serialization problems
    lSession.put(AUTHORITIES, lAuthorities);

    // creating the response
    Token lResponse = createResponse(aToken);
    lResponse.setString("uuid", lUUID);
    lResponse.setString("username", lUsername);
    lResponse.setList("authorities", Tools.parseStringArrayToList(lAuthorities.split(" ")));

    // sending the response to requester
    sendToken(aConnector, lResponse);

    // sending response to clients that share the requester session
    getServer().broadcastToSharedSession(aConnector.getId(), aConnector.getSession().getSessionId(), lResponse,
            false);

    if (mLog.isDebugEnabled()) {
        mLog.debug("Logon process finished successfully!");
    }

    // if successfully logged in...
    if (lUsername != null) {
        // broadcast "login event" to other clients
        broadcastLoginEvent(aConnector);
    }
}

From source file:org.opennms.web.springframework.security.SecurityAuthenticationEventOnmsEventBuilder.java

private EventBuilder createEvent(String uei, AbstractAuthenticationEvent authEvent) {
    EventBuilder builder = new EventBuilder(uei, "OpenNMS.WebUI");
    builder.setTime(new Date(authEvent.getTimestamp()));
    org.springframework.security.core.Authentication auth = authEvent.getAuthentication();
    if (auth != null && auth.getName() != null) {
        builder.addParam("user", WebSecurityUtils.sanitizeString(auth.getName()));
    }/*from   w ww  . j  a  v a 2s  . c om*/
    if (auth != null && auth.getDetails() != null && auth.getDetails() instanceof WebAuthenticationDetails) {
        WebAuthenticationDetails webDetails = (WebAuthenticationDetails) auth.getDetails();
        if (webDetails.getRemoteAddress() != null) {
            builder.addParam("ip", webDetails.getRemoteAddress());
        }
    }
    return builder;
}

From source file:org.springframework.security.cas.authentication.CasAuthenticationProvider.java

/**
 * Gets the serviceUrl. If the {@link Authentication#getDetails()} is an instance of
 * {@link ServiceAuthenticationDetails}, then
 * {@link ServiceAuthenticationDetails#getServiceUrl()} is used. Otherwise, the
 * {@link ServiceProperties#getService()} is used.
 *
 * @param authentication//from w w  w .j a  va2s.co  m
 * @return
 */
private String getServiceUrl(Authentication authentication) {
    String serviceUrl;
    if (authentication.getDetails() instanceof ServiceAuthenticationDetails) {
        serviceUrl = ((ServiceAuthenticationDetails) authentication.getDetails()).getServiceUrl();
    } else if (serviceProperties == null) {
        throw new IllegalStateException(
                "serviceProperties cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails.");
    } else if (serviceProperties.getService() == null) {
        throw new IllegalStateException(
                "serviceProperties.getService() cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails.");
    } else {
        serviceUrl = serviceProperties.getService();
    }
    if (logger.isDebugEnabled()) {
        logger.debug("serviceUrl = " + serviceUrl);
    }
    return serviceUrl;
}

From source file:org.springframework.security.extensions.kerberos.KerberosAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
    String validatedUsername = kerberosClient.login(auth.getName(), auth.getCredentials().toString());
    UserDetails userDetails = this.userDetailsService.loadUserByUsername(validatedUsername);
    UsernamePasswordAuthenticationToken output = new UsernamePasswordAuthenticationToken(userDetails,
            auth.getCredentials(), userDetails.getAuthorities());
    output.setDetails(authentication.getDetails());
    return output;

}