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

The following examples show how to use org.apache.cxf.rs.security.oauth2.utils.OAuthConstants. These examples are extracted from open source projects. 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 Project: cxf   Source File: DirectAuthorizationService.java    License: 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 2
Source Project: syncope   Source File: OIDCClientLogic.java    License: 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 3
Source Project: cxf   Source File: OAuthClientUtils.java    License: 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 4
Source Project: cxf   Source File: AbstractImplicitGrantService.java    License: 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 5
Source Project: cxf   Source File: HawkAuthorizationScheme.java    License: 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 Project: cxf   Source File: SubjectCreatorImpl.java    License: 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 7
Source Project: cxf-fediz   Source File: LogoutService.java    License: 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 8
Source Project: cxf   Source File: JAXRSOAuth2Test.java    License: 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 9
Source Project: cxf   Source File: AccessTokenValidatorService.java    License: 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 10
Source Project: cxf   Source File: OAuthClientUtilsTest.java    License: 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 11
Source Project: cxf   Source File: OidcImplicitService.java    License: 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 12
Source Project: cxf   Source File: ClientCodeRequestFilter.java    License: 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 13
Source Project: cxf   Source File: ClientCodeRequestFilter.java    License: 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 14
Source Project: cxf   Source File: Saml2BearerAuthHandler.java    License: 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 15
Source Project: cxf   Source File: SamlOAuthValidator.java    License: 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 16
Source Project: cxf   Source File: OAuthRequestFilter.java    License: 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 17
Source Project: cxf   Source File: IdTokenResponseFilter.java    License: 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 18
Source Project: cxf   Source File: ClientCodeRequestFilter.java    License: 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 19
Source Project: cxf   Source File: AbstractTokenService.java    License: 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 20
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 21
Source Project: cxf   Source File: AbstractTokenService.java    License: Apache License 2.0 5 votes vote down vote up
protected String retrieveClientId(MultivaluedMap<String, String> params) {
    String clientId = params.getFirst(OAuthConstants.CLIENT_ID);
    if (clientId == null) {
        clientId = (String)getMessageContext().get(OAuthConstants.CLIENT_ID);
    }
    if (clientId == null && clientIdProvider != null) {
        clientId = clientIdProvider.getClientId(getMessageContext());
    }
    return clientId;
}
 
Example 22
Source Project: syncope   Source File: OIDCClientLogic.java    License: Apache License 2.0 5 votes vote down vote up
@PreAuthorize("hasRole('" + IdRepoEntitlement.ANONYMOUS + "')")
public OIDCLoginRequestTO createLoginRequest(final String redirectURI, final String opName) {
    // 1. look for Provider
    OIDCProvider op = getOIDCProvider(opName);

    // 2. create AuthnRequest
    OIDCLoginRequestTO requestTO = new OIDCLoginRequestTO();
    requestTO.setProviderAddress(op.getAuthorizationEndpoint());
    requestTO.setClientId(op.getClientID());
    requestTO.setScope("openid email profile");
    requestTO.setResponseType(OAuthConstants.CODE_RESPONSE_TYPE);
    requestTO.setRedirectURI(redirectURI);
    requestTO.setState(SecureRandomUtils.generateRandomUUID().toString());
    return requestTO;
}
 
Example 23
Source Project: attic-stratos   Source File: ValidationServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
public OAuth2TokenValidationResponseDTO validateAuthenticationRequest(String accessToken) throws Exception {
    OAuth2TokenValidationRequestDTO oauthReq = new OAuth2TokenValidationRequestDTO();
    OAuth2TokenValidationRequestDTO_OAuth2AccessToken oAuth2AccessToken
            = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
    oAuth2AccessToken.setIdentifier(accessToken);
    oAuth2AccessToken.setTokenType(OAuthConstants.BEARER_TOKEN_TYPE);
    oauthReq.setAccessToken(oAuth2AccessToken);
    try {
        return stub.validate(oauthReq);
    } catch (RemoteException e) {
        log.error("Error while validating OAuth2 request");
        throw new Exception("Error while validating OAuth2 request", e);
    }
}
 
Example 24
Source Project: cxf   Source File: OIDCDynamicRegistrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testRegisterClientInitialAccessTokenCodeGrant() throws Exception {
    URL busFile = OIDCDynamicRegistrationTest.class.getResource("client.xml");
    String address = "https://localhost:" + DYNREG_SERVER.getPort() + "/services/dynamicWithAt/register";
    WebClient wc =
        WebClient.create(address, Collections.singletonList(new JsonMapObjectProvider()), busFile.toString())
        .accept("application/json").type("application/json")
        .authorization(new ClientAccessToken(OAuthConstants.BEARER_AUTHORIZATION_SCHEME, ACCESS_TOKEN));

    ClientRegistration reg = newClientRegistrationCodeGrant();
    ClientRegistrationResponse resp = wc.post(reg, ClientRegistrationResponse.class);

    assertNotNull(resp.getClientId());
    assertNotNull(resp.getClientSecret());
    assertEquals(address + "/" + resp.getClientId(),
                 resp.getRegistrationClientUri());
    String regAccessToken = resp.getRegistrationAccessToken();
    assertNotNull(regAccessToken);

    wc.path(resp.getClientId());
    assertEquals(401, wc.get().getStatus());

    ClientRegistration clientRegResp = wc
        .authorization(new ClientAccessToken(OAuthConstants.BEARER_AUTHORIZATION_SCHEME, regAccessToken))
        .get(ClientRegistration.class);
    testCommonRegCodeGrantProperties(clientRegResp);

    assertNull(clientRegResp.getTokenEndpointAuthMethod());

    assertEquals(200, wc.delete().getStatus());
}
 
Example 25
Source Project: cxf   Source File: AbstractImplicitGrantService.java    License: Apache License 2.0 5 votes vote down vote up
protected Response createErrorResponse(String state,
                                       String redirectUri,
                                       String error) {
    StringBuilder sb = getUriWithFragment(redirectUri);
    sb.append(OAuthConstants.ERROR_KEY).append('=').append(error);
    if (state != null) {
        sb.append('&');
        sb.append(OAuthConstants.STATE).append('=').append(state);
    }

    return Response.seeOther(URI.create(sb.toString())).build();
}
 
Example 26
Source Project: cxf   Source File: OIDCDynamicRegistrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private static ClientRegistration newClientRegistrationCodeGrant() {
        final ClientRegistration reg = new ClientRegistration();
        reg.setApplicationType("web");
        reg.setScope(OidcUtils.getOpenIdScope());
        reg.setClientName("dynamic_client");
        reg.setGrantTypes(Collections.singletonList(OAuthConstants.AUTHORIZATION_CODE_GRANT));
//        reg.setResponseTypes(Collections.singletonList(OAuthConstants.CODE_RESPONSE_TYPE));
        reg.setRedirectUris(Collections.singletonList("https://a/b/c"));

        reg.setProperty("post_logout_redirect_uris",
                        Collections.singletonList("https://rp/logout"));
        return reg;
    }
 
Example 27
Source Project: cxf   Source File: OIDCDynamicRegistrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void testCommonRegCodeGrantProperties(ClientRegistration clientRegResp) {
        assertNotNull(clientRegResp);
        assertEquals("web", clientRegResp.getApplicationType());
        assertEquals("openid", clientRegResp.getScope());
        assertEquals("dynamic_client", clientRegResp.getClientName());
        assertEquals(Collections.singletonList(OAuthConstants.AUTHORIZATION_CODE_GRANT),
                     clientRegResp.getGrantTypes());
//        assertEquals(Collections.singletonList(OAuthConstants.CODE_RESPONSE_TYPE),
//                     clientRegResp.getResponseTypes());
        assertEquals(Collections.singletonList("https://a/b/c"),
                     clientRegResp.getRedirectUris());
        assertEquals(Collections.singletonList("https://rp/logout"),
                     clientRegResp.getListStringProperty("post_logout_redirect_uris"));
    }
 
Example 28
Source Project: cxf   Source File: OAuthClientUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getAccessToken() {
    WebClient accessTokenService = mock(WebClient.class);
    String tokenKey = "tokenKey";
    String response = "{\"" + OAuthConstants.ACCESS_TOKEN + "\":\"" + tokenKey + "\"}";
    expect(accessTokenService.form(anyObject(Form.class))).andReturn(
            Response.ok(new ByteArrayInputStream(response.getBytes()), MediaType.APPLICATION_JSON).build());
    replay(accessTokenService);

    ClientAccessToken cat = OAuthClientUtils.getAccessToken(accessTokenService, null, new RefreshTokenGrant(""),
            null, "defaultTokenType", false);
    assertEquals(tokenKey, cat.getTokenKey());

    verify(accessTokenService);
}
 
Example 29
public OAuth2TokenValidationResponseDTO validateAuthenticationRequest(String accessToken) throws Exception {
    OAuth2TokenValidationRequestDTO oauthReq = new OAuth2TokenValidationRequestDTO();
    oauthReq.setAccessToken(accessToken);
    oauthReq.setTokenType(OAuthConstants.BEARER_TOKEN_TYPE);
    try {
        return stub.validate(oauthReq);
    } catch (RemoteException e) {
        log.error("Error while validating OAuth2 request");
        throw new Exception("Error while validating OAuth2 request", e);
    }
}
 
Example 30
Source Project: cxf   Source File: ClientAccessToken.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    if (OAuthConstants.BEARER_AUTHORIZATION_SCHEME.equalsIgnoreCase(super.getTokenType())) {
        return OAuthConstants.BEARER_AUTHORIZATION_SCHEME + " " + super.getTokenKey();
    }
    return super.toString();
}