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

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

Introduction

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

Prototype

public void setDetails(Object details) 

Source Link

Usage

From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java

private Authentication getGrantedAuthority(Authentication authentication) {
    UsernamePasswordAuthenticationToken result = null;
    if (authentication != null && authentication.isAuthenticated()) {
        final List<GrantedAuthority> grantedAuths = getAuthorities(authentication.getName().toString());
        final UserDetails userDetails = new User(authentication.getName().toString(),
                authentication.getCredentials().toString(), grantedAuths);
        result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(),
                grantedAuths);//from  w  w w  .  j a  v a2s. c o m
        result.setDetails(authentication.getDetails());
        return result;
    }
    return authentication;
}

From source file:org.apache.syncope.core.misc.security.SyncopeAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = { BadCredentialsException.class, DisabledException.class })
public Authentication authenticate(final Authentication authentication) {
    boolean authenticated = false;
    User user = null;/*from  w  w w .ja  v  a  2s.c  o m*/

    String username = authentication.getName();
    if (anonymousUser.equals(username)) {
        authenticated = authentication.getCredentials().toString().equals(anonymousKey);
    } else if (adminUser.equals(username)) {
        authenticated = encryptor.verify(authentication.getCredentials().toString(),
                CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword);
    } else {
        user = userDAO.find(username);

        if (user != null) {
            if (user.isSuspended() != null && user.isSuspended()) {
                throw new DisabledException("User " + user.getUsername() + " is suspended");
            }

            CPlainAttr authStatuses = confDAO.find("authentication.statuses");
            if (authStatuses != null && !authStatuses.getValuesAsStrings().contains(user.getStatus())) {
                throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
            }

            authenticated = authenticate(user, authentication.getCredentials().toString());

            updateLoginAttributes(user, authenticated);
        }
    }

    UsernamePasswordAuthenticationToken token;
    if (authenticated) {
        token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), null, userDetailsService
                .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities());

        token.setDetails(authentication.getDetails());

        auditManager.audit(AuditElements.EventCategoryType.REST, "AuthenticationController", null, "login",
                Result.SUCCESS, null, authenticated, authentication,
                "Successfully authenticated, with groups: " + token.getAuthorities());

        LOG.debug("User {} successfully authenticated, with groups {}", authentication.getPrincipal(),
                token.getAuthorities());
    } else {
        auditManager.audit(AuditElements.EventCategoryType.REST, "AuthenticationController", null, "login",
                Result.FAILURE, null, authenticated, authentication,
                "User " + authentication.getPrincipal() + " not authenticated");

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return token;
}

From source file:org.apache.syncope.core.persistence.jpa.inner.MultitenancyTest.java

@BeforeClass
public static void setAuthContext() {
    List<GrantedAuthority> authorities = CollectionUtils.collect(StandardEntitlement.values(),
            new Transformer<String, GrantedAuthority>() {

                @Override/*from  ww w . j  a v a 2 s .co m*/
                public GrantedAuthority transform(final String entitlement) {
                    return new SyncopeGrantedAuthority(entitlement, SyncopeConstants.ROOT_REALM);
                }
            }, new ArrayList<GrantedAuthority>());

    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
            new org.springframework.security.core.userdetails.User("admin", "FAKE_PASSWORD", authorities),
            "FAKE_PASSWORD", authorities);
    auth.setDetails(new SyncopeAuthenticationDetails("Two"));
    SecurityContextHolder.getContext().setAuthentication(auth);
}

From source file:org.apache.syncope.core.spring.security.AuthContextUtils.java

public static void updateUsername(final String newUsername) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(
            new User(newUsername, "FAKE_PASSWORD", auth.getAuthorities()), auth.getCredentials(),
            auth.getAuthorities());//  w  w  w.jav a  2 s . c om
    newAuth.setDetails(auth.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}

From source file:org.apache.syncope.core.spring.security.AuthContextUtils.java

private static void setFakeAuth(final String domain) {
    List<GrantedAuthority> authorities = EntitlementsHolder.getInstance().getValues().stream()
            .map(entitlement -> new SyncopeGrantedAuthority(entitlement, SyncopeConstants.ROOT_REALM))
            .collect(Collectors.toList());

    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
            new User(ApplicationContextProvider.getBeanFactory().getBean("adminUser", String.class),
                    "FAKE_PASSWORD", authorities),
            "FAKE_PASSWORD", authorities);
    auth.setDetails(new SyncopeAuthenticationDetails(domain));
    SecurityContextHolder.getContext().setAuthentication(auth);
}

From source file:org.apache.syncope.core.spring.security.SyncopeAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) {
    String domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain();
    if (StringUtils.isBlank(domainKey)) {
        domainKey = SyncopeConstants.MASTER_DOMAIN;
    }//from   w ww .  j  a va2s . co m
    SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).setDomain(domainKey);

    Boolean authenticated;
    if (anonymousUser.equals(authentication.getName())) {
        authenticated = authentication.getCredentials().toString().equals(anonymousKey);
    } else if (adminUser.equals(authentication.getName())) {
        if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) {
            authenticated = encryptor.verify(authentication.getCredentials().toString(),
                    CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword);
        } else {
            final String domainToFind = domainKey;
            authenticated = AuthContextUtils.execWithAuthContext(SyncopeConstants.MASTER_DOMAIN,
                    new Executable<Boolean>() {

                        @Override
                        public Boolean exec() {
                            Domain domain = dataAccessor.findDomain(domainToFind);

                            return encryptor.verify(authentication.getCredentials().toString(),
                                    domain.getAdminCipherAlgorithm(), domain.getAdminPwd());
                        }
                    });
        }
    } else {
        final Pair<String, Boolean> authResult = AuthContextUtils.execWithAuthContext(domainKey,
                new Executable<Pair<String, Boolean>>() {

                    @Override
                    public Pair<String, Boolean> exec() {
                        return dataAccessor.authenticate(authentication);
                    }
                });
        authenticated = authResult.getValue();
        if (authenticated != null && !authenticated) {
            AuthContextUtils.execWithAuthContext(domainKey, new Executable<Void>() {

                @Override
                public Void exec() {
                    provisioningManager.internalSuspend(authResult.getKey());
                    return null;
                }
            });
        }
    }

    final boolean isAuthenticated = authenticated != null && authenticated;
    UsernamePasswordAuthenticationToken token;
    if (isAuthenticated) {
        token = AuthContextUtils.execWithAuthContext(domainKey,
                new Executable<UsernamePasswordAuthenticationToken>() {

                    @Override
                    public UsernamePasswordAuthenticationToken exec() {
                        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                                authentication.getPrincipal(), null,
                                userDetailsService.loadUserByUsername(authentication.getPrincipal().toString())
                                        .getAuthorities());
                        token.setDetails(authentication.getDetails());

                        dataAccessor.audit(AuditElements.EventCategoryType.LOGIC,
                                AuditElements.AUTHENTICATION_CATEGORY, null, AuditElements.LOGIN_EVENT,
                                Result.SUCCESS, null, isAuthenticated, authentication,
                                "Successfully authenticated, with entitlements: " + token.getAuthorities());
                        return token;
                    }
                });

        LOG.debug("User {} successfully authenticated, with entitlements {}", authentication.getPrincipal(),
                token.getAuthorities());
    } else {
        AuthContextUtils.execWithAuthContext(domainKey, new Executable<Void>() {

            @Override
            public Void exec() {
                dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY,
                        null, AuditElements.LOGIN_EVENT, Result.FAILURE, null, isAuthenticated, authentication,
                        "User " + authentication.getPrincipal() + " not authenticated");
                return null;
            }
        });

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return token;
}

From source file:org.apache.syncope.core.spring.security.UsernamePasswordAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) {
    String domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain();

    final String[] username = new String[1];
    Boolean authenticated;//from w  w w .j  a  v  a  2  s . c  om

    if (anonymousUser.equals(authentication.getName())) {
        username[0] = anonymousUser;
        credentialChecker.checkIsDefaultAnonymousKeyInUse();
        authenticated = authentication.getCredentials().toString().equals(anonymousKey);
    } else if (adminUser.equals(authentication.getName())) {
        username[0] = adminUser;
        if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) {
            credentialChecker.checkIsDefaultAdminPasswordInUse();
            authenticated = ENCRYPTOR.verify(authentication.getCredentials().toString(),
                    CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword);
        } else {
            final String domainToFind = domainKey;
            authenticated = AuthContextUtils.execWithAuthContext(SyncopeConstants.MASTER_DOMAIN, () -> {
                Domain domain = dataAccessor.findDomain(domainToFind);

                return ENCRYPTOR.verify(authentication.getCredentials().toString(),
                        domain.getAdminCipherAlgorithm(), domain.getAdminPwd());
            });
        }
    } else {
        final Pair<User, Boolean> authResult = AuthContextUtils.execWithAuthContext(domainKey,
                () -> dataAccessor.authenticate(authentication));
        authenticated = authResult.getValue();
        if (authResult.getLeft() != null && authResult.getRight() != null) {
            username[0] = authResult.getLeft().getUsername();

            if (!authResult.getRight()) {
                AuthContextUtils.execWithAuthContext(domainKey, () -> {
                    provisioningManager.internalSuspend(authResult.getLeft().getKey());
                    return null;
                });
            }
        }
    }
    if (username[0] == null) {
        username[0] = authentication.getPrincipal().toString();
    }

    final boolean isAuthenticated = authenticated != null && authenticated;
    UsernamePasswordAuthenticationToken token;
    if (isAuthenticated) {
        token = AuthContextUtils.execWithAuthContext(domainKey, () -> {
            UsernamePasswordAuthenticationToken token1 = new UsernamePasswordAuthenticationToken(username[0],
                    null, dataAccessor.getAuthorities(username[0]));
            token1.setDetails(authentication.getDetails());
            dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY,
                    null, AuditElements.LOGIN_EVENT, Result.SUCCESS, null, isAuthenticated, authentication,
                    "Successfully authenticated, with entitlements: " + token1.getAuthorities());
            return token1;
        });

        LOG.debug("User {} successfully authenticated, with entitlements {}", username[0],
                token.getAuthorities());
    } else {
        AuthContextUtils.execWithAuthContext(domainKey, () -> {
            dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY,
                    null, AuditElements.LOGIN_EVENT, Result.FAILURE, null, isAuthenticated, authentication,
                    "User " + username[0] + " not authenticated");
            return null;
        });

        LOG.debug("User {} not authenticated", username[0]);

        throw new BadCredentialsException("User " + username[0] + " not authenticated");
    }

    return token;
}

From source file:org.artifactory.webapp.servlet.AccessFilter.java

@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
private void useAnonymousIfPossible(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
        SecurityContext securityContext) throws IOException, ServletException {
    boolean anonAccessEnabled = context.getAuthorizationService().isAnonAccessEnabled();
    if (anonAccessEnabled || authInterceptors.accept(request)) {
        log.debug("Using anonymous");
        Authentication authentication = getNonUiCachedAuthentication(request);
        if (authentication == null) {
            log.debug("Creating the Anonymous token");
            final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    UserInfo.ANONYMOUS, "");
            AuthenticationDetailsSource ads = new HttpAuthenticationDetailsSource();
            //noinspection unchecked
            authRequest.setDetails(ads.buildDetails(request));
            // explicitly ask for the default spring authentication manager by name (we have another one which
            // is only used by the basic authentication filter)
            AuthenticationManager authenticationManager = context.beanForType("authenticationManager",
                    AuthenticationManager.class);
            authentication = authenticationManager.authenticate(authRequest);
            if (authentication != null && authentication.isAuthenticated()
                    && !RequestUtils.isUiRequest(request)) {
                AuthCacheKey authCacheKey = new AuthCacheKey(authFilter.getCacheKey(request),
                        request.getRemoteAddr());
                nonUiAuthCache.put(authCacheKey, authentication);
                log.debug("Added anonymous authentication {} to cache", authentication);
            }//from  w  ww .j a  va2  s  .com
        } else {
            log.debug("Using cached anonymous authentication");
        }
        useAuthentication(request, response, chain, authentication, securityContext);
    } else {
        if (authFilter.acceptEntry(request)) {
            log.debug("Sending request requiring authentication");
            authFilter.commence(request, response,
                    new InsufficientAuthenticationException("Authentication is required"));
        } else {
            log.debug("No filter or entry just chain");
            chain.doFilter(request, response);
        }
    }
}

From source file:org.artifactory.webapp.wicket.application.ArtifactoryWebSession.java

@Override
public boolean authenticate(final String username, final String password) {
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,
            password);//  w  ww.  ja  va2s. c o m
    HttpServletRequest servletRequest = WicketUtils.getHttpServletRequest();
    HttpServletResponse servletResponse = WicketUtils.getHttpServletResponse();
    replaceSession(); // protect against session fixation
    WebAuthenticationDetails details = new UiAuthenticationDetails(servletRequest, servletResponse);
    authenticationToken.setDetails(details);
    boolean authenticated;
    try {
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        authenticated = authentication.isAuthenticated();
        if (authenticated) {
            setAuthentication(authentication);
            if (StringUtils.isNotBlank(username) && (!username.equals(UserInfo.ANONYMOUS))) {

                //Save the user's last login info in the web session so we can display it in the welcome page
                ArtifactoryContext context = ContextHelper.get();
                SecurityService securityService = context.beanForType(SecurityService.class);
                SerializablePair<String, Long> lastLoginInfo = securityService.getUserLastLoginInfo(username);
                ArtifactoryWebSession.get().setLastLoginInfo(lastLoginInfo);

                //Update the user's current login info in the database
                String remoteAddress = new HttpAuthenticationDetails(servletRequest).getRemoteAddress();
                securityService.updateUserLastLogin(username, remoteAddress, System.currentTimeMillis());
            }
        }
    } catch (AuthenticationException e) {
        authenticated = false;
        AccessLogger.loginDenied(authenticationToken);
        if (log.isDebugEnabled()) {
            log.debug("Failed to authenticate " + username, e);
        }
    }
    return authenticated;
}

From source file:org.asqatasun.webapp.controller.LoginController.java

private void doGuestAutoLogin(HttpServletRequest request, String guestUser) {
    try {//from   w  ww . j  a  va 2  s.com
        // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(guestUser,
                guestPassword);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication guest = authenticationManager.authenticate(token);
        Logger.getLogger(this.getClass()).debug("Logging in with [{}]" + guest.getPrincipal());
        SecurityContextHolder.getContext().setAuthentication(guest);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        Logger.getLogger(this.getClass()).debug("Failure in autoLogin", e);
    }
}