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:com.ai.bss.webui.security.AiBssAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }//from  w w  w.j av a2s. com
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = String.valueOf(token.getCredentials());
    FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>();
    AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray());
    try {
        //            commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback);
        // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before
        // the command is dispatched.
    } catch (StructuralCommandValidationFailedException e) {
        e.printStackTrace();
        return null;
    }
    UserAccount account;
    try {
        account = accountCallback.get();
        if (account == null) {
            throw new BadCredentialsException("Invalid username and/or password");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    } catch (ExecutionException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account,
            authentication.getCredentials(), userAuthorities);
    result.setDetails(authentication.getDetails());
    return result;
}

From source file:org.osiam.auth.login.ldap.OsiamLdapAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) {
    Preconditions.checkArgument(authentication instanceof OsiamLdapAuthentication,
            "OsiamLdapAuthenticationProvider only supports OsiamLdapAuthentication.");

    final OsiamLdapAuthentication userToken = (OsiamLdapAuthentication) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (Strings.isNullOrEmpty(username)) {
        throw new BadCredentialsException("OsiamLdapAuthenticationProvider: Empty Username");
    }//from w  ww  .  j a  v a2 s. c  o  m

    if (Strings.isNullOrEmpty(password)) {
        throw new BadCredentialsException("OsiamLdapAuthenticationProvider: Empty Password");
    }

    User user = resourceServerConnector.getUserByUsername(username);
    checkIfInternalUserExists(user);

    DirContextOperations userData = doAuthentication(userToken);

    UserDetails ldapUser = osiamLdapUserContextMapper.mapUserFromContext(userData, authentication.getName(),
            loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials()));

    user = synchronizeLdapData(userData, user);

    User authUser = new User.Builder(username).setId(user.getId()).build();

    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

    for (Role role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getValue()));
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authUser, null,
            grantedAuthorities);
    result.setDetails(authentication.getDetails());

    return result;
}

From source file:eu.trentorise.smartcampus.resourceprovider.filter.ResourceAuthenticationManager.java

/**
 * Check whether the access to the specific resource is granted. The The
 * resource is identified from the {@link ResourceCallAuthenticationToken}
 * fields {@link ResourceCallAuthenticationToken#getRequestPath()} and
 * {@link ResourceCallAuthenticationToken#getHttpMethod()}.
 * /*from  w  ww .  j av  a 2s .c o m*/
 * @param authentication
 *            the authentication token object as instance of
 *            {@link ResourceCallAuthenticationToken}.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    assert authentication instanceof ResourceCallAuthenticationToken;
    ResourceCallAuthenticationToken rcAuth = (ResourceCallAuthenticationToken) authentication;

    String token = (String) rcAuth.getPrincipal();
    OAuth2Authentication auth = loadAuthentication(token);

    if (auth == null) {
        throw new InvalidTokenException("Invalid token: " + token);
    }

    String resourceUri;
    try {
        resourceUri = getUriManager().getUriFromRequest(rcAuth.getRequestPath(), rcAuth.getHttpMethod(),
                auth.getAuthorities());
    } catch (IOException e) {
        throw new OAuth2Exception("Problem accessing resource descriptor");
    }

    String resourceID = resourceUri;// resourceStore.loadResourceByResourceUri(resourceUri);
    // test senza lettura db

    Collection<String> resourceIds = auth.getAuthorizationRequest().getScope();

    if (resourceID == null || resourceIds.isEmpty() || !resourceIds.contains(resourceID)) {
        throw new OAuth2AccessDeniedException(
                "Invalid token does not contain resource id (" + resourceUri + ")");
    }

    String authority = authServices.loadResourceAuthorityByResourceUri(resourceUri);
    if (ROLE_USER.equals(authority) && auth.isClientOnly()) {
        throw new OAuth2AccessDeniedException("Incorrect access method");
    }
    if (ROLE_CLIENT.equals(authority) && !auth.isClientOnly()) {
        throw new OAuth2AccessDeniedException("Incorrect access method");
    }

    auth.setDetails(authentication.getDetails());

    return auth;
}

From source file:org.pac4j.springframework.security.authentication.ClientAuthenticationProvider.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    logger.debug("authentication : {}", authentication);
    if (!supports(authentication.getClass())) {
        logger.debug("unsupported authentication class : {}", authentication.getClass());
        return null;
    }/*from  w w w  .  j  a v  a  2 s .  c o m*/
    final ClientAuthenticationToken token = (ClientAuthenticationToken) authentication;

    // get the credentials
    final Credentials credentials = (Credentials) authentication.getCredentials();
    logger.debug("credentials : {}", credentials);

    // get the right client
    final String clientName = token.getClientName();
    final Client client = this.clients.findClient(clientName);
    // get the user profile
    final UserProfile userProfile = client.getUserProfile(credentials, null);
    logger.debug("userProfile : {}", userProfile);

    // by default, no authorities
    Collection<? extends GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    // get user details and check them
    if (this.userDetailsService != null) {
        final ClientAuthenticationToken tmpToken = new ClientAuthenticationToken(credentials, clientName,
                userProfile, null);
        final UserDetails userDetails = this.userDetailsService.loadUserDetails(tmpToken);
        logger.debug("userDetails : {}", userDetails);
        if (userDetails != null) {
            this.userDetailsChecker.check(userDetails);
            authorities = userDetails.getAuthorities();
            logger.debug("authorities : {}", authorities);
        }
    }

    // new token with credentials (like previously) and user profile and
    // authorities
    final ClientAuthenticationToken result = new ClientAuthenticationToken(credentials, clientName, userProfile,
            authorities);
    result.setDetails(authentication.getDetails());
    logger.debug("result : {}", result);
    return result;
}

From source file:com.haulmont.restapi.auth.CubaUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    String ipAddress = request.getRemoteAddr();

    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        RestApiConfig config = configuration.getConfig(RestApiConfig.class);
        if (!config.getStandardAuthenticationEnabled()) {
            log.debug(//from  w  ww  .  ja  v a 2  s. c o  m
                    "Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");

            throw new InvalidGrantException("Authentication disabled");
        }

        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

        String login = (String) token.getPrincipal();

        UserSession session;
        try {
            String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());

            LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
            credentials.setIpAddress(ipAddress);
            credentials.setClientType(ClientType.REST_API);
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));

            //if the locale value is explicitly passed in the Accept-Language header then set its value to the
            //credentials. Otherwise, the locale of the user should be used
            Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
            if (locale != null) {
                credentials.setLocale(locale);
                credentials.setOverrideLocale(true);
            } else {
                credentials.setOverrideLocale(false);
            }

            session = authenticationService.login(credentials).getSession();
        } catch (AccountLockedException le) {
            log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
            throw new LockedException("User temporarily blocked");
        } catch (RestApiAccessDeniedException ex) {
            log.info("User is not allowed to use the REST API {}", login);
            throw new BadCredentialsException("User is not allowed to use the REST API");
        } catch (LoginException e) {
            log.info("REST API authentication failed: {} {}", login, ipAddress);
            throw new BadCredentialsException("Bad credentials");
        }

        AppContext.setSecurityContext(new SecurityContext(session));

        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(),
                getRoleUserAuthorities(authentication));
        @SuppressWarnings("unchecked")
        Map<String, String> details = (Map<String, String>) authentication.getDetails();
        details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
        result.setDetails(details);
        return result;
    }

    return null;
}

From source file:org.ambraproject.wombat.config.SpringSecurityConfiguration.java

private LogoutSuccessHandler getLogoutSuccessHandler() {
    return runtimeConfiguration.getCasConfiguration()
            .map(casConfiguration -> (LogoutSuccessHandler) (HttpServletRequest request,
                    HttpServletResponse response, Authentication authentication) -> {
                if (authentication != null && authentication.getDetails() != null) {
                    try {
                        request.getSession().invalidate();
                    } catch (IllegalStateException e) {
                        // session is already invalid, so nothing to do, but log as error since it may indicate a config issue
                        log.error("Attempted to log out of an already logged out session");
                    }//from   ww w. j  a v  a  2 s  .co m
                }

                validateHostname(request);
                String logoutServiceUrl = Link.toSitelessHandler()
                        .toPattern(requestMappingContextDictionary, LOGOUT_HANDLER_NAME).build().get(request);

                response.setStatus(HttpServletResponse.SC_OK);
                response.sendRedirect(casConfiguration.getLogoutUrl() + "?service="
                        + URLEncoder.encode(logoutServiceUrl, Charsets.UTF_8.name()));
            }).orElseThrow(CasConfigurationRequiredException::new);
}

From source file:org.apache.ranger.biz.SessionMgr.java

public UserSessionBase processSuccessLogin(int authType, String userAgent, HttpServletRequest httpRequest) {
    boolean newSessionCreation = true;
    UserSessionBase userSession = null;// w w  w .j a v  a 2s. com

    RangerSecurityContext context = RangerContextHolder.getSecurityContext();
    if (context != null) {
        userSession = context.getUserSession();
    }

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();

    String currentLoginId = authentication.getName();
    if (userSession != null) {
        if (validateUserSession(userSession, currentLoginId)) {
            newSessionCreation = false;
        }
    }

    if (newSessionCreation) {

        getSSOSpnegoAuthCheckForAPI(currentLoginId, httpRequest);
        // Need to build the UserSession
        XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
        if (gjUser == null) {
            logger.error("Error getting user for loginId=" + currentLoginId, new Exception());
            return null;
        }

        XXAuthSession gjAuthSession = new XXAuthSession();
        gjAuthSession.setLoginId(currentLoginId);
        gjAuthSession.setUserId(gjUser.getId());
        gjAuthSession.setAuthTime(DateUtil.getUTCDate());
        gjAuthSession.setAuthStatus(XXAuthSession.AUTH_STATUS_SUCCESS);
        gjAuthSession.setAuthType(authType);
        if (details != null) {
            gjAuthSession.setExtSessionId(details.getSessionId());
            gjAuthSession.setRequestIP(details.getRemoteAddress());
        }

        if (userAgent != null) {
            gjAuthSession.setRequestUserAgent(userAgent);
        }
        gjAuthSession.setDeviceType(httpUtil.getDeviceType(userAgent));
        HttpSession session = httpRequest.getSession();
        if (session != null) {
            if (session.getAttribute("auditLoginId") == null) {
                synchronized (session) {
                    if (session.getAttribute("auditLoginId") == null) {
                        boolean isDownloadLogEnabled = PropertiesUtil
                                .getBooleanProperty("ranger.downloadpolicy.session.log.enabled", false);
                        if (isDownloadLogEnabled) {
                            gjAuthSession = storeAuthSession(gjAuthSession);
                            session.setAttribute("auditLoginId", gjAuthSession.getId());
                        } else if (!StringUtils.isEmpty(httpRequest.getRequestURI())
                                && !(httpRequest.getRequestURI().contains("/secure/policies/download/")
                                        || httpRequest.getRequestURI().contains("/secure/download/"))) {
                            gjAuthSession = storeAuthSession(gjAuthSession);
                            session.setAttribute("auditLoginId", gjAuthSession.getId());
                        } else if (StringUtils.isEmpty(httpRequest.getRequestURI())) {
                            gjAuthSession = storeAuthSession(gjAuthSession);
                            session.setAttribute("auditLoginId", gjAuthSession.getId());
                        } else { //NOPMD
                            //do not log the details for download policy and tag
                        }
                    }
                }
            }
        }

        userSession = new UserSessionBase();
        userSession.setXXPortalUser(gjUser);
        userSession.setXXAuthSession(gjAuthSession);
        if (httpRequest.getAttribute("spnegoEnabled") != null
                && (boolean) httpRequest.getAttribute("spnegoEnabled")) {
            userSession.setSpnegoEnabled(true);
        }

        resetUserSessionForProfiles(userSession);
        resetUserModulePermission(userSession);

        Calendar cal = Calendar.getInstance();
        if (details != null) {
            logger.info("Login Success: loginId=" + currentLoginId + ", sessionId=" + gjAuthSession.getId()
                    + ", sessionId=" + details.getSessionId() + ", requestId=" + details.getRemoteAddress()
                    + ", epoch=" + cal.getTimeInMillis());
        } else {
            logger.info("Login Success: loginId=" + currentLoginId + ", sessionId=" + gjAuthSession.getId()
                    + ", details is null" + ", epoch=" + cal.getTimeInMillis());
        }

    }

    return userSession;
}