Example usage for org.springframework.security.oauth2.common DefaultOAuth2AccessToken setScope

List of usage examples for org.springframework.security.oauth2.common DefaultOAuth2AccessToken setScope

Introduction

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

Prototype

public void setScope(Set<String> scope) 

Source Link

Document

The scope of the token.

Usage

From source file:org.osiam.resource_server.security.authorization.AccessTokenValidationService.java

@Override
public OAuth2AccessToken readAccessToken(String token) {
    AccessToken accessToken = validateAccessToken(token);

    Set<String> scopes = new HashSet<String>();
    for (Scope scope : accessToken.getScopes()) {
        scopes.add(scope.toString());//from w  w w.ja  v  a2 s  .c om
    }

    DefaultOAuth2AccessToken oAuth2AccessToken = new DefaultOAuth2AccessToken(token);
    oAuth2AccessToken.setScope(scopes);
    oAuth2AccessToken.setExpiration(accessToken.getExpiresAt());
    oAuth2AccessToken.setTokenType("BEARER");

    return oAuth2AccessToken;
}

From source file:com.example.ProxyAuthorizationServerTokenServices.java

private DefaultOAuth2AccessToken ectractAccessToken(Map<String, Object> map) {
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken((String) map.get("access_token"));
    token.setRefreshToken(new DefaultOAuth2RefreshToken((String) map.get("refresh_token")));
    token.setScope(OAuth2Utils.parseParameterList((String) map.get("scope")));
    return token;
}

From source file:com.onedrive.api.internal.InternalTokenServices.java

public OAuth2AccessToken getAccessToken(OAuth2ProtectedResourceDetails resource,
        Authentication authentication) {
    if (reference.getAccessTokenListener() != null) {
        AccessToken internalAccessToken = reference.getAccessTokenListener().onAccessTokenRequired(reference);
        if (internalAccessToken != null) {
            DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(
                    internalAccessToken.getAccessToken());
            accessToken.setExpiration(internalAccessToken.getExpiration());
            accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(internalAccessToken.getRefreshToken()));
            accessToken.setScope(internalAccessToken.getScope());
            accessToken.setTokenType(internalAccessToken.getTokenType());
            return accessToken;
        }//ww w .j a  v a 2 s. c om
    }
    return null;
}

From source file:org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Deserializer.java

@Override
public OAuth2AccessToken deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    String tokenValue = null;/*  w  ww .  j av a  2s . co m*/
    String tokenType = null;
    String refreshToken = null;
    Long expiresIn = null;
    Set<String> scope = null;
    Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();

    // TODO What should occur if a parameter exists twice
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String name = jp.getCurrentName();
        jp.nextToken();
        if (OAuth2AccessToken.ACCESS_TOKEN.equals(name)) {
            tokenValue = jp.getText();
        } else if (OAuth2AccessToken.TOKEN_TYPE.equals(name)) {
            tokenType = jp.getText();
        } else if (OAuth2AccessToken.REFRESH_TOKEN.equals(name)) {
            refreshToken = jp.getText();
        } else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
            try {
                expiresIn = jp.getLongValue();
            } catch (JsonParseException e) {
                expiresIn = Long.valueOf(jp.getText());
            }
        } else if (OAuth2AccessToken.SCOPE.equals(name)) {
            String text = jp.getText();
            scope = OAuth2Utils.parseParameterList(text);
        } else {
            additionalInformation.put(name, jp.readValueAs(Object.class));
        }
    }

    // TODO What should occur if a required parameter (tokenValue or tokenType) is missing?

    DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenValue);
    accessToken.setTokenType(tokenType);
    if (expiresIn != null) {
        accessToken.setExpiration(new Date(System.currentTimeMillis() + (expiresIn * 1000)));
    }
    if (refreshToken != null) {
        accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken));
    }
    accessToken.setScope(scope);
    accessToken.setAdditionalInformation(additionalInformation);

    return accessToken;
}

From source file:com.onedrive.api.OneDrive.java

private OAuth2AccessToken getOAuth2AccessToken() {
    if (existingToken != null) {
        DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(existingToken.getAccessToken());
        if (existingToken.getRefreshToken() != null) {
            accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(existingToken.getRefreshToken()));
        }/*from  w w  w  .j a  v  a  2  s . com*/
        accessToken.setExpiration(existingToken.getExpiration());
        accessToken.setScope(existingToken.getScope());
        accessToken.setTokenType(existingToken.getTokenType());
        return accessToken;
    }
    return null;
}

From source file:no.imr.common.security.jwt.DefaultAccessTokenConverter.java

public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(value);
    Map<String, Object> info = new HashMap<String, Object>(map);
    info.remove(EXP);//from  w  w w.ja  va 2s .co  m
    info.remove(AUD);
    info.remove(CLIENT_ID);
    info.remove(SCOPE);
    if (map.containsKey(EXP)) {
        token.setExpiration(new Date((Long) map.get(EXP) * 1000L));
    }
    if (map.containsKey(JTI)) {
        info.put(JTI, map.get(JTI));
    }
    @SuppressWarnings("unchecked")
    Collection<String> scope = (Collection<String>) map.get(SCOPE);
    if (scope != null) {
        token.setScope(new HashSet<String>(scope));
    }
    token.setAdditionalInformation(info);
    return token;
}

From source file:org.apigw.authserver.web.controller.CertifiedClientsControllerTest.java

private void commonMocks() {
    //Collection of Oauthtokens to return when asked for in the controller
    Collection<OAuth2AccessToken> tokens = new ArrayList<OAuth2AccessToken>();
    DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken("MOCK_TOKEN_VALUE");
    //Add some scopes
    Set<String> scope = new HashSet<String>();
    scope.add("MOCK_SCOPE_ITEM_1");
    scope.add("MOCK_SCOPE_ITEM_2");

    //Placeholder for additionalInformation
    Map<String, Object> addInfo = new HashMap<String, Object>();
    addInfo.put("authorization_grant_id", "MOCK_GRANT_ID");

    //Set all relevant things on this accessToken
    accessToken.setScope(scope);
    accessToken.setExpiration(new DateTime().plusDays(1).toDate());
    accessToken.setAdditionalInformation(addInfo);

    tokens.add(accessToken);//  w w  w  .j a  v a 2s.  c  o  m

    //Mock encryptedConsumerTokenService interactions
    Mockito.when(encryptedConsumerTokenService.findTokensByUserName(anyString())).thenReturn(tokens);
    Mockito.when(encryptedConsumerTokenService.getClientId("MOCK_TOKEN_VALUE"))
            .thenReturn("INSTALLED_CLIENT_ID");

    //CertifiedClients to return from clientDetailsServices mock
    List<CertifiedClient> clients = new ArrayList<CertifiedClient>();
    CertifiedClient installedClient = new CertifiedClient();
    CertifiedClient availableClient = new CertifiedClient();
    installedClient.setName("INSTALLED_CLIENT_NAME");
    installedClient.setClientId("INSTALLED_CLIENT_ID");
    installedClient.setOrganization("INSTALLED_CLIENT_ORGANIZATION");
    installedClient.setDescription("A description");

    availableClient.setName("AVAILABLE_CLIENT_NAME");
    availableClient.setClientId("AVAILABLE_CLIENT_ID");
    availableClient.setOrganization("AVAILABLE_CLIENT_ORGANIZATION");
    availableClient.setDescription("A description");
    availableClient.setClientUrl("http://somewhere");

    clients.add(installedClient);
    clients.add(availableClient);

    //Mock clientDetailsService interactions
    Mockito.when(clientDetailsService.findAllClients()).thenReturn(clients);
    Mockito.when(clientDetailsService.loadClientByClientId("INSTALLED_CLIENT_ID")).thenReturn(installedClient);

    //Permission to return from permissionServices mock
    Permission mockPermission = new Permission();
    mockPermission.setDescription("MOCK_ROLE_DESCRIPTION");

    //Mock scopeservices
    Mockito.when(permissionServices.getPermissionByName(anyString())).thenReturn(mockPermission);
}

From source file:com.ge.predix.uaa.token.lib.TestTokenUtil.java

private DefaultOAuth2AccessToken createAccessToken(final String issuerId, final String userId,
        final String username, final String userEmail, final int validitySeconds,
        final Collection<GrantedAuthority> clientScopes, final Set<String> requestedScopes,
        final String clientId, final Set<String> resourceIds, final String grantType, final String refreshToken,
        final Map<String, String> additionalAuthorizationAttributes, final Set<String> responseTypes,
        final String revocableHashSignature, final long issuedAtMillis, final String zoneId) {

    String tokenId = UUID.randomUUID().toString();
    DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenId);
    if (validitySeconds > 0) {
        accessToken.setExpiration(new Date(issuedAtMillis + (validitySeconds * 1000L)));
    }//from  w  w  w. j  ava  2s  .c om
    accessToken.setRefreshToken(refreshToken == null ? null : new DefaultOAuth2RefreshToken(refreshToken));

    if (null == requestedScopes || requestedScopes.size() == 0) {
        // logger.debug("No scopes were granted");
        throw new InvalidTokenException("No scopes were granted");
    }

    accessToken.setScope(requestedScopes);

    Map<String, Object> info = new HashMap<String, Object>();
    info.put(JTI, accessToken.getValue());
    if (null != additionalAuthorizationAttributes) {
        info.put(ADDITIONAL_AZ_ATTR, additionalAuthorizationAttributes);
    }
    accessToken.setAdditionalInformation(info);

    String content;
    try {
        content = JsonUtils.writeValueAsString(createJWTAccessToken(accessToken, issuerId, userId, username,
                userEmail, clientScopes, requestedScopes, clientId, resourceIds, grantType, refreshToken,
                revocableHashSignature, issuedAtMillis, zoneId));
    } catch (JsonUtils.JsonUtilException e) {
        throw new IllegalStateException("Cannot convert access token to JSON", e);
    }
    String token = JwtHelper.encode(content, this.signer).getEncoded();

    // This setter copies the value and returns. Don't change.
    accessToken.setValue(token);

    return accessToken;

}

From source file:it.smartcommunitylab.aac.oauth.NonRemovingTokenServices.java

private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication,
        OAuth2RefreshToken refreshToken) {
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
    int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());

    if (!authentication.isClientOnly()) {

        token.setExpiration(new Date(System.currentTimeMillis()
                + (getUserAccessTokenValiditySeconds(authentication.getOAuth2Request()) * 1000L)));
    } else if (validitySeconds > 0) {
        token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
    } else {/*w  w w .j a  v  a 2  s  .  co  m*/
        token.setExpiration(new Date(Long.MAX_VALUE));
    }

    token.setRefreshToken(refreshToken);
    token.setScope(authentication.getOAuth2Request().getScope());

    logger.info("Created token " + token.getValue() + " expires at " + token.getExpiration());
    return tokenEnhancer != null ? tokenEnhancer.enhance(token, authentication) : token;
}