Search in sources :

Example 51 with OAuth2Request

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

the class OpenIDConnectProviderDiscovery method discover.

/**
     * Returns the response to a request to discover the OpenId Connect provider.
     *
     * @param resource The resource.
     * @param rel The rel.
     * @param deploymentUrl The deployment url of the OpenId Connect provider.
     * @param request The OAuth2 request.
     * @return A {@code Map} of the OpenId Connect provider urls.
     * @throws BadRequestException If the request is malformed.
     * @throws NotFoundException If the user cannot be found.
     */
public Map<String, Object> discover(String resource, String rel, String deploymentUrl, OAuth2Request request) throws BadRequestException, NotFoundException {
    if (resource == null || resource.isEmpty()) {
        logger.error("No resource provided in discovery.");
        throw new BadRequestException("No resource provided in discovery.");
    }
    if (rel == null || rel.isEmpty() || !rel.equalsIgnoreCase("http://openid.net/specs/connect/1.0/issuer")) {
        logger.error("No or invalid rel provided in discovery.");
        throw new BadRequestException("No or invalid rel provided in discovery.");
    }
    String userid = null;
    //test if the resource is a uri
    try {
        final URI object = new URI(resource);
        if (object.getScheme().equalsIgnoreCase("https") || object.getScheme().equalsIgnoreCase("http")) {
            //resource is of the form of https://example.com/
            if (!object.getPath().isEmpty()) {
                //resource is of the form of https://example.com/joe
                userid = object.getPath();
                userid = userid.substring(1, userid.length());
            }
        } else if (object.getScheme().equalsIgnoreCase("acct")) {
            //resource is not uri so only option is it is an email of form acct:joe@example.com
            String s = new String(resource);
            s = s.replaceFirst("acct:", "");
            final int firstAt = s.indexOf('@');
            userid = s.substring(0, firstAt);
        } else {
            logger.error("Invalid parameters.");
            throw new BadRequestException("Invalid parameters.");
        }
    } catch (Exception e) {
        logger.error("Invalid parameters.", e);
        throw new BadRequestException("Invalid parameters.");
    }
    if (userid != null) {
        if (!openIDConnectProvider.isUserValid(userid, request)) {
            logger.error("Invalid parameters.");
            throw new NotFoundException("Invalid parameters.");
        }
    }
    final Map<String, Object> response = new HashMap<String, Object>();
    response.put("subject", resource);
    final Set<Object> set = new HashSet<Object>();
    final Map<String, Object> objectMap = new HashMap<String, Object>();
    objectMap.put("rel", rel);
    objectMap.put("href", deploymentUrl + "/oauth2");
    set.add(objectMap);
    response.put("links", set);
    return response;
}
Also used : HashMap(java.util.HashMap) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) URI(java.net.URI) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) HashSet(java.util.HashSet)

Example 52 with OAuth2Request

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

the class OpenIdConnectAuthorizeRequestValidator method validateOpenIdScope.

private void validateOpenIdScope(OAuth2Request request) throws InvalidClientException, InvalidRequestException, InvalidScopeException, NotFoundException {
    final ClientRegistration clientRegistration = clientRegistrationStore.get(request.<String>getParameter(CLIENT_ID), request);
    if (Utils.isOpenIdConnectClient(clientRegistration)) {
        final Set<String> responseTypes = Utils.splitResponseType(request.<String>getParameter(RESPONSE_TYPE));
        Set<String> requestedScopes = Utils.splitScope(request.<String>getParameter(SCOPE));
        if (CollectionUtils.isEmpty(requestedScopes)) {
            requestedScopes = clientRegistration.getDefaultScopes();
        }
        if (!requestedScopes.contains(OPENID)) {
            throw new InvalidRequestException("Missing expected scope=openid from request", Utils.isOpenIdConnectFragmentErrorType(responseTypes) ? FRAGMENT : QUERY);
        }
        validateNonce(request, responseTypes);
    }
}
Also used : ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException)

Example 53 with OAuth2Request

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

the class EndSession method endSession.

/**
     * Handles GET requests to the OpenId Connect end session endpoint for ending OpenId Connect user sessions.
     *
     * @return The OpenId Connect token of the session that has ended.
     * @throws OAuth2RestletException If an error occurs whilst ending the users session.
     */
@Get
public Representation endSession() throws OAuth2RestletException {
    final OAuth2Request request = requestFactory.create(getRequest());
    final String idToken = request.getParameter(OAuth2Constants.Params.END_SESSION_ID_TOKEN_HINT);
    final String redirectUri = request.getParameter(OAuth2Constants.Params.POST_LOGOUT_REDIRECT_URI);
    try {
        openIDConnectEndSession.endSession(idToken);
        if (StringUtils.isNotEmpty(redirectUri)) {
            return handleRedirect(request, idToken, redirectUri);
        }
    } catch (OAuth2Exception e) {
        throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), null);
    }
    return null;
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) OAuth2RestletException(org.forgerock.oauth2.restlet.OAuth2RestletException) OAuth2Exception(org.forgerock.oauth2.core.exceptions.OAuth2Exception) Get(org.restlet.resource.Get)

Example 54 with OAuth2Request

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

the class ClientCredentialsReader method verifyJwtBearer.

private ClientCredentials verifyJwtBearer(OAuth2Request request, boolean basicAuth, String endpoint) throws InvalidClientException, InvalidRequestException, NotFoundException {
    final OAuth2Jwt jwt = OAuth2Jwt.create(request.<String>getParameter(CLIENT_ASSERTION));
    final ClientRegistration clientRegistration = clientRegistrationStore.get(jwt.getSubject(), request);
    if (jwt.isExpired()) {
        throw failureFactory.getException(request, "JWT has expired");
    }
    if (!clientRegistration.verifyJwtIdentity(jwt)) {
        throw failureFactory.getException(request, "JWT is not valid");
    }
    if (basicAuth && jwt.getSubject() != null) {
        logger.error("Client (" + jwt.getSubject() + ") using multiple authentication methods");
        throw failureFactory.getException(request, "Client authentication failed");
    }
    if (endpoint != null && !jwt.isIntendedForAudience(endpoint)) {
        throw failureFactory.getException(request, "Audience validation failed");
    }
    return new ClientCredentials(jwt.getSubject(), null, true, false);
}
Also used : OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) OAuth2Jwt(org.forgerock.oauth2.core.OAuth2Jwt)

Example 55 with OAuth2Request

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

the class OpenAMClientDAO method read.

/**
     * {@inheritDoc}
     */
public Client read(String clientId, OAuth2Request request) throws UnauthorizedClientException {
    Map<String, Set<String>> clientAttributes = new HashMap<String, Set<String>>();
    try {
        AMIdentity theID = null;
        final SSOToken token = AccessController.doPrivileged(AdminTokenAction.getInstance());
        final String realm = request.getParameter(OAuth2Constants.Custom.REALM);
        AMIdentityRepository repo = idRepoFactory.create(realm, token);
        IdSearchControl idsc = new IdSearchControl();
        idsc.setRecursive(true);
        idsc.setAllReturnAttributes(true);
        // search for the identity
        Set<AMIdentity> results;
        idsc.setMaxResults(0);
        IdSearchResults searchResults = repo.searchIdentities(IdType.AGENTONLY, clientId, idsc);
        results = searchResults.getSearchResults();
        if (results == null || results.size() != 1) {
            logger.error("OpenAMClientDAO.read(): No client profile or more than one profile found.");
            throw new UnauthorizedClientException("Not able to get client from OpenAM");
        }
        theID = results.iterator().next();
        //if the client is deactivated return null
        if (!theID.isActive()) {
            theID = null;
        } else {
            clientAttributes = theID.getAttributes();
        }
    } catch (UnauthorizedClientException e) {
        logger.error("OpenAMClientDAO.read(): Unable to get client AMIdentity: ", e);
        throw new UnauthorizedClientException("Not able to get client from OpenAM");
    } catch (SSOException e) {
        logger.error("OpenAMClientDAO.read(): Unable to get client AMIdentity: ", e);
        throw new UnauthorizedClientException("Not able to get client from OpenAM");
    } catch (IdRepoException e) {
        logger.error("OpenAMClientDAO.read(): Unable to get client AMIdentity: ", e);
        throw new UnauthorizedClientException("Not able to get client from OpenAM");
    }
    Client client = createClient(clientAttributes);
    client.setClientID(clientId);
    return client;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) SSOToken(com.iplanet.sso.SSOToken) HashMap(java.util.HashMap) IdSearchResults(com.sun.identity.idm.IdSearchResults) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) AMIdentity(com.sun.identity.idm.AMIdentity) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdSearchControl(com.sun.identity.idm.IdSearchControl) OAuth2Client(org.forgerock.oauth2.core.OAuth2Constants.OAuth2Client) Client(org.forgerock.openidconnect.Client)

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