Search in sources :

Example 86 with OAuth2Request

use of org.forgerock.oauth2.core.OAuth2Request in project OpenAM by OpenRock.

the class OpenAMTokenStore method readDeviceCode.

@Override
public DeviceCode readDeviceCode(String clientId, String code, OAuth2Request request) throws ServerException, NotFoundException, InvalidGrantException {
    DeviceCode deviceCode = request.getToken(DeviceCode.class);
    if (deviceCode == null) {
        try {
            JsonValue token = tokenStore.read(code);
            if (token == null) {
                return null;
            }
            deviceCode = new DeviceCode(token);
        } catch (CoreTokenException e) {
            logger.error("Unable to read device code corresponding to id: " + code, e);
            throw new ServerException("Could not read token in CTS: " + e.getMessage());
        }
    }
    if (!clientId.equals(deviceCode.getClientId())) {
        throw new InvalidGrantException();
    }
    validateTokenRealm(deviceCode.getRealm(), request);
    request.setToken(DeviceCode.class, deviceCode);
    return deviceCode;
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) JsonValue(org.forgerock.json.JsonValue) DeviceCode(org.forgerock.oauth2.core.DeviceCode) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException)

Example 87 with OAuth2Request

use of org.forgerock.oauth2.core.OAuth2Request in project OpenAM by OpenRock.

the class DeviceCodeResource method issueCode.

@Post
public Representation issueCode(Representation body) throws OAuth2RestletException {
    final Request restletRequest = getRequest();
    OAuth2Request request = requestFactory.create(restletRequest);
    String state = request.getParameter(STATE);
    // Client ID, Response Type and Scope are required, all other parameters are optional
    String clientId = request.getParameter(CLIENT_ID);
    String scope = request.getParameter(SCOPE);
    String responseType = request.getParameter(RESPONSE_TYPE);
    try {
        if (isEmpty(clientId) || isEmpty(scope) || isEmpty(responseType)) {
            throw new OAuth2RestletException(400, "bad_request", "client_id, scope and response_type are required parameters", state);
        } else {
            // check client_id exists
            clientRegistrationStore.get(clientId, request);
        }
        if (scope == null) {
            scope = "";
        }
        final String maxAge = request.getParameter(MAX_AGE);
        DeviceCode code = tokenStore.createDeviceCode(oAuth2Utils.split(scope, " "), null, clientId, request.<String>getParameter(NONCE), request.<String>getParameter(RESPONSE_TYPE), request.<String>getParameter(STATE), request.<String>getParameter(ACR_VALUES), request.<String>getParameter(PROMPT), request.<String>getParameter(UI_LOCALES), request.<String>getParameter(LOGIN_HINT), maxAge == null ? null : Integer.valueOf(maxAge), request.<String>getParameter(CLAIMS), request, request.<String>getParameter(CODE_CHALLENGE), request.<String>getParameter(CODE_CHALLENGE_METHOD));
        Map<String, Object> result = new HashMap<>();
        OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
        result.put(DEVICE_CODE, code.getDeviceCode());
        result.put(USER_CODE, code.getUserCode());
        result.put(EXPIRES_IN, providerSettings.getDeviceCodeLifetime());
        result.put(INTERVAL, providerSettings.getDeviceCodePollInterval());
        String verificationUrl = providerSettings.getVerificationUrl();
        if (StringUtils.isBlank(verificationUrl)) {
            final HttpServletRequest servletRequest = ServletUtils.getRequest(restletRequest);
            final String realm = request.getParameter(OAuth2Constants.Custom.REALM);
            verificationUrl = baseURLProviderFactory.get(realm).getRootURL(servletRequest) + "/oauth2/device/user";
        }
        result.put(VERIFICATION_URL, verificationUrl);
        return jacksonRepresentationFactory.create(result);
    } catch (OAuth2Exception e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), state);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) HashMap(java.util.HashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(org.restlet.Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) DeviceCode(org.forgerock.oauth2.core.OAuth2Constants.DeviceCode) DeviceCode(org.forgerock.oauth2.core.DeviceCode) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) OAuth2Exception(org.forgerock.oauth2.core.exceptions.OAuth2Exception) Post(org.restlet.resource.Post)

Example 88 with OAuth2Request

use of org.forgerock.oauth2.core.OAuth2Request in project OpenAM by OpenRock.

the class DeviceCodeVerificationResource method verify.

/**
     * Handles POST requests to the OAuth2 device/user endpoint.
     */
@Post
public Representation verify(Representation body) throws ServerException, NotFoundException, InvalidGrantException, OAuth2RestletException {
    final Request restletRequest = getRequest();
    OAuth2Request request = requestFactory.create(restletRequest);
    DeviceCode deviceCode;
    try {
        deviceCode = tokenStore.readDeviceCode(request.<String>getParameter(OAuth2Constants.DeviceCode.USER_CODE), request);
    } catch (InvalidGrantException e) {
        return getTemplateRepresentation(FORM, request, "not_found");
    }
    if (deviceCode == null || deviceCode.isIssued()) {
        return getTemplateRepresentation(FORM, request, "not_found");
    }
    addRequestParamsFromDeviceCode(restletRequest, deviceCode);
    try {
        final String decision = request.getParameter("decision");
        if (StringUtils.isNotEmpty(decision)) {
            final boolean consentGiven = "allow".equalsIgnoreCase(decision);
            final boolean saveConsent = "on".equalsIgnoreCase(request.<String>getParameter("save_consent"));
            if (saveConsent) {
                saveConsent(request);
            }
            if (consentGiven) {
                ResourceOwner resourceOwner = resourceOwnerSessionValidator.validate(request);
                deviceCode.setResourceOwnerId(resourceOwner.getId());
                deviceCode.setAuthorized(true);
                tokenStore.updateDeviceCode(deviceCode, request);
            } else {
                tokenStore.deleteDeviceCode(deviceCode.getClientId(), deviceCode.getDeviceCode(), request);
            }
        } else {
            authorizationService.authorize(request);
        }
    } catch (IllegalArgumentException e) {
        if (e.getMessage().contains("client_id")) {
            throw new OAuth2RestletException(400, "invalid_request", e.getMessage(), request.<String>getParameter("state"));
        }
        throw new OAuth2RestletException(400, "invalid_request", e.getMessage(), request.<String>getParameter("redirect_uri"), request.<String>getParameter("state"));
    } catch (ResourceOwnerAuthenticationRequired e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), e.getRedirectUri().toString(), null);
    } catch (ResourceOwnerConsentRequired e) {
        return representation.getRepresentation(getContext(), request, "authorize.ftl", getDataModel(e, request));
    } catch (InvalidClientException | RedirectUriMismatchException e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), request.<String>getParameter("state"));
    } catch (OAuth2Exception e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), request.<String>getParameter("redirect_uri"), request.<String>getParameter("state"), e.getParameterLocation());
    }
    return getTemplateRepresentation(THANKS_PAGE, request, null);
}
Also used : ResourceOwnerAuthenticationRequired(org.forgerock.oauth2.core.exceptions.ResourceOwnerAuthenticationRequired) RedirectUriMismatchException(org.forgerock.oauth2.core.exceptions.RedirectUriMismatchException) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) ResourceOwnerConsentRequired(org.forgerock.oauth2.core.exceptions.ResourceOwnerConsentRequired) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) Request(org.restlet.Request) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) DeviceCode(org.forgerock.oauth2.core.DeviceCode) OAuth2Exception(org.forgerock.oauth2.core.exceptions.OAuth2Exception) Post(org.restlet.resource.Post)

Example 89 with OAuth2Request

use of org.forgerock.oauth2.core.OAuth2Request in project OpenAM by OpenRock.

the class DeviceCodeVerificationResource method saveConsent.

private void saveConsent(OAuth2Request request) throws NotFoundException, ServerException, InvalidScopeException, AccessDeniedException, ResourceOwnerAuthenticationRequired, InteractionRequiredException, BadRequestException, LoginRequiredException, InvalidClientException {
    OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    ResourceOwner resourceOwner = resourceOwnerSessionValidator.validate(request);
    ClientRegistration clientRegistration = clientRegistrationStore.get(request.<String>getParameter(CLIENT_ID), request);
    Set<String> scope = Utils.splitScope(request.<String>getParameter(SCOPE));
    Set<String> validatedScope = providerSettings.validateAuthorizationScope(clientRegistration, scope, request);
    providerSettings.saveConsent(resourceOwner, clientRegistration.getClientId(), validatedScope);
}
Also used : ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 90 with OAuth2Request

use of org.forgerock.oauth2.core.OAuth2Request in project OpenAM by OpenRock.

the class AuthorizationServiceImplTest method setUp.

@BeforeMethod
public void setUp() throws Exception {
    requestValidator = mock(AuthorizeRequestValidator.class);
    List<AuthorizeRequestValidator> requestValidators = new ArrayList<AuthorizeRequestValidator>();
    requestValidators.add(requestValidator);
    resourceOwnerSessionValidator = mock(ResourceOwnerSessionValidator.class);
    OAuth2ProviderSettingsFactory providerSettingsFactory = mock(OAuth2ProviderSettingsFactory.class);
    resourceOwnerConsentVerifier = mock(ResourceOwnerConsentVerifier.class);
    clientRegistrationStore = mock(ClientRegistrationStore.class);
    tokenIssuer = mock(AuthorizationTokenIssuer.class);
    ClientAuthenticationFailureFactory failureFactory = mock(ClientAuthenticationFailureFactory.class);
    authorizationService = new AuthorizationServiceImpl(requestValidators, resourceOwnerSessionValidator, providerSettingsFactory, resourceOwnerConsentVerifier, clientRegistrationStore, tokenIssuer, failureFactory);
    providerSettings = mock(OAuth2ProviderSettings.class);
    given(providerSettingsFactory.get(Matchers.<OAuth2Request>anyObject())).willReturn(providerSettings);
}
Also used : ArrayList(java.util.ArrayList) ClientAuthenticationFailureFactory(org.forgerock.oauth2.core.exceptions.ClientAuthenticationFailureFactory) BeforeMethod(org.testng.annotations.BeforeMethod)

Aggregations

OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)73 Test (org.testng.annotations.Test)45 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)32 Request (org.restlet.Request)31 AccessToken (org.forgerock.oauth2.core.AccessToken)27 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)27 JsonValue (org.forgerock.json.JsonValue)24 ChallengeResponse (org.restlet.data.ChallengeResponse)17 AccessTokenVerifier (org.forgerock.oauth2.core.AccessTokenVerifier)13 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)11 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)11 HashMap (java.util.HashMap)10 HashSet (java.util.HashSet)10 InvalidGrantException (org.forgerock.oauth2.core.exceptions.InvalidGrantException)10 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)10 Response (org.restlet.Response)10 ClientRegistration (org.forgerock.oauth2.core.ClientRegistration)9 OAuth2Exception (org.forgerock.oauth2.core.exceptions.OAuth2Exception)9 DeviceCode (org.forgerock.oauth2.core.DeviceCode)8 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)8