org.apache.cxf.rs.security.oauth2.common.OAuthPermission Java Examples

The following examples show how to use org.apache.cxf.rs.security.oauth2.common.OAuthPermission. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public List<OAuthPermission> convertScopeToPermissions(Client client, List<String> requestedScopes) {
    checkRequestedScopes(client, requestedScopes);
    if (requestedScopes.isEmpty()) {
        return Collections.emptyList();
    }
    List<OAuthPermission> list = new ArrayList<>();
    for (String scope : requestedScopes) {
        convertSingleScopeToPermission(client, scope, list);
    }
    if (!list.isEmpty()) {
        return list;
    }
    throw new OAuthServiceException("Requested scopes can not be mapped");

}
 
Example #2
Source File: EHCacheOIDCTokenProvider.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@Override
public List<OAuthPermission> convertScopeToPermissions(Client client, List<String> requestedScopes) {
    if (requestedScopes.isEmpty()) {
        return Collections.emptyList();
    }

    List<OAuthPermission> permissions = new ArrayList<>();
    for (String requestedScope : requestedScopes) {
        if ("openid".equals(requestedScope)) {
            OAuthPermission permission = new OAuthPermission("openid", "Authenticate user");
            permissions.add(permission);
        } else {
            throw new OAuthServiceException("invalid_scope");
        }
    }

    return permissions;
}
 
Example #3
Source File: OidcImplicitService.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean canAuthorizationBeSkipped(MultivaluedMap<String, String> params,
                                            Client client,
                                            UserSubject userSubject,
                                            List<String> requestedScope,
                                            List<OAuthPermission> permissions) {
    List<String> promptValues = OidcUtils.getPromptValues(params);
    if (promptValues.contains(OidcUtils.PROMPT_CONSENT_VALUE)) {
        // Displaying the consent screen is preferred by the client
        return false;
    }
    // Check the pre-configured consent
    boolean preConfiguredConsentForScopes =
        super.canAuthorizationBeSkipped(params, client, userSubject, requestedScope, permissions);

    if (!preConfiguredConsentForScopes && promptValues.contains(OidcUtils.PROMPT_NONE_VALUE)) {
        // An error is returned if client does not have pre-configured consent for the requested scopes/claims
        LOG.log(Level.FINE, "Prompt 'none' request can not be met");
        throw new OAuthServiceException(new OAuthError(OidcUtils.CONSENT_REQUIRED_ERROR));
    }
    return preConfiguredConsentForScopes;
}
 
Example #4
Source File: OidcAuthorizationCodeService.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean canAuthorizationBeSkipped(MultivaluedMap<String, String> params,
                                            Client client,
                                            UserSubject userSubject,
                                            List<String> requestedScope,
                                            List<OAuthPermission> permissions) {
    List<String> promptValues = OidcUtils.getPromptValues(params);
    if (promptValues.contains(OidcUtils.PROMPT_CONSENT_VALUE)) {
        // Displaying the consent screen is preferred by the client
        return false;
    }
    // Check the pre-configured consent
    boolean preConfiguredConsentForScopes =
        super.canAuthorizationBeSkipped(params, client, userSubject, requestedScope, permissions);

    if (!preConfiguredConsentForScopes && promptValues.contains(OidcUtils.PROMPT_NONE_VALUE)) {
        // An error is returned if client does not have pre-configured consent for the requested scopes/claims
        LOG.log(Level.FINE, "Prompt 'none' request can not be met");
        throw new OAuthServiceException(new OAuthError(OidcUtils.CONSENT_REQUIRED_ERROR));
    }
    return preConfiguredConsentForScopes;
}
 
Example #5
Source File: OAuthScopesFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void checkScopes(Method m) {
    List<String> methodScopes = scopesMap.get(m.getName());
    if (methodScopes == null) {
        return;
    }
    boolean matchAll = scopesMatchAllMap.get(m.getName());
    OAuthContext context = OAuthContextUtils.getContext(mc);
    List<String> requestScopes = new LinkedList<>();
    for (OAuthPermission perm : context.getPermissions()) {
        if (matchAll) {
            requestScopes.add(perm.getPermission());
        } else if (methodScopes.contains(perm.getPermission())) {
            return;
        }
    }

    if (!requestScopes.containsAll(methodScopes)) {
        LOG.warning("Scopes do not match");
        throw ExceptionUtils.toForbiddenException(null, null);
    }

}
 
Example #6
Source File: OAuthUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static ClientAccessToken toClientAccessToken(ServerAccessToken serverToken, boolean supportOptionalParams) {
    String tokenKey =
        serverToken.getEncodedToken() != null ? serverToken.getEncodedToken() : serverToken.getTokenKey();
    ClientAccessToken clientToken = new ClientAccessToken(serverToken.getTokenType(),
                                                          tokenKey);
    clientToken.setRefreshToken(serverToken.getRefreshToken());
    if (supportOptionalParams) {
        clientToken.setExpiresIn(serverToken.getExpiresIn());
        List<OAuthPermission> perms = serverToken.getScopes();
        String scopeString = OAuthUtils.convertPermissionsToScope(perms);
        if (!StringUtils.isEmpty(scopeString)) {
            clientToken.setApprovedScope(scopeString);
        }
        clientToken.setParameters(new HashMap<String, String>(serverToken.getParameters()));
    }
    return clientToken;
}
 
Example #7
Source File: AuthorizationCodeGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected OAuthAuthorizationData createAuthorizationData(Client client,
                                                         MultivaluedMap<String, String> params,
                                                         String redirectUri,
                                                         UserSubject subject,
                                                         List<OAuthPermission> requestedPerms,
                                                         List<OAuthPermission> alreadyAuthorizedPerms,
                                                         boolean authorizationCanBeSkipped) {
    OAuthAuthorizationData data =
        super.createAuthorizationData(client, params, redirectUri, subject,
                                      requestedPerms, alreadyAuthorizedPerms, authorizationCanBeSkipped);
    setCodeChallenge(data, params);
    return data;
}
 
Example #8
Source File: AbstractOAuthDataProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddGetDeleteRefreshToken() {
    Client c = addClient("101", "bob");

    AccessTokenRegistration atr = new AccessTokenRegistration();
    atr.setClient(c);
    atr.setApprovedScope(Arrays.asList("a", "refreshToken"));
    atr.setSubject(c.getResourceOwnerSubject());

    ServerAccessToken at = getProvider().createAccessToken(atr);
    validateAccessToken(at);
    ServerAccessToken at2 = getProvider().getAccessToken(at.getTokenKey());
    validateAccessToken(at2);
    assertEquals(at.getTokenKey(), at2.getTokenKey());
    List<OAuthPermission> scopes = at2.getScopes();
    assertNotNull(scopes);
    assertEquals(2, scopes.size());
    OAuthPermission perm = scopes.get(0);
    assertEquals("a", perm.getPermission());
    OAuthPermission perm2 = scopes.get(1);
    assertEquals("refreshToken", perm2.getPermission());

    RefreshToken rt = getProvider().getRefreshToken(at2.getRefreshToken());
    assertNotNull(rt);
    assertEquals(at2.getTokenKey(), rt.getAccessTokens().get(0));

    List<RefreshToken> tokens = getProvider().getRefreshTokens(c, c.getResourceOwnerSubject());
    assertNotNull(tokens);
    assertEquals(1, tokens.size());
    assertEquals(rt.getTokenKey(), tokens.get(0).getTokenKey());

    getProvider().revokeToken(c, rt.getTokenKey(), OAuthConstants.REFRESH_TOKEN);

    assertNull(getProvider().getRefreshToken(rt.getTokenKey()));
}
 
Example #9
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void init() {
    for (OAuthPermission perm : permissionMap.values()) {
        if (defaultScopes != null && defaultScopes.contains(perm.getPermission())) {
            perm.setDefaultPermission(true);
        }
        if (invisibleToClientScopes != null && invisibleToClientScopes.contains(perm.getPermission())) {
            perm.setInvisibleToClient(true);
        }
    }
}
 
Example #10
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected ServerAccessToken doRefreshAccessToken(Client client,
                                                 RefreshToken oldRefreshToken,
                                                 List<String> restrictedScopes) {
    ServerAccessToken at = createNewAccessToken(client, oldRefreshToken.getSubject());
    at.setAudiences(oldRefreshToken.getAudiences() != null
            ? new ArrayList<String>(oldRefreshToken.getAudiences()) : null);
    at.setGrantType(oldRefreshToken.getGrantType());
    at.setGrantCode(oldRefreshToken.getGrantCode());
    at.setSubject(oldRefreshToken.getSubject());
    at.setNonce(oldRefreshToken.getNonce());
    at.setClientCodeVerifier(oldRefreshToken.getClientCodeVerifier());
    at.getExtraProperties().putAll(oldRefreshToken.getExtraProperties());
    if (restrictedScopes.isEmpty()) {
        at.setScopes(oldRefreshToken.getScopes() != null
                ? new ArrayList<OAuthPermission>(oldRefreshToken.getScopes()) : null);
    } else {
        List<OAuthPermission> theNewScopes = convertScopeToPermissions(client, restrictedScopes);
        if (oldRefreshToken.getScopes().containsAll(theNewScopes)) {
            at.setScopes(theNewScopes);
        } else {
            throw new OAuthServiceException("Invalid scopes");
        }
    }

    if (isUseJwtFormatForAccessTokens()) {
        JwtClaims claims = createJwtAccessToken(at);
        String jose = processJwtAccessToken(claims);
        if (isPersistJwtEncoding()) {
            at.setTokenKey(jose);
        } else {
            at.setEncodedToken(jose);
        }
    }

    return at;
}
 
Example #11
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void convertSingleScopeToPermission(Client client,
                                              String scope,
                                              List<OAuthPermission> perms) {
    OAuthPermission permission = permissionMap.get(scope);
    if (permission == null) {
        throw new OAuthServiceException("Unexpected scope: " + scope);
    }
    perms.add(permission);
}
 
Example #12
Source File: RefreshTokenEnabledProvider.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
public RefreshTokenEnabledProvider(final OAuthDataProvider delegate) {
    this.delegate = delegate;
    if (AbstractOAuthDataProvider.class.isInstance(delegate)) {
        final AbstractOAuthDataProvider provider = AbstractOAuthDataProvider.class.cast(delegate);
        final Map<String, OAuthPermission> permissionMap = new HashMap<>(provider.getPermissionMap());
        permissionMap.putIfAbsent(OAuthConstants.REFRESH_TOKEN_SCOPE, new OAuthPermission(OAuthConstants.REFRESH_TOKEN_SCOPE, "allow to refresh a token"));
        provider.setPermissionMap(permissionMap);
    }
}
 
Example #13
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected ServerAccessToken doCreateAccessToken(AccessTokenRegistration atReg) {
    ServerAccessToken at = createNewAccessToken(atReg.getClient(), atReg.getSubject());
    at.setAudiences(atReg.getAudiences());
    at.setGrantType(atReg.getGrantType());
    List<String> theScopes = atReg.getApprovedScope();
    List<OAuthPermission> thePermissions =
        convertScopeToPermissions(atReg.getClient(), theScopes);
    at.setScopes(thePermissions);
    at.setSubject(atReg.getSubject());
    at.setClientCodeVerifier(atReg.getClientCodeVerifier());
    at.setNonce(atReg.getNonce());
    at.setResponseType(atReg.getResponseType());
    at.setGrantCode(atReg.getGrantCode());
    at.getExtraProperties().putAll(atReg.getExtraProperties());

    if (messageContext != null) {
        String certCnf = (String)messageContext.get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256);
        if (certCnf != null) {
            // At a later stage we will likely introduce a dedicated Confirmation bean (as it is used in POP etc)
            at.getExtraProperties().put(JoseConstants.HEADER_X509_THUMBPRINT_SHA256, certCnf);
        }
    }

    if (isUseJwtFormatForAccessTokens()) {
        JwtClaims claims = createJwtAccessToken(at);
        String jose = processJwtAccessToken(claims);
        if (isPersistJwtEncoding()) {
            at.setTokenKey(jose);
        } else {
            at.setEncodedToken(jose);
        }
    }

    return at;
}
 
Example #14
Source File: CryptoUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void compareAccessTokens(ServerAccessToken token, ServerAccessToken token2) {
    assertEquals(token.getTokenKey(), token2.getTokenKey());
    assertEquals(token.getTokenType(), token2.getTokenType());
    assertEquals(token.getIssuedAt(), token2.getIssuedAt());
    assertEquals(token.getExpiresIn(), token2.getExpiresIn());
    Client regClient1 = token.getClient();
    Client regClient2 = token2.getClient();
    assertEquals(regClient1.getClientId(), regClient2.getClientId());
    assertNull(regClient2.getApplicationDescription());
    UserSubject endUser1 = token.getSubject();
    UserSubject endUser2 = token2.getSubject();
    assertEquals(endUser1.getLogin(), endUser2.getLogin());
    assertEquals(endUser1.getId(), endUser2.getId());
    assertEquals(endUser1.getRoles(), endUser2.getRoles());

    assertEquals(token.getRefreshToken(), token2.getRefreshToken());
    assertEquals(token.getAudiences(), token2.getAudiences());
    assertEquals(token.getGrantType(), token2.getGrantType());
    assertEquals(token.getParameters(), token2.getParameters());

    List<OAuthPermission> permissions = token.getScopes();
    List<OAuthPermission> permissions2 = token2.getScopes();
    assertEquals(1, permissions.size());
    assertEquals(1, permissions2.size());
    OAuthPermission perm1 = permissions.get(0);
    OAuthPermission perm2 = permissions2.get(0);
    assertEquals(perm1.getPermission(), perm2.getPermission());
    assertEquals(perm1.getDescription(), perm2.getDescription());

    RefreshToken refreshToken =
        ModelEncryptionSupport.decryptRefreshToken(p, token2.getRefreshToken(), p.key);
    assertEquals(1200L, refreshToken.getExpiresIn());
}
 
Example #15
Source File: JPAOAuthDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void saveAccessToken(final ServerAccessToken serverToken) {
    executeInTransaction(em -> {
        List<OAuthPermission> perms = new LinkedList<>();
        for (OAuthPermission perm : serverToken.getScopes()) {
            OAuthPermission permSaved = em.find(OAuthPermission.class, perm.getPermission());
            if (permSaved != null) {
                perms.add(permSaved);
            } else {
                em.persist(perm);
                perms.add(perm);
            }
        }
        serverToken.setScopes(perms);

        if (serverToken.getSubject() != null) {
            UserSubject sub = em.find(UserSubject.class, serverToken.getSubject().getId());
            if (sub == null) {
                em.persist(serverToken.getSubject());
            } else {
                sub = em.merge(serverToken.getSubject());
                serverToken.setSubject(sub);
            }
        }
        // ensure we have a managed association
        // (needed for OpenJPA : InvalidStateException: Encountered unmanaged object)
        if (serverToken.getClient() != null) {
            serverToken.setClient(em.find(Client.class, serverToken.getClient().getClientId()));
        }

        em.persist(serverToken);
        return null;
    });
}
 
Example #16
Source File: AccessTokenIntrospectionClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
private AccessTokenValidation convertIntrospectionToValidation(TokenIntrospection response) {
    AccessTokenValidation atv = new AccessTokenValidation();
    atv.setInitialValidationSuccessful(response.isActive());
    if (response.getClientId() != null) {
        atv.setClientId(response.getClientId());
    }
    if (response.getIat() != null) {
        atv.setTokenIssuedAt(response.getIat());
    } else {
        atv.setTokenIssuedAt(OAuthUtils.getIssuedAt());
    }
    if (response.getExp() != null) {
        atv.setTokenLifetime(response.getExp() - atv.getTokenIssuedAt());
    }
    if (response.getNbf() != null) {
        atv.setTokenNotBefore(response.getNbf());
    }
    if (!StringUtils.isEmpty(response.getAud())) {
        atv.setAudiences(response.getAud());
    }
    if (response.getIss() != null) {
        atv.setTokenIssuer(response.getIss());
    }
    if (response.getScope() != null) {
        String[] scopes = response.getScope().split(" ");
        List<OAuthPermission> perms = new LinkedList<>();
        for (String s : scopes) {
            if (!StringUtils.isEmpty(s)) {
                perms.add(new OAuthPermission(s.trim()));
            }
        }
        atv.setTokenScopes(perms);
    }
    if (response.getUsername() != null) {
        atv.setTokenSubject(new UserSubject(response.getUsername()));
    }
    atv.getExtraProps().putAll(response.getExtensions());

    return atv;
}
 
Example #17
Source File: RedirectionBasedGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean noConsentForRequestedScopes(MultivaluedMap<String, String> params,
                                              Client client,
                                              UserSubject userSubject,
                                              List<String> requestedScope,
                                              List<OAuthPermission> permissions) {
    return scopesRequiringNoConsent != null
           && requestedScope != null
           && scopesRequiringNoConsent.containsAll(requestedScope);
}
 
Example #18
Source File: RedirectionBasedGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean canAuthorizationBeSkipped(MultivaluedMap<String, String> params,
                                            Client client,
                                            UserSubject userSubject,
                                            List<String> requestedScope,
                                            List<OAuthPermission> permissions) {
    return noConsentForRequestedScopes(params, client, userSubject, requestedScope, permissions);
}
 
Example #19
Source File: ImplicitGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected OAuthAuthorizationData createAuthorizationData(Client client,
                                                         MultivaluedMap<String, String> params,
                                                         String redirectUri,
                                                         UserSubject subject,
                                                         List<OAuthPermission> requestedPerms,
                                                         List<OAuthPermission> alreadyAuthorizedPerms,
                                                         boolean authorizationCanBeSkipped) {
    OAuthAuthorizationData data =
        super.createAuthorizationData(client, params, redirectUri, subject,
                                      requestedPerms, alreadyAuthorizedPerms, authorizationCanBeSkipped);
    data.setImplicitFlow(true);
    return data;
}
 
Example #20
Source File: ModelEncryptionSupport.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static ServerAccessToken recreateAccessToken(OAuthDataProvider provider,
                                              String newTokenKey,
                                              String[] parts) {


    @SuppressWarnings("serial")
    final ServerAccessToken newToken = new ServerAccessToken(provider.getClient(parts[4]),
                                                             parts[1],
                                                             newTokenKey == null ? parts[0] : newTokenKey,
                                                             Long.parseLong(parts[2]),
                                                             Long.parseLong(parts[3])) {
    };

    newToken.setRefreshToken(getStringPart(parts[5]));
    newToken.setGrantType(getStringPart(parts[6]));
    newToken.setAudiences(parseSimpleList(parts[7]));
    newToken.setParameters(parseSimpleMap(parts[8]));

    // Permissions
    if (!parts[9].trim().isEmpty()) {
        List<OAuthPermission> perms = new LinkedList<>();
        String[] allPermParts = parts[9].split("\\.");
        for (int i = 0; i + 4 < allPermParts.length; i = i + 5) {
            OAuthPermission perm = new OAuthPermission(allPermParts[i], allPermParts[i + 1]);
            perm.setDefaultPermission(Boolean.parseBoolean(allPermParts[i + 2]));
            perm.setHttpVerbs(parseSimpleList(allPermParts[i + 3]));
            perm.setUris(parseSimpleList(allPermParts[i + 4]));
            perms.add(perm);
        }
        newToken.setScopes(perms);
    }
    //Client verifier:
    newToken.setClientCodeVerifier(parts[10]);
    //UserSubject:
    newToken.setSubject(recreateUserSubject(parts[11]));

    newToken.setExtraProperties(parseSimpleMap(parts[12]));

    return newToken;
}
 
Example #21
Source File: EncryptingDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
BearerAccessToken createAccessTokenInternal(AccessTokenRegistration accessTokenReg) {
    BearerAccessToken token = new BearerAccessToken(accessTokenReg.getClient(), 3600L);
    token.setSubject(accessTokenReg.getSubject());

    createRefreshToken(token);

    token.setGrantType(accessTokenReg.getGrantType());
    token.setAudiences(accessTokenReg.getAudiences());
    token.setParameters(Collections.singletonMap("param", "value"));
    token.setScopes(Collections.singletonList(
        new OAuthPermission("read", "read permission")));
    return token;
}
 
Example #22
Source File: OAuthUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String convertPermissionsToScope(List<OAuthPermission> perms) {
    StringBuilder sb = new StringBuilder();
    for (OAuthPermission perm : perms) {
        if (perm.isInvisibleToClient() || perm.getPermission() == null) {
            continue;
        }
        if (sb.length() > 0) {
            sb.append(' ');
        }
        sb.append(perm.getPermission());
    }
    return sb.toString();
}
 
Example #23
Source File: UserInfoService.java    From cxf with Apache License 2.0 4 votes vote down vote up
@GET
@Produces({"application/json", "application/jwt" })
public Response getUserInfo() {
    OAuthContext oauth = OAuthContextUtils.getContext(mc);

    // Check the access token has the "openid" scope
    if (!oauth.getPermissions().stream()
        .map(OAuthPermission::getPermission)
        .anyMatch(OidcUtils.OPENID_SCOPE::equals)) {
        return Response.status(Status.UNAUTHORIZED).build();
    }

    UserInfo userInfo = null;
    if (userInfoProvider != null) {
        userInfo = userInfoProvider.getUserInfo(oauth.getClientId(), oauth.getSubject(),
            OAuthUtils.convertPermissionsToScopeList(oauth.getPermissions()));
    } else if (oauth.getSubject() instanceof OidcUserSubject) {
        OidcUserSubject oidcUserSubject = (OidcUserSubject)oauth.getSubject();
        userInfo = oidcUserSubject.getUserInfo();
        if (userInfo == null) {
            userInfo = createFromIdToken(oidcUserSubject.getIdToken());
        }
    }
    if (userInfo == null) {
        // Consider customizing the error code in case of UserInfo being not available
        return Response.serverError().build();
    }

    final Object responseEntity;
    // UserInfo may be returned in a clear form as JSON
    if (super.isJwsRequired() || super.isJweRequired()) {
        Client client = null;
        if (oauthDataProvider != null) {
            client = oauthDataProvider.getClient(oauth.getClientId());
        }
        responseEntity = super.processJwt(new JwtToken(userInfo), client);
    } else {
        responseEntity = convertUserInfoToResponseEntity(userInfo);
    }
    return Response.ok(responseEntity).build();

}
 
Example #24
Source File: EncryptingDataProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public List<OAuthPermission> convertScopeToPermissions(Client client, List<String> requestedScope) {
    // assuming that no specific scopes is documented/supported
    return Collections.emptyList();
}
 
Example #25
Source File: AbstractOAuthDataProviderTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testAddGetDeleteAccessToken() {
    Client c = addClient("101", "bob");

    AccessTokenRegistration atr = new AccessTokenRegistration();
    atr.setClient(c);
    atr.setApprovedScope(Collections.singletonList("a"));
    atr.setSubject(c.getResourceOwnerSubject());

    ServerAccessToken at = getProvider().createAccessToken(atr);
    validateAccessToken(at);
    ServerAccessToken at2 = getProvider().getAccessToken(at.getTokenKey());
    validateAccessToken(at2);
    assertEquals(at.getTokenKey(), at2.getTokenKey());
    List<OAuthPermission> scopes = at2.getScopes();
    assertNotNull(scopes);
    assertEquals(1, scopes.size());
    OAuthPermission perm = scopes.get(0);
    assertEquals("a", perm.getPermission());

    List<ServerAccessToken> tokens = getProvider().getAccessTokens(c, c.getResourceOwnerSubject());
    assertNotNull(tokens);
    assertEquals(1, tokens.size());
    assertEquals(at.getTokenKey(), tokens.get(0).getTokenKey());
    validateAccessToken(tokens.get(0));

    tokens = getProvider().getAccessTokens(c, null);
    assertNotNull(tokens);
    assertEquals(1, tokens.size());
    assertEquals(at.getTokenKey(), tokens.get(0).getTokenKey());
    validateAccessToken(tokens.get(0));

    tokens = getProvider().getAccessTokens(null, c.getResourceOwnerSubject());
    assertNotNull(tokens);
    assertEquals(1, tokens.size());
    assertEquals(at.getTokenKey(), tokens.get(0).getTokenKey());
    validateAccessToken(tokens.get(0));

    tokens = getProvider().getAccessTokens(null, null);
    assertNotNull(tokens);
    assertEquals(1, tokens.size());
    assertEquals(at.getTokenKey(), tokens.get(0).getTokenKey());
    validateAccessToken(tokens.get(0));

    getProvider().revokeToken(c, at.getTokenKey(), OAuthConstants.ACCESS_TOKEN);
    assertNull(getProvider().getAccessToken(at.getTokenKey()));
}
 
Example #26
Source File: RefreshTokenEnabledProvider.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
@Override
public List<OAuthPermission> convertScopeToPermissions(final Client client, final List<String> requestedScopes) {
    return delegate.convertScopeToPermissions(client, requestedScopes);
}
 
Example #27
Source File: OAuth2Provider.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public List<OAuthPermission> convertScopeToPermissions(final Client client, final List<String> list) {
  return Collections.singletonList(new OAuthPermission());
}
 
Example #28
Source File: JPAAdapter.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
public static EntityManagerFactory createEntityManagerFactory(final OAuth2Options configuration) {
    return Persistence.createEntityManagerFactory("oauth2", new HashMap() {{
        put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
        put("openjpa.MetaDataFactory", "jpa(Types=" +
                Client.class.getName() + ',' +
                OAuthPermission.class.getName() + ',' +
                UserSubject.class.getName() + ',' +
                ServerAuthorizationCodeGrant.class.getName() + ',' +
                BearerAccessToken.class.getName() + ',' +
                RefreshToken.class.getName() + ")");

        // plain connection but not used cause of pooling
        /*
        put("openjpa.ConnectionDriverName", configuration.getJpaDriver());
        put("openjpa.ConnectionURL", configuration.getJpaDriver());
        put("openjpa.ConnectionUsername", configuration.getJpdaDatabaseUsername());
        put("openjpa.ConnectionPassword", configuration.getJpdaDatabasePassword());
        */
        /* cool...but what about pooling?
        put("javax.persistence.jdbc.driver", configuration.getJpaDriver());
        put("javax.persistence.jdbc.url", configuration.getJpaDatabaseUrl());
        put("javax.persistence.jdbc.user", configuration.getJpdaDatabaseUsername());
        put("javax.persistence.jdbc.password", configuration.getJpdaDatabasePassword());
        */
        // pooling support
        put("openjpa.ConnectionDriverName", BasicDataSource.class.getName());
        put("openjpa.ConnectionProperties",
                "DriverClassName=" + configuration.getJpaDriver() + ',' +
                        "Url=" + configuration.getJpaDatabaseUrl() + ',' +
                        "Username=" + configuration.getJpdaDatabaseUsername() + ',' +
                        "Password=" + configuration.getJpdaDatabasePassword() + ',' +
                        "MaxActive=" + configuration.getJpaMaxActive() + ',' +
                        "MaxWaitMillis=" + configuration.getJpaMaxWait() + ',' +
                        "MaxIdle=" + configuration.getJpaMaxIdle() + ',' +
                        "TestOnBorrow=" + configuration.isJpaTestOnBorrow() + ',' +
                        "TestOnReturn=" + configuration.isJpaTestOnReturn() + ',' +
                        "TestWhileIdle=" + (configuration.getJpaValidationQuery() != null && !configuration.getJpaValidationQuery().isEmpty()) + ',' +
                        ofNullable(configuration.getJpaValidationQuery()).map(v -> "ValidationQuery=" + v + ',').orElse("") +
                        ofNullable(configuration.getJpaValidationInterval()).map(v -> "MinEvictableIdleTimeMillis=" + v).orElse(""));

        ofNullable(configuration.getJpaProperties())
                .map(p -> new Properties() {{
                    try {
                        load(new StringReader(p));
                    } catch (final IOException e) {
                        throw new IllegalArgumentException(e);
                    }
                }})
                .ifPresent(this::putAll);
    }});
}
 
Example #29
Source File: ModelEncryptionSupport.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static String tokenizeServerToken(ServerAccessToken token) {
    StringBuilder state = new StringBuilder();
    // 0: key
    state.append(tokenizeString(token.getTokenKey()));
    // 1: type
    state.append(SEP);
    state.append(tokenizeString(token.getTokenType()));
    // 2: expiresIn
    state.append(SEP);
    state.append(token.getExpiresIn());
    // 3: issuedAt
    state.append(SEP);
    state.append(token.getIssuedAt());
    // 4: client id
    state.append(SEP);
    state.append(tokenizeString(token.getClient().getClientId()));
    // 5: refresh token
    state.append(SEP);
    state.append(tokenizeString(token.getRefreshToken()));
    // 6: grant type
    state.append(SEP);
    state.append(tokenizeString(token.getGrantType()));
    // 7: audience
    state.append(SEP);
    state.append(token.getAudiences().toString());
    // 8: other parameters
    state.append(SEP);
    // {key=value, key=value}
    state.append(token.getParameters().toString());
    // 9: permissions
    state.append(SEP);
    if (token.getScopes().isEmpty()) {
        state.append(' ');
    } else {
        for (OAuthPermission p : token.getScopes()) {
            // 9.1
            state.append(tokenizeString(p.getPermission()));
            state.append('.');
            // 9.2
            state.append(tokenizeString(p.getDescription()));
            state.append('.');
            // 9.3
            state.append(p.isDefaultPermission());
            state.append('.');
            // 9.4
            state.append(p.getHttpVerbs().toString());
            state.append('.');
            // 9.5
            state.append(p.getUris().toString());
        }
    }
    state.append(SEP);
    // 10: code verifier
    state.append(tokenizeString(token.getClientCodeVerifier()));
    state.append(SEP);
    // 11: user subject
    tokenizeUserSubject(state, token.getSubject());
    // 13: extra properties
    state.append(SEP);
    // {key=value, key=value}
    state.append(token.getExtraProperties().toString());
    return state.toString();
}
 
Example #30
Source File: OAuthDataProviderImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public List<OAuthPermission> convertScopeToPermissions(Client client, List<String> requestedScope) {
    return null;
}