Example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken getPrincipal

List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getPrincipal

Introduction

In this page you can find the example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken getPrincipal.

Prototype

public Object getPrincipal() 

Source Link

Usage

From source file:com.evolveum.midpoint.model.impl.security.MidpointRestAuthenticator.java

public void handleRequest(AuthorizationPolicy policy, Message m, ContainerRequestContext requestCtx) {

    if (policy == null) {
        RestServiceUtil.createAbortMessage(requestCtx);
        return;/*from  w  w  w . j av  a 2 s.com*/
    }

    T authenticationContext = createAuthenticationContext(policy, requestCtx);

    if (authenticationContext == null) {
        return;
    }

    String enteredUsername = authenticationContext.getUsername();

    if (enteredUsername == null) {
        RestServiceUtil.createAbortMessage(requestCtx);
        return;
    }

    LOGGER.trace("Authenticating username '{}' to REST service", enteredUsername);

    // We need to create task before attempting authentication. Task ID is also a session ID.
    Task task = taskManager.createTaskInstance(ModelRestService.OPERATION_REST_SERVICE);
    task.setChannel(SchemaConstants.CHANNEL_REST_URI);

    ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_REST_URI);
    connEnv.setSessionIdOverride(task.getTaskIdentifier());
    UsernamePasswordAuthenticationToken token;
    try {
        token = getAuthenticationEvaluator().authenticate(connEnv, authenticationContext);
    } catch (UsernameNotFoundException | BadCredentialsException e) {
        LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername,
                e.getMessage(), e);
        requestCtx.abortWith(Response.status(Status.UNAUTHORIZED)
                .header("WWW-Authenticate", "Basic authentication failed. Cannot authenticate user.").build());
        return;
    } catch (DisabledException | LockedException | CredentialsExpiredException | AccessDeniedException
            | AuthenticationCredentialsNotFoundException | AuthenticationServiceException e) {
        LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername,
                e.getMessage(), e);
        requestCtx.abortWith(Response.status(Status.FORBIDDEN).build());
        return;
    }

    UserType user = ((MidPointPrincipal) token.getPrincipal()).getUser();
    task.setOwner(user.asPrismObject());

    //  m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);
    if (!authorizeUser(user, null, enteredUsername, connEnv, requestCtx)) {
        return;
    }

    String oid = requestCtx.getHeaderString("Switch-To-Principal");
    OperationResult result = task.getResult();
    if (StringUtils.isNotBlank(oid)) {
        try {
            PrismObject<UserType> authorizedUser = model.getObject(UserType.class, oid, null, task, result);
            task.setOwner(authorizedUser);
            if (!authorizeUser(AuthorizationConstants.AUTZ_REST_PROXY_URL, user, authorizedUser,
                    enteredUsername, connEnv, requestCtx)) {
                return;
            }
            authenticateUser(authorizedUser, authorizedUser.getName().getOrig(), connEnv, requestCtx);
            //               if (!authorizeUser(authorizedUser.asObjectable(), null, authorizedUser.getName().getOrig(), connEnv, requestCtx)){
            //                    return;
            //                 }
        } catch (ObjectNotFoundException | SchemaException | SecurityViolationException | CommunicationException
                | ConfigurationException | ExpressionEvaluationException e) {
            LOGGER.trace("Exception while authenticating user identified with '{}' to REST service: {}", oid,
                    e.getMessage(), e);
            requestCtx.abortWith(Response.status(Status.UNAUTHORIZED)
                    .header("WWW-Authenticate", "Proxy Authentication failed. Cannot authenticate user.")
                    .build());
            return;
        }

    }

    m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);

    LOGGER.trace("Authorized to use REST service ({})", user);

}

From source file:it.geosolutions.geostore.services.rest.impl.RESTServiceImpl.java

/**
 * @return User - The authenticated user that is accessing this service, or null if guest access.
 *///from w ww.  jav a 2 s  .  c o m
protected User extractAuthUser(SecurityContext sc) throws InternalErrorWebEx {
    if (sc == null)
        throw new InternalErrorWebEx("Missing auth info");
    else {
        Principal principal = sc.getUserPrincipal();
        if (principal == null) {
            // If I'm here I'm sure that the service is running is allowed for the unauthenticated users
            // due to service-based authorization step that uses annotations on services declaration (seee module geostore-rest-api). 
            // So I'm going to create a Principal to be used during resources-based authorization.
            principal = createGuestPrincipal();
        }
        if (!(principal instanceof UsernamePasswordAuthenticationToken)) {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Mismatching auth principal");
            }
            throw new InternalErrorWebEx("Mismatching auth principal (" + principal.getClass() + ")");
        }

        UsernamePasswordAuthenticationToken usrToken = (UsernamePasswordAuthenticationToken) principal;

        //DamianoG 06/03/2014 Why create a new Instance when we can deal with the object taken from the DB? Being the instance taken from DB Transient we avoid problems saving security rules...
        //            User user = new User();
        //            user.setName(usrToken.getName());
        //            for (GrantedAuthority authority : usrToken.getAuthorities()) {
        //                if (authority != null) {
        //                    if (authority.getAuthority() != null
        //                            && authority.getAuthority().contains("ADMIN"))
        //                        user.setRole(Role.ADMIN);
        //
        //                    if (authority.getAuthority() != null
        //                            && authority.getAuthority().contains("USER") && user.getRole() == null)
        //                        user.setRole(Role.USER);
        //
        //                    if (user.getRole() == null)
        //                        user.setRole(Role.GUEST);
        //                }
        //            }
        User user = (User) usrToken.getPrincipal();

        LOGGER.info("Accessing service with user " + user.getName() + " and role " + user.getRole());

        return user;
    }
}

From source file:org.apache.nifi.kerberos.KerberosProvider.java

@Override
public final AuthenticationResponse authenticate(final LoginCredentials credentials)
        throws InvalidLoginCredentialsException, IdentityAccessException {
    if (provider == null) {
        throw new IdentityAccessException("The Kerberos authentication provider is not initialized.");
    }//from  w w w  .j a v a  2  s.c om

    try {
        // Perform the authentication
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                credentials.getUsername(), credentials.getPassword());
        logger.debug("Created authentication token for principal {} with name {} and is authenticated {}",
                token.getPrincipal(), token.getName(), token.isAuthenticated());

        final Authentication authentication = provider.authenticate(token);
        logger.debug(
                "Ran provider.authenticate() and returned authentication for "
                        + "principal {} with name {} and is authenticated {}",
                authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated());

        return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration,
                issuer);
    } catch (final AuthenticationException e) {
        throw new InvalidLoginCredentialsException(e.getMessage(), e);
    }
}

From source file:org.bibsonomy.webapp.util.spring.security.rememberMeServices.LDAPRememberMeServices.java

@Override
protected void onLoginSuccess(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication successfulAuthentication) {
    if (successfulAuthentication instanceof UsernamePasswordAuthenticationToken) {
        final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) successfulAuthentication;

        final Object principal = token.getPrincipal();

        if (principal instanceof UserAdapter) {
            final UserAdapter userDetails = (UserAdapter) principal;
            final String username = userDetails.getUsername();
            final String ldapID = userDetails.getUser().getLdapId();
            final String clearPassword = token.getCredentials().toString();

            final int tokenLifetime = this.getTokenValiditySeconds();
            final long expiryTime = this.calculateExpiryTime(tokenLifetime);

            final String signatureValue = this.makeTokenSignature(
                    new String[] { Long.toString(expiryTime), username, ldapID, clearPassword });

            this.setCookie(
                    new String[] { username, ldapID, clearPassword, Long.toString(expiryTime), signatureValue },
                    tokenLifetime, request, response);

            if (log.isDebugEnabled()) {
                log.debug("Added remember-me cookie for user '" + username + "', expiry: '"
                        + new Date(expiryTime) + "'");
            }/*from  w  w w .  j  a  v  a  2 s  .com*/
        }
    }
}

From source file:org.geoserver.security.iride.IrideAuthenticationProvider.java

/**
 * Returns the {@link UsernamePasswordAuthenticationToken} token.
 *
 * @param auth the {@link UsernamePasswordAuthenticationToken} token
 * @return the {@link UsernamePasswordAuthenticationToken} token
 * @see UsernamePasswordAuthenticationProvider#authenticate(Authentication, HttpServletRequest)
 *//*ww w .  j a  v a 2 s.co m*/
private UsernamePasswordAuthenticationToken buildAuthenticationToken(UsernamePasswordAuthenticationToken auth) {
    if (auth == null) {
        // pass request to next provider in the chain
        return null;
    }

    if (!auth.getAuthorities().contains(GeoServerRole.AUTHENTICATED_ROLE)) {
        final List<GrantedAuthority> roles = new ArrayList<>();
        roles.addAll(auth.getAuthorities());
        roles.add(GeoServerRole.AUTHENTICATED_ROLE);

        final UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(
                auth.getPrincipal(), auth.getCredentials(), roles);
        newAuth.setDetails(auth.getDetails());

        return newAuth;
    }

    return auth;
}

From source file:org.orcid.frontend.web.controllers.RegistrationController.java

private void automaticallyLogin(HttpServletRequest request, String password, OrcidProfile orcidProfile) {
    UsernamePasswordAuthenticationToken token = null;
    try {/*from w  ww.  j  av a2s  .  co m*/
        String orcid = orcidProfile.getOrcidIdentifier().getPath();
        // Force refresh of profile entity to ensure new password value is
        // picked up from DB.
        profileDao.refresh(profileDao.find(orcid));
        token = new UsernamePasswordAuthenticationToken(orcid, password);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (AuthenticationException e) {
        // this should never happen
        SecurityContextHolder.getContext().setAuthentication(null);
        LOGGER.warn("User {0} should have been logged-in, but we unable to due to a problem", e,
                (token != null ? token.getPrincipal() : "empty principle"));
    }
}

From source file:org.orcid.frontend.web.controllers.RegistrationController.java

public void createMinimalRegistrationAndLogUserIn(HttpServletRequest request, HttpServletResponse response,
        OrcidProfile profileToSave, boolean usedCaptchaVerification) {
    String password = profileToSave.getPassword();
    UsernamePasswordAuthenticationToken token = null;
    try {/*from  ww w  . j  a  v  a  2 s  . com*/
        profileToSave = createMinimalRegistration(request, profileToSave, usedCaptchaVerification);
        String orcidId = profileToSave.getOrcidIdentifier().getPath();
        token = new UsernamePasswordAuthenticationToken(profileToSave.getOrcidIdentifier().getPath(), password);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        if (internalSSOManager.enableCookie()) {
            //Set user cookie
            internalSSOManager.writeCookie(orcidId, request, response);
        }
    } catch (AuthenticationException e) {
        // this should never happen
        SecurityContextHolder.getContext().setAuthentication(null);
        LOGGER.warn("User {0} should have been logged-in, but we unable to due to a problem", e,
                (token != null ? token.getPrincipal() : "empty principle"));
    }

}

From source file:org.springframework.security.authentication.jaas.AbstractJaasAuthenticationProvider.java

/**
 * Attempts to login the user given the Authentication objects principal and
 * credential/*  w  ww.  j  av a  2  s .  c o  m*/
 *
 * @param auth The Authentication object to be authenticated.
 *
 * @return The authenticated Authentication object, with it's grantedAuthorities set.
 *
 * @throws AuthenticationException This implementation does not handle 'locked' or
 * 'disabled' accounts. This method only throws a AuthenticationServiceException, with
 * the message of the LoginException that will be thrown, should the
 * loginContext.login() method fail.
 */
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    if (!(auth instanceof UsernamePasswordAuthenticationToken)) {
        return null;
    }

    UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;
    Set<GrantedAuthority> authorities;

    try {
        // Create the LoginContext object, and pass our InternallCallbackHandler
        LoginContext loginContext = createLoginContext(new InternalCallbackHandler(auth));

        // Attempt to login the user, the LoginContext will call our
        // InternalCallbackHandler at this point.
        loginContext.login();

        // Create a set to hold the authorities, and add any that have already been
        // applied.
        authorities = new HashSet<>();

        // Get the subject principals and pass them to each of the AuthorityGranters
        Set<Principal> principals = loginContext.getSubject().getPrincipals();

        for (Principal principal : principals) {
            for (AuthorityGranter granter : this.authorityGranters) {
                Set<String> roles = granter.grant(principal);

                // If the granter doesn't wish to grant any authorities, it should
                // return null.
                if ((roles != null) && !roles.isEmpty()) {
                    for (String role : roles) {
                        authorities.add(new JaasGrantedAuthority(role, principal));
                    }
                }
            }
        }

        // Convert the authorities set back to an array and apply it to the token.
        JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(),
                request.getCredentials(), new ArrayList<>(authorities), loginContext);

        // Publish the success event
        publishSuccessEvent(result);

        // we're done, return the token.
        return result;

    } catch (LoginException loginException) {
        AuthenticationException ase = this.loginExceptionResolver.resolveException(loginException);

        publishFailureEvent(request, ase);
        throw ase;
    }
}