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

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

Introduction

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

Prototype

Collection<? extends GrantedAuthority> getAuthorities();

Source Link

Document

Set by an AuthenticationManager to indicate the authorities that the principal has been granted.

Usage

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  o  m*/
    newAuth.setDetails(auth.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}

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

private void setWicketRoles(Authentication authentication) {
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    String[] authorityRoles = new String[authorities.size()];
    int i = 0;//from w  w  w.ja  v a2s .c  o m
    for (GrantedAuthority authority : authorities) {
        String role = authority.getAuthority();
        authorityRoles[i] = role;
        i++;
    }
    roles = new Roles(authorityRoles);
}

From source file:org.broadleafcommerce.openadmin.server.security.service.AdminSecurityServiceImpl.java

@Override
@Transactional("blTransactionManager")
public AdminUser changePassword(PasswordChange passwordChange) {
    AdminUser user = readAdminUserByUserName(passwordChange.getUsername());
    user.setUnencodedPassword(passwordChange.getNewPassword());
    user = saveAdminUser(user);//w  ww.j av a 2 s . c o m
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
            passwordChange.getUsername(), passwordChange.getNewPassword(), auth.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authRequest);
    auth.setAuthenticated(false);
    return user;
}

From source file:org.cbioportal.security.spring.CancerStudyPermissionEvaluator.java

private Set<String> getGrantedAuthorities(Authentication authentication) {
    String appName = getAppName().toUpperCase();
    Set<String> allAuthorities = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
    Set<String> grantedAuthorities = new HashSet<>();

    if (filterGroupsByAppName()) {
        for (String au : allAuthorities) {
            if (au.toUpperCase().startsWith(appName + ":")) {
                grantedAuthorities.add(au.substring(appName.length() + 1).toUpperCase());
            }/*from  ww  w .  ja  v  a2s  . co m*/
        }
    } else {
        for (String au : allAuthorities) {
            grantedAuthorities.add(au.toUpperCase());
        }
    }

    // all users are allowed access to PUBLIC studies
    if (log.isDebugEnabled()) {
        log.debug("PUBLIC_CANCER_STUDIES_GROUP= "
                + ((PUBLIC_CANCER_STUDIES_GROUP == null) ? "null" : PUBLIC_CANCER_STUDIES_GROUP));
    }

    if (PUBLIC_CANCER_STUDIES_GROUP != null) {
        grantedAuthorities.add(PUBLIC_CANCER_STUDIES_GROUP.toUpperCase());
    }

    return grantedAuthorities;
}

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

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        return authentication;
    }/*  w  w  w  .  java2s. 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.LdapLoginAuthenticationManager.java

@Override
protected UaaUser userAuthenticated(Authentication request, UaaUser userFromRequest, UaaUser userFromDb) {
    boolean userModified = false;
    //we must check and see if the email address has changed between authentications
    if (request.getPrincipal() != null && request.getPrincipal() instanceof ExtendedLdapUserDetails) {
        if (haveUserAttributesChanged(userFromDb, userFromRequest)) {
            userFromDb = userFromDb//from   w w  w.  j a  v a 2 s  . c  o  m
                    .modifyAttributes(userFromRequest.getEmail(), userFromRequest.getGivenName(),
                            userFromRequest.getFamilyName(), userFromRequest.getPhoneNumber())
                    .modifyUsername(userFromRequest.getUsername());
            userModified = true;
        }
    }
    ExternalGroupAuthorizationEvent event = new ExternalGroupAuthorizationEvent(userFromDb, userModified,
            request.getAuthorities(), isAutoAddAuthorities());
    publish(event);
    return getUserDatabase().retrieveUserById(userFromDb.getId());
}

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

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        return authentication;
    }//  w ww .  j av a 2  s  .  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.oauth.token.UaaTokenStore.java

protected byte[] serializeOauth2Authentication(OAuth2Authentication auth2Authentication) {
    Authentication userAuthentication = auth2Authentication.getUserAuthentication();
    HashMap<String, Object> data = new HashMap<>();
    if (userAuthentication != null) {
        data.put(USER_AUTHENTICATION_UAA_PRINCIPAL,
                JsonUtils.writeValueAsString(userAuthentication.getPrincipal()));
        data.put(USER_AUTHENTICATION_AUTHORITIES,
                UaaStringUtils.getStringsFromAuthorities(userAuthentication.getAuthorities()));
    }/*from  w ww.j  a  v  a 2 s . c o m*/
    data.put(OAUTH2_REQUEST_PARAMETERS, auth2Authentication.getOAuth2Request().getRequestParameters());
    data.put(OAUTH2_REQUEST_CLIENT_ID, auth2Authentication.getOAuth2Request().getClientId());
    data.put(OAUTH2_REQUEST_AUTHORITIES,
            UaaStringUtils.getStringsFromAuthorities(auth2Authentication.getOAuth2Request().getAuthorities()));
    data.put(OAUTH2_REQUEST_APPROVED, auth2Authentication.getOAuth2Request().isApproved());
    data.put(OAUTH2_REQUEST_SCOPE, auth2Authentication.getOAuth2Request().getScope());
    data.put(OAUTH2_REQUEST_RESOURCE_IDS, auth2Authentication.getOAuth2Request().getResourceIds());
    data.put(OAUTH2_REQUEST_REDIRECT_URI, auth2Authentication.getOAuth2Request().getRedirectUri());
    data.put(OAUTH2_REQUEST_RESPONSE_TYPES, auth2Authentication.getOAuth2Request().getResponseTypes());

    //currently not serializing any of the
    //Map<String, Serializable > extensionProperties
    if (auth2Authentication.getOAuth2Request().getExtensions() != null
            && auth2Authentication.getOAuth2Request().getExtensions().size() > 0) {
        logger.warn("[oauth_code] Unable to serialize extensions:"
                + auth2Authentication.getOAuth2Request().getExtensions());
    }
    return JsonUtils.writeValueAsBytes(data);
}

From source file:org.cloudfoundry.identity.uaa.oauth.TokenKeyEndpoint.java

protected boolean includeSymmetricalKeys(Principal principal) {
    if (principal != null) {
        if (principal instanceof AnonymousAuthenticationToken) {
            return false;
        } else if (principal instanceof Authentication) {
            Authentication auth = (Authentication) principal;
            if (auth.getAuthorities() != null) {
                for (GrantedAuthority authority : auth.getAuthorities()) {
                    if ("uaa.resource".equals(authority.getAuthority())) {
                        return true;
                    }//from  w w w  .  ja  v a2  s .c  o m
                }
            }
        }
    }
    return false;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenStore.java

protected byte[] serializeOauth2Authentication(OAuth2Authentication auth2Authentication) {
    Authentication userAuthentication = auth2Authentication.getUserAuthentication();
    HashMap<String, Object> data = new HashMap<>();
    if (userAuthentication != null) {
        if (userAuthentication instanceof UaaAuthentication) {
            data.put(USER_AUTHENTICATION_UAA_AUTHENTICATION, JsonUtils.writeValueAsString(userAuthentication));
        } else {/*from   w  ww. j a  v a  2  s  . c  o  m*/
            data.put(USER_AUTHENTICATION_UAA_PRINCIPAL,
                    JsonUtils.writeValueAsString(userAuthentication.getPrincipal()));
            data.put(USER_AUTHENTICATION_AUTHORITIES,
                    UaaStringUtils.getStringsFromAuthorities(userAuthentication.getAuthorities()));
        }
    }
    data.put(OAUTH2_REQUEST_PARAMETERS, auth2Authentication.getOAuth2Request().getRequestParameters());
    data.put(OAUTH2_REQUEST_CLIENT_ID, auth2Authentication.getOAuth2Request().getClientId());
    data.put(OAUTH2_REQUEST_AUTHORITIES,
            UaaStringUtils.getStringsFromAuthorities(auth2Authentication.getOAuth2Request().getAuthorities()));
    data.put(OAUTH2_REQUEST_APPROVED, auth2Authentication.getOAuth2Request().isApproved());
    data.put(OAUTH2_REQUEST_SCOPE, auth2Authentication.getOAuth2Request().getScope());
    data.put(OAUTH2_REQUEST_RESOURCE_IDS, auth2Authentication.getOAuth2Request().getResourceIds());
    data.put(OAUTH2_REQUEST_REDIRECT_URI, auth2Authentication.getOAuth2Request().getRedirectUri());
    data.put(OAUTH2_REQUEST_RESPONSE_TYPES, auth2Authentication.getOAuth2Request().getResponseTypes());

    //currently not serializing any of the
    //Map<String, Serializable > extensionProperties
    if (auth2Authentication.getOAuth2Request().getExtensions() != null
            && auth2Authentication.getOAuth2Request().getExtensions().size() > 0) {
        logger.warn("[oauth_code] Unable to serialize extensions:"
                + auth2Authentication.getOAuth2Request().getExtensions());
    }
    return JsonUtils.writeValueAsBytes(data);
}