Search in sources :

Example 1 with OAuthAuthorizationData

use of org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData in project meecrowave by apache.

the class OAuth2Test method authorizationCode.

@Test
public void authorizationCode() throws URISyntaxException {
    final int httpPort = MEECROWAVE.getConfiguration().getHttpPort();
    createRedirectedClient(httpPort);
    final Client client = ClientBuilder.newClient().property(Message.MAINTAIN_SESSION, true).register(new OAuthJSONProvider());
    try {
        final WebTarget target = client.target("http://localhost:" + httpPort);
        final Response authorization = target.path("oauth2/authorize").queryParam(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE_GRANT).queryParam(OAuthConstants.RESPONSE_TYPE, OAuthConstants.CODE_RESPONSE_TYPE).queryParam(OAuthConstants.CLIENT_ID, "c1").queryParam(OAuthConstants.CLIENT_SECRET, "cpwd").queryParam(OAuthConstants.REDIRECT_URI, "http://localhost:" + httpPort + "/redirected").request(APPLICATION_JSON_TYPE).header("authorization", "Basic " + printBase64Binary("test:pwd".getBytes(StandardCharsets.UTF_8))).get();
        final OAuthAuthorizationData data = authorization.readEntity(OAuthAuthorizationData.class);
        assertNotNull(data.getAuthenticityToken());
        assertEquals("c1", data.getClientId());
        assertEquals("http://localhost:" + httpPort + "/oauth2/authorize/decision", data.getReplyTo());
        assertEquals("code", data.getResponseType());
        assertEquals("http://localhost:" + httpPort + "/redirected", data.getRedirectUri());
        final Response decision = target.path("oauth2/authorize/decision").queryParam(OAuthConstants.SESSION_AUTHENTICITY_TOKEN, data.getAuthenticityToken()).queryParam(OAuthConstants.AUTHORIZATION_DECISION_KEY, "allow").request(APPLICATION_JSON_TYPE).cookie(authorization.getCookies().get("JSESSIONID")).header("authorization", "Basic " + printBase64Binary("test:pwd".getBytes(StandardCharsets.UTF_8))).get();
        assertEquals(Response.Status.SEE_OTHER.getStatusCode(), decision.getStatus());
        assertTrue(decision.getLocation().toASCIIString(), decision.getLocation().toASCIIString().startsWith("http://localhost:" + httpPort + "/redirected?code="));
        final ClientAccessToken token = target.path("oauth2/token").request(APPLICATION_JSON_TYPE).post(entity(new Form().param(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE_GRANT).param(OAuthConstants.CODE_RESPONSE_TYPE, decision.getLocation().getRawQuery().substring("code=".length())).param(OAuthConstants.REDIRECT_URI, "http://localhost:" + httpPort + "/redirected").param(OAuthConstants.CLIENT_ID, "c1").param(OAuthConstants.CLIENT_SECRET, "cpwd"), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class);
        assertNotNull(token);
        assertEquals("Bearer", token.getTokenType());
        assertNotNull(token.getTokenKey());
        assertEquals(3600, token.getExpiresIn());
        assertNotEquals(0, token.getIssuedAt());
        assertNotNull(token.getRefreshToken());
    } finally {
        client.close();
    }
}
Also used : Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData) Test(org.junit.Test)

Example 2 with OAuthAuthorizationData

use of org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData in project cxf by apache.

the class AuthorizationCodeGrantService method createAuthorizationData.

@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;
}
Also used : OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)

Example 3 with OAuthAuthorizationData

use of org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData in project cxf by apache.

the class RedirectionBasedGrantService method startAuthorization.

protected Response startAuthorization(MultivaluedMap<String, String> params, UserSubject userSubject, Client client, String redirectUri) {
    // Enforce the client confidentiality requirements
    if (!OAuthUtils.isGrantSupportedForClient(client, canSupportPublicClient(client), supportedGrantType)) {
        LOG.fine("The grant type is not supported");
        return createErrorResponse(params, redirectUri, OAuthConstants.UNAUTHORIZED_CLIENT);
    }
    // Check response_type
    String responseType = params.getFirst(OAuthConstants.RESPONSE_TYPE);
    if (responseType == null || !getSupportedResponseTypes().contains(responseType)) {
        LOG.fine("The response type is null or not supported");
        return createErrorResponse(params, redirectUri, OAuthConstants.UNSUPPORTED_RESPONSE_TYPE);
    }
    // Get the requested scopes
    String providedScope = params.getFirst(OAuthConstants.SCOPE);
    List<String> requestedScope = null;
    List<OAuthPermission> requestedPermissions = null;
    try {
        requestedScope = OAuthUtils.getRequestedScopes(client, providedScope, useAllClientScopes, partialMatchScopeValidation);
        requestedPermissions = getDataProvider().convertScopeToPermissions(client, requestedScope);
    } catch (OAuthServiceException ex) {
        LOG.log(Level.FINE, "Error processing scopes", ex);
        return createErrorResponse(params, redirectUri, OAuthConstants.INVALID_SCOPE);
    }
    // Validate the audience
    String clientAudience = params.getFirst(OAuthConstants.CLIENT_AUDIENCE);
    // in the list of Client audiences set at the Client registration time.
    if (!OAuthUtils.validateAudience(clientAudience, client.getRegisteredAudiences())) {
        LOG.fine("Error validating audience parameter");
        return createErrorResponse(params, redirectUri, OAuthConstants.INVALID_REQUEST);
    }
    // Request a new grant only if no pre-authorized token is available
    ServerAccessToken preAuthorizedToken = null;
    if (canAccessTokenBeReturned(responseType)) {
        preAuthorizedToken = getDataProvider().getPreauthorizedToken(client, requestedScope, userSubject, supportedGrantType);
    }
    List<OAuthPermission> alreadyAuthorizedPerms = null;
    boolean preAuthorizationComplete = false;
    if (preAuthorizedToken != null) {
        alreadyAuthorizedPerms = preAuthorizedToken.getScopes();
        preAuthorizationComplete = OAuthUtils.convertPermissionsToScopeList(alreadyAuthorizedPerms).containsAll(requestedScope);
    }
    Response finalResponse = null;
    try {
        final boolean authorizationCanBeSkipped = preAuthorizationComplete || canAuthorizationBeSkipped(params, client, userSubject, requestedScope, requestedPermissions);
        // Populate the authorization challenge data
        OAuthAuthorizationData data = createAuthorizationData(client, params, redirectUri, userSubject, requestedPermissions, alreadyAuthorizedPerms, authorizationCanBeSkipped);
        if (authorizationCanBeSkipped) {
            getMessageContext().put(AUTHORIZATION_REQUEST_PARAMETERS, params);
            List<OAuthPermission> approvedScopes = preAuthorizationComplete ? preAuthorizedToken.getScopes() : requestedPermissions;
            finalResponse = createGrant(data, client, requestedScope, OAuthUtils.convertPermissionsToScopeList(approvedScopes), userSubject, preAuthorizedToken);
        } else {
            if (preAuthorizedToken != null) {
                data.setPreauthorizedTokenKey(preAuthorizedToken.getTokenKey());
            }
            finalResponse = Response.ok(data).build();
        }
    } catch (OAuthServiceException ex) {
        finalResponse = createErrorResponse(params, redirectUri, ex.getError().getError());
    }
    return finalResponse;
}
Also used : Response(javax.ws.rs.core.Response) OAuthPermission(org.apache.cxf.rs.security.oauth2.common.OAuthPermission) ServerAccessToken(org.apache.cxf.rs.security.oauth2.common.ServerAccessToken) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)

Example 4 with OAuthAuthorizationData

use of org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData in project cxf by apache.

the class OAuth2TestUtils method getLocation.

public static String getLocation(WebClient client, AuthorizationCodeParameters parameters) {
    // Make initial authorization request
    client.type("application/json").accept("application/json");
    client.query("client_id", parameters.getConsumerId());
    client.query("redirect_uri", "http://www.blah.apache.org");
    client.query("response_type", parameters.getResponseType());
    if (parameters.getScope() != null) {
        client.query("scope", parameters.getScope());
    }
    if (parameters.getNonce() != null) {
        client.query("nonce", parameters.getNonce());
    }
    if (parameters.getState() != null) {
        client.query("state", parameters.getState());
    }
    if (parameters.getRequest() != null) {
        client.query("request", parameters.getRequest());
    }
    client.path(parameters.getPath());
    Response response = client.get();
    OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);
    // Now call "decision" to get the authorization code grant
    client.path("decision");
    client.type("application/x-www-form-urlencoded");
    Form form = new Form();
    form.param("session_authenticity_token", authzData.getAuthenticityToken());
    form.param("client_id", authzData.getClientId());
    form.param("redirect_uri", authzData.getRedirectUri());
    if (authzData.getNonce() != null) {
        form.param("nonce", authzData.getNonce());
    }
    if (authzData.getProposedScope() != null) {
        form.param("scope", authzData.getProposedScope());
    }
    if (authzData.getState() != null) {
        form.param("state", authzData.getState());
    }
    form.param("response_type", authzData.getResponseType());
    form.param("oauthDecision", "allow");
    response = client.post(form);
    String location = response.getHeaderString("Location");
    if (parameters.getState() != null) {
        Assert.assertTrue(location.contains("state=" + parameters.getState()));
    }
    return location;
}
Also used : Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)

Example 5 with OAuthAuthorizationData

use of org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData in project cxf by apache.

the class OAuth2TestUtils method setupProviders.

public static List<Object> setupProviders() {
    List<Object> providers = new ArrayList<>();
    JSONProvider<OAuthAuthorizationData> jsonP = new JSONProvider<OAuthAuthorizationData>();
    jsonP.setNamespaceMap(Collections.singletonMap("http://org.apache.cxf.rs.security.oauth", "ns2"));
    providers.add(jsonP);
    providers.add(new OAuthJSONProvider());
    providers.add(new JsonWebKeysProvider());
    providers.add(new JsonMapObjectProvider());
    return providers;
}
Also used : JsonWebKeysProvider(org.apache.cxf.rs.security.jose.jaxrs.JsonWebKeysProvider) ArrayList(java.util.ArrayList) JSONProvider(org.apache.cxf.jaxrs.provider.json.JSONProvider) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) JsonMapObjectProvider(org.apache.cxf.jaxrs.provider.json.JsonMapObjectProvider) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)

Aggregations

OAuthAuthorizationData (org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData)14 Response (javax.ws.rs.core.Response)10 Form (javax.ws.rs.core.Form)9 URL (java.net.URL)5 WebClient (org.apache.cxf.jaxrs.client.WebClient)5 JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)4 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)4 OAuthPermission (org.apache.cxf.rs.security.oauth2.common.OAuthPermission)2 OAuthJSONProvider (org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider)2 ArrayList (java.util.ArrayList)1 Client (javax.ws.rs.client.Client)1 WebTarget (javax.ws.rs.client.WebTarget)1 JSONProvider (org.apache.cxf.jaxrs.provider.json.JSONProvider)1 JsonMapObjectProvider (org.apache.cxf.jaxrs.provider.json.JsonMapObjectProvider)1 JsonWebKeysProvider (org.apache.cxf.rs.security.jose.jaxrs.JsonWebKeysProvider)1 ClientAccessToken (org.apache.cxf.rs.security.oauth2.common.ClientAccessToken)1 ServerAccessToken (org.apache.cxf.rs.security.oauth2.common.ServerAccessToken)1 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)1 Test (org.junit.Test)1