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.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);// w  ww .  ja  v  a 2  s. 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 ww  .  jav  a2 s .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.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());//from   w w  w  . j  a  v a  2  s .c om
    newAuth.setDetails(auth.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}

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

public static String getDomain() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    String domainKey = auth != null && auth.getDetails() instanceof SyncopeAuthenticationDetails
            ? SyncopeAuthenticationDetails.class.cast(auth.getDetails()).getDomain()
            : null;//from ww w.j  a  v a  2  s .co  m
    if (StringUtils.isBlank(domainKey)) {
        domainKey = SyncopeConstants.MASTER_DOMAIN;
    }

    return domainKey;
}

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;
    }//w w  w .j  a  v a  2  s  . 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;//  w  w w.  j a va2 s.c o m

    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.apromore.service.impl.ProcessServiceImpl.java

/**
 * @see org.apromore.service.ProcessService#exportProcess(String, Integer, String, Version, String, String, boolean, java.util.Set)
 * {@inheritDoc}//from  w  w  w  . ja v a 2s.co  m
 */
@Override
public ExportFormatResultType exportProcess(final String name, final Integer processId, final String branch,
        final Version version, final String format, final String annName, final boolean withAnn,
        Set<RequestParameterType<?>> canoniserProperties) throws ExportFormatException {
    try {
        // Debug tracing of the authenticated principal
        org.springframework.security.core.Authentication auth = org.springframework.security.core.context.SecurityContextHolder
                .getContext().getAuthentication();
        if (auth != null) {
            LOGGER.info("Authentication principal=" + auth.getPrincipal() + " details=" + auth.getDetails()
                    + " thread=" + Thread.currentThread());
        } else {
            LOGGER.info("Authentication is null");
        }

        ExportFormatResultType exportResult = new ExportFormatResultType();

        // Work out if we are looking at the original format or native format for this model.
        if (isRequestForNativeFormat(processId, branch, version, format)) {
            exportResult.setNative(new DataHandler(new ByteArrayDataSource(
                    nativeRepo.getNative(processId, branch, version.toString(), format).getContent(),
                    "text/xml")));
        } else if (isRequestForAnnotationsOnly(format)) {
            exportResult
                    .setNative(
                            new DataHandler(new ByteArrayDataSource(
                                    annotationRepo.getAnnotation(processId, branch, version.toString(),
                                            AnnotationHelper.getAnnotationName(annName)).getContent(),
                                    "text/xml")));
        } else {
            CanonicalProcessType cpt = getProcessModelVersion(processId, name, branch, version, false);
            Process process;
            if (format.equals(Constants.CANONICAL)) {
                exportResult.setNative(new DataHandler(
                        new ByteArrayDataSource(canoniserSrv.CPFtoString(cpt), Constants.XML_MIMETYPE)));
            } else {
                DecanonisedProcess dp;
                AnnotationsType anf = null;
                process = processRepo.findOne(processId);
                if (withAnn) {
                    Annotation ann = annotationRepo.getAnnotation(processId, branch, version.toString(),
                            annName);
                    if (ann != null) {
                        String annotation = ann.getContent();
                        if (annotation != null && !annotation.equals("")) {
                            ByteArrayDataSource dataSource = new ByteArrayDataSource(annotation,
                                    Constants.XML_MIMETYPE);
                            anf = ANFSchema.unmarshalAnnotationFormat(dataSource.getInputStream(), false)
                                    .getValue();
                        }
                    }

                    if (ann != null && !process.getNativeType().getNatType()
                            .equalsIgnoreCase(ann.getNatve().getNativeType().getNatType())) {
                        anf = annotationSrv.preProcess(ann.getNatve().getNativeType().getNatType(), format, cpt,
                                anf);
                    } else {
                        anf = annotationSrv.preProcess(process.getNativeType().getNatType(), format, cpt, anf);
                    }
                } else if (annName == null) {
                    anf = annotationSrv.preProcess(null, format, cpt, null);
                }

                dp = canoniserSrv.deCanonise(format, cpt, anf, canoniserProperties);

                exportResult.setMessage(PluginHelper.convertFromPluginMessages(dp.getMessages()));
                exportResult.setNative(
                        new DataHandler(new ByteArrayDataSource(dp.getNativeFormat(), Constants.XML_MIMETYPE)));
            }
        }

        return exportResult;
    } catch (Exception e) {
        LOGGER.error("Failed to export process model {} to format {}", name, format);
        LOGGER.error("Original exception was: ", e);
        throw new ExportFormatException(e);
    }
}

From source file:org.apromore.service.impl.ProcessServiceImpl.java

/**
 * @see org.apromore.service.ProcessService#getBPMNRepresentation(String, Integer, String, Version)
 * {@inheritDoc}//from  ww w.ja va2  s  .  c  o  m
 */
@Override
public String getBPMNRepresentation(final String name, final Integer processId, final String branch,
        final Version version) throws RepositoryException {
    String xmlBPMNProcess;
    String format = "BPMN 2.0";
    String annName = "BPMN 2.0";

    try {
        // Debug tracing of the authenticated principal
        org.springframework.security.core.Authentication auth = org.springframework.security.core.context.SecurityContextHolder
                .getContext().getAuthentication();
        if (auth != null) {
            LOGGER.info("Authentication principal=" + auth.getPrincipal() + " details=" + auth.getDetails()
                    + " thread=" + Thread.currentThread());
        } else {
            LOGGER.info("Authentication is null");
        }

        // Work out if we are looking at the original format or native format for this model.
        if (isRequestForNativeFormat(processId, branch, version, format)) {
            xmlBPMNProcess = nativeRepo.getNative(processId, branch, version.toString(), format).getContent();
            LOGGER.info("native");
        } else {
            LOGGER.info("notNative");
            CanonicalProcessType cpt = getProcessModelVersion(processId, name, branch, version, false);
            Process process = processRepo.findOne(processId);
            DecanonisedProcess dp;
            AnnotationsType anf = null;

            Annotation ann = annotationRepo.getAnnotation(processId, branch, version.toString(), annName);
            if (ann != null) {
                String annotation = ann.getContent();
                if (annotation != null && !annotation.equals("")) {
                    ByteArrayDataSource dataSource = new ByteArrayDataSource(annotation,
                            Constants.XML_MIMETYPE);
                    anf = ANFSchema.unmarshalAnnotationFormat(dataSource.getInputStream(), false).getValue();
                }
            }

            if (ann != null && !process.getNativeType().getNatType()
                    .equalsIgnoreCase(ann.getNatve().getNativeType().getNatType())) {
                anf = annotationSrv.preProcess(ann.getNatve().getNativeType().getNatType(), format, cpt, anf);
            } else {
                anf = annotationSrv.preProcess(process.getNativeType().getNatType(), format, cpt, anf);
            }
            dp = canoniserSrv.deCanonise(format, cpt, anf, new HashSet<RequestParameterType<?>>());
            xmlBPMNProcess = IOUtils.toString(dp.getNativeFormat(), "UTF-8");
        }

        //LOGGER.info("[new method] PROCESS:\n" + xmlBPMNProcess);
        return xmlBPMNProcess;

    } catch (Exception e) {
        LOGGER.error("Failed to retrive the process!");
        LOGGER.error("Original exception was: ", e);
        throw new RepositoryException(e);
    }
}

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

@Override
public Authentication authenticate(Authentication req) throws AuthenticationException {
    logger.debug("Processing authentication request for " + req.getName());

    if (req.getCredentials() == null) {
        BadCredentialsException e = new BadCredentialsException("No password supplied");
        publish(new AuthenticationFailureBadCredentialsEvent(req, e));
        throw e;//from w  w w  . j  a  va  2s .c  om
    }

    UaaUser user = getUaaUser(req);

    if (user == null) {
        logger.debug("No user named '" + req.getName() + "' was found for origin:" + origin);
        publish(new UserNotFoundEvent(req));
    } else {
        if (!accountLoginPolicy.isAllowed(user, req)) {
            logger.warn("Login policy rejected authentication for " + user.getUsername() + ", " + user.getId()
                    + ". Ignoring login request.");
            AuthenticationPolicyRejectionException e = new AuthenticationPolicyRejectionException(
                    "Your account has been locked because of too many failed attempts to login.");
            publish(new AuthenticationFailureLockedEvent(req, e));
            throw e;
        }

        boolean passwordMatches = ((CharSequence) req.getCredentials()).length() != 0
                && encoder.matches((CharSequence) req.getCredentials(), user.getPassword());

        if (!passwordMatches) {
            logger.debug("Password did not match for user " + req.getName());
            publish(new UserAuthenticationFailureEvent(user, req));
        } else {
            logger.debug(
                    "Password successfully matched for userId[" + user.getUsername() + "]:" + user.getId());

            if (!(allowUnverifiedUsers && user.isLegacyVerificationBehavior()) && !user.isVerified()) {
                publish(new UnverifiedUserAuthenticationEvent(user, req));
                logger.debug("Account not verified: " + user.getId());
                throw new AccountNotVerifiedException("Account not verified");
            }

            checkPasswordExpired(user.getPasswordLastModified());

            UaaAuthentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(),
                    (UaaAuthenticationDetails) req.getDetails());

            success.setAuthenticationMethods(Collections.singleton("pwd"));
            Date passwordNewerThan = getPasswordNewerThan();
            if (passwordNewerThan != null) {
                if (user.getPasswordLastModified() == null
                        || (passwordNewerThan.getTime() > user.getPasswordLastModified().getTime())) {
                    logger.info("Password change required for user: " + user.getEmail());
                    throw new PasswordChangeRequiredException(success, "User password needs to be changed");
                }
            }

            if (user.isPasswordChangeRequired()) {
                logger.info("Password change required for user: " + user.getEmail());
                throw new PasswordChangeRequiredException(success, "User password needs to be changed");
            }
            publish(new UserAuthenticationSuccessEvent(user, success));

            return success;
        }
    }

    BadCredentialsException e = new BadCredentialsException("Bad credentials");
    publish(new AuthenticationFailureBadCredentialsEvent(req, e));
    throw e;
}

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

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

    if (!(authentication instanceof AuthzAuthenticationRequest)) {
        return null;
    }/*  ww w. j av  a 2 s  .c  o  m*/

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

    ExpiringCode expiringCode = doRetrieveCode(code);
    Map<String, String> codeData = null;
    try {
        if (expiringCode == null) {
            logger.debug("Autologin code has expired");
            throw new InvalidCodeException("expired_code", "Expired code", 422);
        }
        codeData = JsonUtils.readValue(expiringCode.getData(), new TypeReference<Map<String, String>>() {
        });
        if (!isAutologinCode(expiringCode.getIntent(), codeData.get("action"))) {
            logger.debug("Code is not meant for autologin");
            throw new InvalidCodeException("invalid_code", "Not an autologin code", 422);
        }
    } catch (JsonUtils.JsonUtilException x) {
        throw new BadCredentialsException("JsonConversion error", x);
    }

    String userId = codeData.get("user_id");
    String clientId = codeData.get(OAuth2Utils.CLIENT_ID);

    if (clientId == null) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client id missing");
    }

    try {
        clientDetailsService.loadClientByClientId(clientId);
    } catch (NoSuchClientException x) {
        throw new BadCredentialsException("Cannot redeem provided code for user, client is missing");
    }

    UaaUser user = null;

    try {
        user = userDatabase.retrieveUserById(userId);
    } catch (UsernameNotFoundException e) {
        throw new BadCredentialsException("Cannot redeem provided code for user, user is missing");
    }

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

    UaaPrincipal principal = new UaaPrincipal(user);

    return new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES,
            (UaaAuthenticationDetails) authentication.getDetails());
}