org.apache.cxf.rs.security.oauth2.utils.OAuthConstants Java Examples

The following examples show how to use org.apache.cxf.rs.security.oauth2.utils.OAuthConstants. 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: Saml2BearerAuthHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void validateToken(Message message, Element element, String clientId) {

        SamlAssertionWrapper wrapper = toWrapper(element);
        // The common SAML assertion validation:
        // signature, subject confirmation, etc
        super.validateToken(message, wrapper);

        // This is specific to OAuth2 path
        // Introduce SAMLOAuth2Validator to be reused between auth and grant handlers
        Subject subject = SAMLUtils.getSubject(message, wrapper);
        if (subject.getName() == null) {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }

        if (clientId != null && !clientId.equals(subject.getName())) {
            //TODO:  Attempt to map client_id to subject.getName()
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
        samlOAuthValidator.validate(message, wrapper);
        message.put(OAuthConstants.CLIENT_ID, subject.getName());
    }
 
Example #2
Source File: OAuthClientUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static UriBuilder getAuthorizationURIBuilder(String authorizationServiceURI,
                                      String clientId,
                                      String redirectUri,
                                      String state,
                                      String scope) {
    UriBuilder ub = getAuthorizationURIBuilder(authorizationServiceURI,
                                               clientId,
                                               scope);
    if (redirectUri != null) {
        ub.queryParam(OAuthConstants.REDIRECT_URI, redirectUri);
    }
    if (state != null) {
        ub.queryParam(OAuthConstants.STATE, state);
    }
    return ub;
}
 
Example #3
Source File: AbstractImplicitGrantService.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected AbstractFormImplicitResponse prepareFormResponse(OAuthRedirectionState state,
                                       Client client,
                                       List<String> requestedScope,
                                       List<String> approvedScope,
                                       UserSubject userSubject,
                                       ServerAccessToken preAuthorizedToken) {

    ClientAccessToken clientToken =
        getClientAccessToken(state, client, requestedScope, approvedScope, userSubject, preAuthorizedToken);

    FormTokenResponse bean = new FormTokenResponse();
    bean.setResponseType(OAuthConstants.TOKEN_RESPONSE_TYPE);
    bean.setRedirectUri(state.getRedirectUri());
    bean.setState(state.getState());
    bean.setAccessToken(clientToken.getTokenKey());
    bean.setAccessTokenType(clientToken.getTokenType());
    bean.setAccessTokenExpiresIn(clientToken.getExpiresIn());
    bean.getParameters().putAll(clientToken.getParameters());
    return bean;
}
 
Example #4
Source File: OIDCClientLogic.java    From syncope with Apache License 2.0 6 votes vote down vote up
private static UserInfo getUserInfo(
    final String endpoint,
    final String accessToken,
    final IdToken idToken,
    final Consumer consumer) {

    WebClient userInfoServiceClient = WebClient.create(endpoint, List.of(new JsonMapObjectProvider())).
            accept(MediaType.APPLICATION_JSON);
    ClientAccessToken clientAccessToken =
            new ClientAccessToken(OAuthConstants.BEARER_AUTHORIZATION_SCHEME, accessToken);
    UserInfoClient userInfoClient = new UserInfoClient();
    userInfoClient.setUserInfoServiceClient(userInfoServiceClient);
    UserInfo userInfo = null;
    try {
        userInfo = userInfoClient.getUserInfo(clientAccessToken, idToken, consumer);
    } catch (Exception e) {
        LOG.error("While getting the userInfo", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
    return userInfo;
}
 
Example #5
Source File: HawkAuthorizationScheme.java    From cxf with Apache License 2.0 6 votes vote down vote up
public String toAuthorizationHeader(String macAlgo, String macSecret) {

        String data = getNormalizedRequestString();
        String signature = HmacUtils.encodeHmacString(macSecret,
                                                      HmacAlgorithm.toHmacAlgorithm(macAlgo).getJavaName(),
                                                      data);

        StringBuilder sb = new StringBuilder();
        sb.append(OAuthConstants.HAWK_AUTHORIZATION_SCHEME).append(' ');
        addParameter(sb, OAuthConstants.HAWK_TOKEN_ID, macKey, false);
        addParameter(sb, OAuthConstants.HAWK_TOKEN_TIMESTAMP, timestamp, false);
        addParameter(sb, OAuthConstants.HAWK_TOKEN_NONCE, nonce, false);
        addParameter(sb, OAuthConstants.HAWK_TOKEN_SIGNATURE, signature, true);

        return sb.toString();
    }
 
Example #6
Source File: AbstractTokenService.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Client getClientFromTLSCertificates(SecurityContext sc,
                                              TLSSessionInfo tlsSessionInfo,
                                              MultivaluedMap<String, String> params) {
    Client client = null;
    if (OAuthUtils.isMutualTls(sc, tlsSessionInfo)) {
        X509Certificate cert = OAuthUtils.getRootTLSCertificate(tlsSessionInfo);
        String subjectDn = OAuthUtils.getSubjectDnFromTLSCertificates(cert);
        if (!StringUtils.isEmpty(subjectDn)) {
            client = getClient(subjectDn, params);
            validateClientAuthenticationMethod(client, OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS);
            // The certificates must be registered with the client and match TLS certificates
            // in case of the binding where Client's clientId is a subject distinguished name
            compareTlsCertificates(tlsSessionInfo, client.getApplicationCertificates());
            OAuthUtils.setCertificateThumbprintConfirmation(getMessageContext(), cert);
        }
    }
    return client;
}
 
Example #7
Source File: SubjectCreatorImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public OidcUserSubject createUserSubject(MessageContext mc, MultivaluedMap<String, String> params) {
    OidcUserSubject oidcSub = new OidcUserSubject(OAuthUtils.createSubject(mc,
        (SecurityContext)mc.get(SecurityContext.class.getName())));

    final List<String> scopes;
    String requestedScope = params.getFirst(OAuthConstants.SCOPE);
    if (requestedScope != null && !requestedScope.isEmpty()) {
        scopes = OidcUtils.getScopeClaims(requestedScope.split(" "));
    } else {
        scopes = Collections.emptyList();
    }

    oidcSub.setIdToken(ID_TOKEN_PROVIDER.getIdToken(null, oidcSub, scopes));

    return oidcSub;
}
 
Example #8
Source File: ClientCodeRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void checkSecurityContextEnd(ContainerRequestContext rc,
                                     MultivaluedMap<String, String> requestParams) {
    SecurityContext sc = rc.getSecurityContext();
    if (sc == null || sc.getUserPrincipal() == null) {
        String codeParam = requestParams.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE);
        if (codeParam == null
            && requestParams.containsKey(OAuthConstants.ERROR_KEY)
            && !faultAccessDeniedResponses) {
            if (!applicationCanHandleAccessDenied) {
                String error = requestParams.getFirst(OAuthConstants.ERROR_KEY);
                rc.abortWith(Response.ok(new AccessDeniedResponse(error)).build());
            }
        } else {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
    }
}
 
Example #9
Source File: LogoutService.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private Client getClient(MultivaluedMap<String, String> params, IdToken idTokenHint) {
    String clientId = params.getFirst(OAuthConstants.CLIENT_ID);
    if (clientId == null && idTokenHint != null) {
        clientId = idTokenHint.getAudience();
        mc.getHttpServletRequest().setAttribute(OAuthConstants.CLIENT_ID, clientId);
    }
    if (clientId == null) {
        throw new BadRequestException();
    }
    Client c = dataProvider.getClient(clientId);
    if (c == null) {
        throw new BadRequestException();
    }
    if (StringUtils.isEmpty(c.getProperties().get(CLIENT_LOGOUT_URIS))) {
        throw new BadRequestException();
    }
    return c;
}
 
Example #10
Source File: JAXRSOAuth2Test.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicAuthClientCred() throws Exception {
    String address = "https://localhost:" + port + "/oauth2/token";
    WebClient wc = createWebClient(address);
    ClientCredentialsGrant grant = new ClientCredentialsGrant();
    // Pass client_id & client_secret as form properties
    // (instead WebClient can be initialized with username & password)
    grant.setClientId("bob");
    grant.setClientSecret("bobPassword");
    try {
        OAuthClientUtils.getAccessToken(wc, grant);
        fail("Form based authentication is not supported");
    } catch (OAuthServiceException ex) {
        assertEquals(OAuthConstants.UNAUTHORIZED_CLIENT, ex.getError().getError());
    }

    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
                                                           new Consumer("bob", "bobPassword"),
                                                           new ClientCredentialsGrant(),
                                                           true);
    assertNotNull(at.getTokenKey());
}
 
Example #11
Source File: IdTokenResponseFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void process(ClientAccessToken ct, ServerAccessToken st) {
    if (st.getResponseType() != null
        && OidcUtils.CODE_AT_RESPONSE_TYPE.equals(st.getResponseType())
        && OAuthConstants.IMPLICIT_GRANT.equals(st.getGrantType())) {
        // token post-processing as part of the current hybrid (implicit) flow
        // so no id_token is returned now - however when the code gets exchanged later on
        // this filter will add id_token to the returned access token
        return;
    }
    // Only add an IdToken if the client has the "openid" scope
    if (ct.getApprovedScope() == null || !ct.getApprovedScope().contains(OidcUtils.OPENID_SCOPE)) {
        return;
    }
    String idToken = getProcessedIdToken(st);
    if (idToken != null) {
        ct.getParameters().put(OidcUtils.ID_TOKEN, idToken);
    }

}
 
Example #12
Source File: DirectAuthorizationService.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Client getClient(MultivaluedMap<String, String> params) {
    Client client = null;

    try {
        client = getValidClient(params.getFirst(OAuthConstants.CLIENT_ID), params);
    } catch (OAuthServiceException ex) {
        if (ex.getError() != null) {
            reportInvalidRequestError(ex.getError(), null);
        }
    }

    if (client == null) {
        reportInvalidRequestError("Client ID is invalid", null);
    }
    return client;

}
 
Example #13
Source File: SamlOAuthValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void validate(Message message, SamlAssertionWrapper wrapper) {
    validateSAMLVersion(wrapper);

    Conditions cs = wrapper.getSaml2().getConditions();
    validateAudience(message, cs);

    if (issuer != null) {
        String actualIssuer = getIssuer(wrapper);
        String expectedIssuer = OAuthConstants.CLIENT_ID.equals(issuer)
            ? wrapper.getSaml2().getSubject().getNameID().getValue() : issuer;
        if (actualIssuer == null || !actualIssuer.equals(expectedIssuer)) {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
    }
    if (!validateAuthenticationSubject(message, cs, wrapper.getSaml2().getSubject())) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
}
 
Example #14
Source File: ClientCodeRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void processCodeResponse(ContainerRequestContext rc,
                                   UriInfo ui,
                                   MultivaluedMap<String, String> requestParams) {

    MultivaluedMap<String, String> state = null;
    if (clientStateManager != null) {
        state = clientStateManager.fromRedirectState(mc, requestParams);
    }

    String codeParam = requestParams.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE);
    ClientAccessToken at = null;
    if (codeParam != null) {
        AuthorizationCodeGrant grant = prepareCodeGrant(codeParam, getAbsoluteRedirectUri(ui));
        if (state != null) {
            grant.setCodeVerifier(state.getFirst(OAuthConstants.AUTHORIZATION_CODE_VERIFIER));
        }
        at = OAuthClientUtils.getAccessToken(accessTokenServiceClient, consumer, grant, useAuthorizationHeader);
    }
    ClientTokenContext tokenContext = initializeClientTokenContext(rc, at, requestParams, state);
    if (at != null && clientTokenContextManager != null) {
        clientTokenContextManager.setClientTokenContext(mc, tokenContext);
    }
    setClientCodeRequest(tokenContext);
}
 
Example #15
Source File: OAuthRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected String getTokenFromFormData(Message message) {
    String method = (String)message.get(Message.HTTP_REQUEST_METHOD);
    String type = (String)message.get(Message.CONTENT_TYPE);
    if (type != null && MediaType.APPLICATION_FORM_URLENCODED.startsWith(type)
        && method != null && (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT))) {
        try {
            FormEncodingProvider<Form> provider = new FormEncodingProvider<>(true);
            Form form = FormUtils.readForm(provider, message);
            MultivaluedMap<String, String> formData = form.asMap();
            String token = formData.getFirst(OAuthConstants.ACCESS_TOKEN);
            if (token != null) {
                FormUtils.restoreForm(provider, form, message);
                return token;
            }
        } catch (Exception ex) {
            // the exception will be thrown below
        }
    }
    AuthorizationUtils.throwAuthorizationFailure(supportedSchemes, realm);
    return null;
}
 
Example #16
Source File: ClientCodeRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected MultivaluedMap<String, String> createRedirectState(ContainerRequestContext rc,
                                                             UriInfo ui,
                                                             MultivaluedMap<String, String> codeRequestState) {
    if (clientStateManager == null) {
        return new MetadataMap<String, String>();
    }
    String codeVerifier = null;
    if (codeVerifierTransformer != null) {
        codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32));
        codeRequestState.putSingle(OAuthConstants.AUTHORIZATION_CODE_VERIFIER,
                                   codeVerifier);
    }
    MultivaluedMap<String, String> redirectState =
        clientStateManager.toRedirectState(mc, codeRequestState);
    if (codeVerifier != null) {
        redirectState.putSingle(OAuthConstants.AUTHORIZATION_CODE_VERIFIER, codeVerifier);
    }
    return redirectState;
}
 
Example #17
Source File: OidcImplicitService.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected String processIdToken(OAuthRedirectionState state, IdToken idToken) {
    OAuthJoseJwtProducer processor = idTokenHandler == null ? new OAuthJoseJwtProducer() : idTokenHandler;

    String code =
        (String)JAXRSUtils.getCurrentMessage().getExchange().get(OAuthConstants.AUTHORIZATION_CODE_VALUE);
    if (code != null) {
        // this service is invoked as part of the hybrid flow
        Properties props = JwsUtils.loadSignatureOutProperties(false);
        SignatureAlgorithm sigAlgo = null;
        if (processor.isSignWithClientSecret()) {
            sigAlgo = OAuthUtils.getClientSecretSignatureAlgorithm(props);
        } else {
            sigAlgo = JwsUtils.getSignatureAlgorithm(props, SignatureAlgorithm.RS256);
        }
        idToken.setAuthorizationCodeHash(OidcUtils.calculateAuthorizationCodeHash(code, sigAlgo));
    }

    idToken.setNonce(state.getNonce());
    return processor.processJwt(new JwtToken(idToken));
}
 
Example #18
Source File: OAuthClientUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void getAccessTokenInternalServerError() {
    WebClient accessTokenService = mock(WebClient.class);
    expect(accessTokenService.form(anyObject(Form.class)))
            .andReturn(Response.serverError().type(MediaType.TEXT_PLAIN)
                    .entity(new ByteArrayInputStream("Unrecoverable error in the server.".getBytes())).build());
    replay(accessTokenService);

    try {
        OAuthClientUtils.getAccessToken(accessTokenService, null, new RefreshTokenGrant(""), null, null, false);
        fail();
    } catch (OAuthServiceException e) {
        assertEquals(OAuthConstants.SERVER_ERROR, e.getMessage());
    } finally {
        verify(accessTokenService);
    }
}
 
Example #19
Source File: AccessTokenValidatorService.java    From cxf with Apache License 2.0 6 votes vote down vote up
@POST
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public AccessTokenValidation getTokenValidationInfo(@Encoded MultivaluedMap<String, String> params) {
    checkSecurityContext();
    String authScheme = params.getFirst(OAuthConstants.AUTHORIZATION_SCHEME_TYPE);
    String authSchemeData = params.getFirst(OAuthConstants.AUTHORIZATION_SCHEME_DATA);
    try {
        return super.getAccessTokenValidation(authScheme, authSchemeData, params);
    } catch (NotAuthorizedException ex) {
        // at this point it does not mean that RS failed to authenticate but that the basic
        // local or chained token validation has failed
        AccessTokenValidation v = new AccessTokenValidation();
        v.setInitialValidationSuccessful(false);
        return v;
    }
}
 
Example #20
Source File: AuthorizationService.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/decision")
public Response authorizeDecision(@QueryParam(OAuthConstants.RESPONSE_TYPE) String responseType) {
    RedirectionBasedGrantService service = getService(responseType);
    if (service != null) {
        return service.authorizeDecision();
    }
    return reportInvalidResponseType();
}
 
Example #21
Source File: AuthorizationService.java    From cxf with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces({"application/xhtml+xml", "text/html", "application/xml", "application/json" })
public Response authorizePost(MultivaluedMap<String, String> params) {
    String responseType = params.getFirst(OAuthConstants.RESPONSE_TYPE);
    RedirectionBasedGrantService service = getService(responseType);
    if (service != null) {
        return service.authorize();
    }
    return reportInvalidResponseType();
}
 
Example #22
Source File: AbstractGrant.java    From cxf with Apache License 2.0 5 votes vote down vote up
public MultivaluedMap<String, String> toMap() {
    MultivaluedMap<String, String> map = new MetadataMap<>();
    map.putSingle(OAuthConstants.GRANT_TYPE, getType());
    if (scope != null) {
        map.putSingle(OAuthConstants.SCOPE, scope);
    }
    if (audience != null) {
        map.putSingle(OAuthConstants.CLIENT_AUDIENCE, audience);
    }
    return map;
}
 
Example #23
Source File: ResourceOwnerGrant.java    From cxf with Apache License 2.0 5 votes vote down vote up
public MultivaluedMap<String, String> toMap() {
    MultivaluedMap<String, String> map = super.toMap();
    map.putSingle(OAuthConstants.RESOURCE_OWNER_NAME, ownerName);
    map.putSingle(OAuthConstants.RESOURCE_OWNER_PASSWORD, ownerPassword);

    return map;
}
 
Example #24
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 #25
Source File: ClientCodeRequestFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void setCodeVerifier(UriBuilder ub, MultivaluedMap<String, String> redirectState) {
    if (codeVerifierTransformer != null) {
        String codeVerifier = redirectState.getFirst(OAuthConstants.AUTHORIZATION_CODE_VERIFIER);
        ub.queryParam(OAuthConstants.AUTHORIZATION_CODE_CHALLENGE,
                      codeVerifierTransformer.transformCodeVerifier(codeVerifier));
        ub.queryParam(OAuthConstants.AUTHORIZATION_CODE_CHALLENGE_METHOD,
                      codeVerifierTransformer.getChallengeMethod());
    }
}
 
Example #26
Source File: DynamicRegistrationService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected ClientRegistration fromClientToClientRegistration(Client c) {
    ClientRegistration reg = new ClientRegistration();
    reg.setClientName(c.getApplicationName());
    reg.setGrantTypes(c.getAllowedGrantTypes());
    reg.setApplicationType(c.isConfidential() ? "web" : "native");
    if (!c.getRedirectUris().isEmpty()) {
        reg.setRedirectUris(c.getRedirectUris());
    }
    if (!c.getRegisteredScopes().isEmpty()) {
        reg.setScope(OAuthUtils.convertListOfScopesToString(c.getRegisteredScopes()));
    }
    if (c.getApplicationWebUri() != null) {
        reg.setClientUri(c.getApplicationWebUri());
    }
    if (c.getApplicationLogoUri() != null) {
        reg.setLogoUri(c.getApplicationLogoUri());
    }
    if (!c.getRegisteredAudiences().isEmpty()) {
        reg.setResourceUris(c.getRegisteredAudiences());
    }
    if (c.getTokenEndpointAuthMethod() != null) {
        reg.setTokenEndpointAuthMethod(c.getTokenEndpointAuthMethod());
        if (OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS.equals(c.getTokenEndpointAuthMethod())) {
            String subjectDn = c.getProperties().get(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN);
            if (subjectDn != null) {
                reg.setProperty(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN, subjectDn);
            }
            String issuerDn = c.getProperties().get(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN);
            if (issuerDn != null) {
                reg.setProperty(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN, issuerDn);
            }
        }
    }

    return reg;
}
 
Example #27
Source File: AbstractImplicitGrantService.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected StringBuilder prepareRedirectResponse(OAuthRedirectionState state,
                                      Client client,
                                      List<String> requestedScope,
                                      List<String> approvedScope,
                                      UserSubject userSubject,
                                      ServerAccessToken preAuthorizedToken) {

    ClientAccessToken clientToken =
        getClientAccessToken(state, client, requestedScope, approvedScope, userSubject, preAuthorizedToken);
    // return the token by appending it as a fragment parameter to the redirect URI

    StringBuilder sb = getUriWithFragment(state.getRedirectUri());

    sb.append(OAuthConstants.ACCESS_TOKEN).append('=').append(clientToken.getTokenKey());
    sb.append('&');
    sb.append(OAuthConstants.ACCESS_TOKEN_TYPE).append('=').append(clientToken.getTokenType());

    if (isWriteOptionalParameters()) {
        sb.append('&').append(OAuthConstants.ACCESS_TOKEN_EXPIRES_IN)
            .append('=').append(clientToken.getExpiresIn());
        if (!StringUtils.isEmpty(clientToken.getApprovedScope())) {
            sb.append('&').append(OAuthConstants.SCOPE).append('=')
                .append(HttpUtils.queryEncode(clientToken.getApprovedScope()));
        }
        for (Map.Entry<String, String> entry : clientToken.getParameters().entrySet()) {
            sb.append('&').append(entry.getKey()).append('=').append(HttpUtils.queryEncode(entry.getValue()));
        }
    }
    if (clientToken.getRefreshToken() != null) {
        processRefreshToken(sb, clientToken.getRefreshToken());
    }

    finalizeResponse(sb, state);
    return sb;
}
 
Example #28
Source File: OAuthJSONProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadHawkClientAccessToken() throws Exception {
    String response = "{" + "\"access_token\":\"1234\"," + "\"token_type\":\"hawk\","
        + "\"refresh_token\":\"5678\"," + "\"expires_in\":12345," + "\"scope\":\"read\","
        + "\"secret\":\"adijq39jdlaska9asud\"," + "\"algorithm\":\"hmac-sha-256\","
        + "\"my_parameter\":\"http://abc\"" + "}";
    ClientAccessToken macToken = doReadClientAccessToken(response, "hawk", null);
    assertEquals("adijq39jdlaska9asud",
                 macToken.getParameters().get(OAuthConstants.HAWK_TOKEN_KEY));
    assertEquals("hmac-sha-256",
                 macToken.getParameters().get(OAuthConstants.HAWK_TOKEN_ALGORITHM));
}
 
Example #29
Source File: ClientRegistrationService.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
@Path("/{id}/at/{tokenId}/revoke")
public ClientTokens revokeClientAccessToken(@PathParam("id") String clientId,
                                                  @PathParam("tokenId") String tokenId,
                                                  @FormParam("client_csrfToken") String csrfToken) {
    
    return doRevokeClientToken(clientId, csrfToken, tokenId, OAuthConstants.ACCESS_TOKEN);
}
 
Example #30
Source File: AbstractGrantHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected ServerAccessToken doCreateAccessToken(Client client,
                                                UserSubject subject,
                                                MultivaluedMap<String, String> params) {

    return doCreateAccessToken(client,
                               subject,
                               OAuthUtils.parseScope(params.getFirst(OAuthConstants.SCOPE)),
                               getAudiences(client, params.getFirst(OAuthConstants.CLIENT_AUDIENCE)));
}