Java源码示例:org.apache.cxf.rs.security.oauth2.utils.OAuthConstants

示例1
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;

}
 
示例2
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;
}
 
示例3
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;
}
 
示例4
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;
}
 
示例5
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();
    }
 
示例6
@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;
}
 
示例7
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;
}
 
示例8
@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());
}
 
示例9
@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;
    }
}
 
示例10
@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);
    }
}
 
示例11
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));
}
 
示例12
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;
}
 
示例13
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);
}
 
示例14
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());
    }
 
示例15
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);
    }
}
 
示例16
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;
}
 
示例17
@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);
    }

}
 
示例18
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);
        }
    }
}
 
示例19
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;
}
 
示例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);
    }
}
 
示例21
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;
}
 
示例22
@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;
}
 
示例23
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);
    }
}
 
示例24
@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());
}
 
示例25
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();
}
 
示例26
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;
    }
 
示例27
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"));
    }
 
示例28
@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);
}
 
示例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);
    }
}
 
示例30
@Override
public String toString() {
    if (OAuthConstants.BEARER_AUTHORIZATION_SCHEME.equalsIgnoreCase(super.getTokenType())) {
        return OAuthConstants.BEARER_AUTHORIZATION_SCHEME + " " + super.getTokenKey();
    }
    return super.toString();
}