Example usage for org.springframework.security.oauth2.common OAuth2AccessToken getAdditionalInformation

List of usage examples for org.springframework.security.oauth2.common OAuth2AccessToken getAdditionalInformation

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common OAuth2AccessToken getAdditionalInformation.

Prototype

Map<String, Object> getAdditionalInformation();

Source Link

Document

The additionalInformation map is used by the token serializers to export any fields used by extensions of OAuth.

Usage

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) {

    Map<String, Object> vars = new LinkedHashMap<>();
    Map<String, String> keys = new HashMap<>();

    if (isNull(accessToken)) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }//from  ww w.ja  v a 2  s.c  om

    vars.put("access_token", accessToken.getValue());
    vars.put("token_type", accessToken.getTokenType());
    String state = authorizationRequest.getState();

    if (nonNull(state)) {
        vars.put("state", state);
    }

    Date expiration = accessToken.getExpiration();
    if (nonNull(expiration)) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        vars.put("expires_in", expires_in);
    }

    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (isNull(originalScope)
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope()));
    }

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (nonNull(value)) {
            keys.put("extra_" + key, key);
            vars.put("extra_" + key, value);
        }
    }
    // Do not include the refresh token (even if there is one)
    return append(authorizationRequest.getRedirectUri(), vars, keys, true);
}

From source file:com.acc.conv.Oauth2AccessTokenConverter.java

@Override
public void marshal(final Object source, final HierarchicalStreamWriter writerOrig,
        final MarshallingContext context) {
    final OAuth2AccessToken token = (OAuth2AccessToken) source;
    final ExtendedHierarchicalStreamWriter writer = (ExtendedHierarchicalStreamWriter) writerOrig
            .underlyingWriter();/*from   w  ww .  j  a  v  a2  s  .  c  o  m*/

    writer.startNode(OAuth2AccessToken.ACCESS_TOKEN, String.class);
    writer.setValue(formattedValue(token.getValue()));
    writer.endNode();

    writer.startNode(OAuth2AccessToken.TOKEN_TYPE, String.class);
    writer.setValue(formattedValue(token.getTokenType()));
    writer.endNode();

    final OAuth2RefreshToken refreshToken = token.getRefreshToken();
    if (refreshToken != null) {
        writer.startNode(OAuth2AccessToken.REFRESH_TOKEN, String.class);
        writer.setValue(formattedValue(refreshToken.getValue()));
        writer.endNode();

    }
    final Date expiration = token.getExpiration();
    if (expiration != null) {
        final long now = System.currentTimeMillis();
        writer.startNode(OAuth2AccessToken.EXPIRES_IN, Integer.class);
        writer.setValue(String.valueOf((expiration.getTime() - now) / 1000));
        writer.endNode();
    }
    final Set<String> scope = token.getScope();
    if (scope != null && !scope.isEmpty()) {
        final StringBuffer scopes = new StringBuffer();
        for (final String s : scope) {
            Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope);
            scopes.append(s);
            scopes.append(' ');
        }

        writer.startNode(OAuth2AccessToken.SCOPE, String.class);
        writer.setValue(formattedValue(scopes.substring(0, scopes.length() - 1)));
        writer.endNode();
    }
    final Map<String, Object> additionalInformation = token.getAdditionalInformation();
    for (final String key : additionalInformation.keySet()) {
        writer.startNode(key, String.class);
        writer.setValue(formattedValue(String.valueOf(additionalInformation.get(key))));
        writer.endNode();
    }
}

From source file:com.avego.oauth.migration.OauthDataMigrator.java

/**
 * This migrates the oauth access tokens
 * @throws IOException If an IO error occurs such as when serializing/deserializing data
 * @throws ClassNotFoundException If a class not found when serializing/deserializing data
 * @throws InvocationTargetException If an invocation target exception occurs when using reflection to convert to the new objects
 * @throws IllegalAccessException If an IllegalAccessException exception occurs when using reflection to convert to the new objects
 * @throws NoSuchMethodException If a NoSuchMethodException exception occurs when using reflection to convert to the new objects
 * @throws InstantiationException/*w  ww  .  j  ava2  s.  c  o m*/
 * @throws IllegalArgumentException
 */
@SuppressWarnings("unchecked")
protected void migrateAccessTokens() throws IOException, ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, IllegalArgumentException, InstantiationException {

    int numTokens = this.dao.countUnmigratedAccessTokens();
    int pageSize = PAGE_SIZE;

    int numMigrated = 0;
    System.out.println("Starting Migrating " + numTokens + " access token(s) ...");

    while (numTokens > 0) {

        List<OauthAccessTokenRecord> accessTokens = this.dao.getUnmigratedOauthAccessTokenRecords(pageSize);

        for (OauthAccessTokenRecord tokenRecord : accessTokens) {

            String oldTokenId = tokenRecord.getTokenId();
            System.out.println("Migrating token with id: " + oldTokenId + "...");

            String newTokenId = this.dao.generateNewTokenKey(tokenRecord.getTokenId());
            String newRefreshToken = this.dao.generateNewTokenKey(tokenRecord.getRefreshToken());

            if (this.removeRefreshTokens) {
                newRefreshToken = null;
            }

            System.out.println("New token id: " + newTokenId);
            System.out.println("New refresh token id: " + newRefreshToken);

            // deserialize the token, note this is backward compatible
            OAuth2AccessToken accessToken = null;
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(tokenRecord.getToken()));
            try {
                Object obj = ois.readObject();
                accessToken = (OAuth2AccessToken) obj;
            } finally {
                ois.close();
            }

            // replace the token value in the access token..
            if (this.serializeNewTokenValues) {

                Constructor<OAuth2AccessToken> constructor = null;

                // see if it has a set value method
                Method setValueMethod = MethodUtils.getAccessibleMethod(accessToken.getClass(), "setValue",
                        String.class);
                if (setValueMethod != null) {
                    Object res = setValueMethod.invoke(accessToken, newTokenId);
                    if (res != null && res instanceof OAuth2AccessToken) {
                        accessToken = (OAuth2AccessToken) res;
                    }
                } else {

                    // look for constructors that we can use
                    constructor = (Constructor<OAuth2AccessToken>) ConstructorUtils
                            .getAccessibleConstructor(accessToken.getClass(), String.class);
                    if (constructor != null) {

                        OAuth2AccessToken newAccessToken = constructor.newInstance(newTokenId);

                        // we also need to invoke setters for other fields
                        MethodUtils.invokeMethod(newAccessToken, "setAdditionalInformation",
                                accessToken.getAdditionalInformation());
                        MethodUtils.invokeMethod(newAccessToken, "setExpiration", accessToken.getExpiration());
                        MethodUtils.invokeMethod(newAccessToken, "setScope", accessToken.getScope());
                        MethodUtils.invokeMethod(newAccessToken, "setTokenType", accessToken.getTokenType());

                        accessToken = newAccessToken;

                    } else {
                        throw new IllegalStateException("The access token with the class: "
                                + accessToken.getClass().getName()
                                + " did not have a set value method nor a constructor taking a string which we need to update its token value");
                    }

                }

                // we also need to overwrite the refresh token
                String newRefreshTokenValue = this.dao
                        .generateNewTokenKey(accessToken.getRefreshToken().getValue());
                OAuth2RefreshToken refreshToken = replaceOAuth2RefreshTokenValue(accessToken.getRefreshToken(),
                        newRefreshTokenValue);
                MethodUtils.invokeMethod(accessToken, "setRefreshToken", refreshToken);
            }

            if (this.removeRefreshTokens) {
                MethodUtils.invokeMethod(accessToken, "setRefreshToken", new Object[] { null },
                        new Class<?>[] { OAuth2RefreshToken.class });
            }

            byte[] tokenData = SerializationUtils.serialize((Serializable) accessToken);

            // deserialise the authenticated, this is NOT backward compatible so we have to read using a diff class loader
            OAuth2Authentication auth = deserializeOAuth2Authentication(tokenRecord.getAuthentication());
            byte[] authData = SerializationUtils.serialize(auth);

            // this does the actual migration of the token
            this.dao.updateOauthAccessToken(oldTokenId, newTokenId, newRefreshToken, tokenData, authData);

            System.out.println("Migrated token with id: " + oldTokenId);
            numMigrated++;
            System.out.println("");
        }
        numTokens = this.dao.countUnmigratedAccessTokens();
    }

    System.out.println("Finished Migrating " + numMigrated + " access token(s).");

}

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

public String buildRedirectURI(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken,
        Authentication authUser) {//from   w  w  w  . j  av  a  2s  .  c  o m

    String requestedRedirect = authorizationRequest.getRedirectUri();
    if (accessToken == null) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }

    StringBuilder url = new StringBuilder();
    url.append("token_type=").append(encode(accessToken.getTokenType()));

    //only append access token if grant_type is implicit
    //or token is part of the response type
    if (authorizationRequest.getResponseTypes().contains("token")) {
        url.append("&access_token=").append(encode(accessToken.getValue()));
    }

    if (accessToken instanceof CompositeToken
            && authorizationRequest.getResponseTypes().contains(CompositeToken.ID_TOKEN)) {
        url.append("&").append(CompositeToken.ID_TOKEN).append("=")
                .append(encode(((CompositeToken) accessToken).getIdTokenValue()));
    }

    if (authorizationRequest.getResponseTypes().contains("code")) {
        String code = generateCode(authorizationRequest, authUser);
        url.append("&code=").append(encode(code));
    }

    String state = authorizationRequest.getState();
    if (state != null) {
        url.append("&state=").append(encode(state));
    }

    Date expiration = accessToken.getExpiration();
    if (expiration != null) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        url.append("&expires_in=").append(expires_in);
    }

    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (originalScope == null
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        url.append("&" + OAuth2Utils.SCOPE + "=")
                .append(encode(OAuth2Utils.formatParameterList(accessToken.getScope())));
    }

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (value != null) {
            url.append("&" + encode(key) + "=" + encode(value.toString()));
        }
    }

    if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
        HttpHost httpHost = URIUtils.extractHost(URI.create(requestedRedirect));
        String sessionState = openIdSessionStateCalculator.calculate(
                ((UaaPrincipal) authUser.getPrincipal()).getId(), authorizationRequest.getClientId(),
                httpHost.toURI());

        url.append("&session_state=").append(sessionState);
    }

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(requestedRedirect);
    String existingFragment = builder.build(true).getFragment();
    if (StringUtils.hasText(existingFragment)) {
        existingFragment = existingFragment + "&" + url.toString();
    } else {
        existingFragment = url.toString();
    }
    builder.fragment(existingFragment);
    // Do not include the refresh token (even if there is one)
    return builder.build(true).toUriString();
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java

private Map<String, ?> createJWTAccessToken(OAuth2AccessToken token, String userId, String username,
        String userEmail, Collection<GrantedAuthority> clientScopes, Set<String> requestedScopes,
        String clientId, Set<String> resourceIds, String grantType, String refreshToken) {

    Map<String, Object> response = new LinkedHashMap<String, Object>();

    response.put(JTI, token.getAdditionalInformation().get(JTI));
    response.putAll(token.getAdditionalInformation());

    response.put(SUB, userId);/*from ww w  . j  av  a2s  .  c  om*/
    if (null != clientScopes) {
        response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(clientScopes));
    }

    response.put(OAuth2AccessToken.SCOPE, requestedScopes);
    response.put(CLIENT_ID, clientId);
    response.put(CID, clientId);
    response.put(AZP, clientId); //openId Connect

    if (null != grantType) {
        response.put(GRANT_TYPE, grantType);
    }
    if (!"client_credentials".equals(grantType)) {
        response.put(USER_ID, userId);
        response.put(USER_NAME, username == null ? userId : username);
        if (null != userEmail) {
            response.put(EMAIL, userEmail);
        }
    }

    response.put(IAT, System.currentTimeMillis() / 1000);
    if (token.getExpiration() != null) {
        response.put(EXP, token.getExpiration().getTime() / 1000);
    }

    if (tokenEndpoint != null) {
        response.put(ISS, tokenEndpoint);
    }

    // TODO: different values for audience in the AT and RT. Need to sync
    // them up
    response.put(AUD, resourceIds);

    return response;
}

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

private Map<String, ?> createJWTAccessToken(OAuth2AccessToken token, String userId, UaaUser user,
        Date userAuthenticationTime, Collection<GrantedAuthority> clientScopes, Set<String> requestedScopes,
        String clientId, Set<String> resourceIds, String grantType, String refreshToken,
        String revocableHashSignature, boolean revocable) {

    Map<String, Object> response = new LinkedHashMap<String, Object>();

    response.put(JTI, token.getAdditionalInformation().get(JTI));
    response.putAll(token.getAdditionalInformation());

    response.put(SUB, clientId);/*from  w ww  . j  a v a2 s  .c om*/
    if (null != clientScopes) {
        response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(clientScopes));
    }

    response.put(OAuth2AccessToken.SCOPE, requestedScopes);
    response.put(CLIENT_ID, clientId);
    response.put(CID, clientId);
    response.put(AZP, clientId); //openId Connect
    if (revocable) {
        response.put(REVOCABLE, true);
    }

    if (null != grantType) {
        response.put(GRANT_TYPE, grantType);
    }
    if (user != null && userId != null) {
        response.put(USER_ID, userId);
        String origin = user.getOrigin();
        if (StringUtils.hasLength(origin)) {
            response.put(ORIGIN, origin);
        }
        String username = user.getUsername();
        response.put(USER_NAME, username == null ? userId : username);
        String userEmail = user.getEmail();
        if (userEmail != null) {
            response.put(EMAIL, userEmail);
        }
        if (userAuthenticationTime != null) {
            response.put(AUTH_TIME, userAuthenticationTime.getTime() / 1000);
        }
        response.put(SUB, userId);
    }

    if (StringUtils.hasText(revocableHashSignature)) {
        response.put(REVOCATION_SIGNATURE, revocableHashSignature);
    }

    response.put(IAT, System.currentTimeMillis() / 1000);
    response.put(EXP, token.getExpiration().getTime() / 1000);

    if (getTokenEndpoint() != null) {
        response.put(ISS, getTokenEndpoint());
        response.put(ZONE_ID, IdentityZoneHolder.get().getId());
    }

    // TODO: different values for audience in the AT and RT. Need to sync
    // them up
    response.put(AUD, resourceIds);

    for (String excludedClaim : getExcludedClaims()) {
        response.remove(excludedClaim);
    }

    return response;
}

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

protected void validateExternalAttributes(OAuth2AccessToken accessToken) {
    Map<String, String> extendedAttributes = (Map<String, String>) accessToken.getAdditionalInformation()
            .get(ClaimConstants.EXTERNAL_ATTR);
    if (tokenEnhancer != null) {
        Assert.assertEquals("test", extendedAttributes.get("purpose"));
    } else {//from  www. ja v a  2s.  com
        assertNull("External attributes should not exist", extendedAttributes);
    }
}

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

@Test
public void testCreateAccessTokenAuthcodeGrantAdditionalAuthorizationAttributes() {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
    azParameters.put("authorities",
            "{\"az_attr\":{\"external_group\":\"domain\\\\group1\", \"external_id\":\"abcd1234\"}}");
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);// ww  w .ja v a2s  .co m
    OAuth2AccessToken token = tokenServices.createAccessToken(authentication);

    this.assertCommonUserAccessTokenProperties(token);
    assertThat(token, issuerUri(is(ISSUER_URI)));
    assertThat(token, scope(is(requestedAuthScopes)));
    assertThat(token, validFor(is(60 * 60 * 12)));

    OAuth2RefreshToken refreshToken = token.getRefreshToken();
    this.assertCommonUserRefreshTokenProperties(refreshToken);
    assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI)));
    assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30)));

    this.assertCommonEventProperties(token, userId, buildJsonString(requestedAuthScopes));

    Map<String, String> azMap = new LinkedHashMap<>();
    azMap.put("external_group", "domain\\group1");
    azMap.put("external_id", "abcd1234");
    assertEquals(azMap, token.getAdditionalInformation().get("az_attr"));
}

From source file:org.opentestsystem.shared.security.oauth.resource.SbacTokenConverter.java

@Override
public Map<String, ?> convertAccessToken(final OAuth2AccessToken token,
        final OAuth2Authentication authentication) {
    final Map<String, Object> response = Maps.newHashMap();
    final OAuth2Request clientToken = authentication.getOAuth2Request();

    if (!authentication.isClientOnly()) {
        response.putAll(//  w  w  w  .  j  a  v a  2s. com
                this.userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication()));
    }

    if (token.getScope() != null) {
        response.put(SCOPE, token.getScope());
    }

    if (token.getExpiration() != null) {
        response.put(EXPIRES, token.getExpiration().getTime() / 1000);
    }

    response.putAll(token.getAdditionalInformation());

    response.put(CLIENT_ID, clientToken.getClientId());
    if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) {
        response.put(AUD, clientToken.getResourceIds());
    }
    return response;
}