Search in sources :

Example 1 with Scope

use of com.nimbusds.oauth2.sdk.Scope in project spring-security by spring-projects.

the class NimbusOpaqueTokenIntrospector method convertClaimsSet.

private OAuth2AuthenticatedPrincipal convertClaimsSet(TokenIntrospectionSuccessResponse response) {
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    Map<String, Object> claims = response.toJSONObject();
    if (response.getAudience() != null) {
        List<String> audiences = new ArrayList<>();
        for (Audience audience : response.getAudience()) {
            audiences.add(audience.getValue());
        }
        claims.put(OAuth2TokenIntrospectionClaimNames.AUD, Collections.unmodifiableList(audiences));
    }
    if (response.getClientID() != null) {
        claims.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, response.getClientID().getValue());
    }
    if (response.getExpirationTime() != null) {
        Instant exp = response.getExpirationTime().toInstant();
        claims.put(OAuth2TokenIntrospectionClaimNames.EXP, exp);
    }
    if (response.getIssueTime() != null) {
        Instant iat = response.getIssueTime().toInstant();
        claims.put(OAuth2TokenIntrospectionClaimNames.IAT, iat);
    }
    if (response.getIssuer() != null) {
        // RFC-7662 page 7 directs users to RFC-7519 for defining the values of these
        // issuer fields.
        // https://datatracker.ietf.org/doc/html/rfc7662#page-7
        // 
        // RFC-7519 page 9 defines issuer fields as being 'case-sensitive' strings
        // containing
        // a 'StringOrURI', which is defined on page 5 as being any string, but
        // strings containing ':'
        // should be treated as valid URIs.
        // https://datatracker.ietf.org/doc/html/rfc7519#section-2
        // 
        // It is not defined however as to whether-or-not normalized URIs should be
        // treated as the same literal
        // value. It only defines validation itself, so to avoid potential ambiguity
        // or unwanted side effects that
        // may be awkward to debug, we do not want to manipulate this value. Previous
        // versions of Spring Security
        // would *only* allow valid URLs, which is not what we wish to achieve here.
        claims.put(OAuth2TokenIntrospectionClaimNames.ISS, response.getIssuer().getValue());
    }
    if (response.getNotBeforeTime() != null) {
        claims.put(OAuth2TokenIntrospectionClaimNames.NBF, response.getNotBeforeTime().toInstant());
    }
    if (response.getScope() != null) {
        List<String> scopes = Collections.unmodifiableList(response.getScope().toStringList());
        claims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, scopes);
        for (String scope : scopes) {
            authorities.add(new SimpleGrantedAuthority(AUTHORITY_PREFIX + scope));
        }
    }
    return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities);
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Audience(com.nimbusds.oauth2.sdk.id.Audience) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Instant(java.time.Instant) ArrayList(java.util.ArrayList) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject)

Example 2 with Scope

use of com.nimbusds.oauth2.sdk.Scope in project cas by apereo.

the class NimbusOAuthJacksonModuleTests method verifyOperation.

@Test
public void verifyOperation() throws Exception {
    val mapper = SERIALIZER.getObjectMapper();
    assertTrue(mapper.getRegisteredModuleIds().contains(NimbusOAuthJacksonModule.class.getName()));
    runTest(CodeVerifier.class, new CodeVerifier(RandomUtils.randomAlphabetic(CodeVerifier.MIN_LENGTH)));
    runTest(BearerAccessToken.class, new BearerAccessToken("access-token-value"));
    runTest(RefreshToken.class, new RefreshToken("access-token-value"));
    runTest(AccessTokenType.class, AccessTokenType.BEARER);
    runTest(Scope.class, new Scope("profile"));
}
Also used : lombok.val(lombok.val) CodeVerifier(com.nimbusds.oauth2.sdk.pkce.CodeVerifier) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) Scope(com.nimbusds.oauth2.sdk.Scope) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Test(org.junit.jupiter.api.Test)

Example 3 with Scope

use of com.nimbusds.oauth2.sdk.Scope in project ddf by codice.

the class OidcHandlerConfigurationImpl method setProperties.

public void setProperties(Map<String, Object> properties) {
    if (properties == null || properties.isEmpty()) {
        LOGGER.warn("Received null or empty properties. Cannot update.");
        return;
    }
    idpType = (String) properties.getOrDefault(IDP_TYPE_KEY, idpType);
    clientId = (String) properties.getOrDefault(CLIENT_ID_KEY, idpType);
    realm = (String) properties.getOrDefault(REALM_KEY, realm);
    secret = (String) properties.getOrDefault(SECRET_KEY, secret);
    discoveryUri = (String) properties.getOrDefault(DISCOVERY_URI_KEY, discoveryUri);
    baseUri = (String) properties.getOrDefault(BASE_URI_KEY, baseUri);
    scope = (String) properties.getOrDefault(SCOPE_KEY, scope);
    useNonce = (boolean) properties.getOrDefault(USE_NONCE_KEY, useNonce);
    responseType = (String) properties.getOrDefault(RESPONSE_TYPE_KEY, responseType);
    responseMode = (String) properties.getOrDefault(RESPONSE_MODE_KEY, responseMode);
    logoutUri = (String) properties.getOrDefault(LOGOUT_URI_KEY, logoutUri);
    connectTimeout = (int) properties.getOrDefault(CONNECT_TIMEOUT_KEY, connectTimeout);
    readTimeout = (int) properties.getOrDefault(READ_TIMEOUT_KEY, readTimeout);
    // TODO - Remove if fragment response_mode is supported
    if (IMPLICIT_FLOWS.contains(new ResponseType(responseType))) {
        responseMode = "form_post";
    }
    oidcConfiguration = createOidcConfiguration(idpType, realm, baseUri);
    oidcConfiguration.setClientId(clientId);
    oidcConfiguration.setDiscoveryURI(discoveryUri);
    oidcConfiguration.setSecret(secret);
    oidcConfiguration.setScope(scope);
    oidcConfiguration.setResponseType(responseType);
    oidcConfiguration.setResponseMode(responseMode);
    oidcConfiguration.setUseNonce(useNonce);
    oidcConfiguration.setLogoutUrl(logoutUri);
    oidcConfiguration.setWithState(true);
    oidcConfiguration.setConnectTimeout(connectTimeout);
    oidcConfiguration.setReadTimeout(readTimeout);
    try {
        testConnection();
    } catch (TechnicalException e) {
        LOGGER.warn("Failed to validate OIDC handler configuration. Please review configuration and ensure the auth server is reachable", e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Example 4 with Scope

use of com.nimbusds.oauth2.sdk.Scope in project nifi by apache.

the class AccessResource method oidcRequest.

@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
@Path("oidc/request")
@ApiOperation(value = "Initiates a request to authenticate through the configured OpenId Connect provider.", notes = NON_GUARANTEED_ENDPOINT)
public void oidcRequest(@Context HttpServletRequest httpServletRequest, @Context HttpServletResponse httpServletResponse) throws Exception {
    // only consider user specific access over https
    if (!httpServletRequest.isSecure()) {
        forwardToMessagePage(httpServletRequest, httpServletResponse, "User authentication/authorization is only supported when running over HTTPS.");
        return;
    }
    // ensure oidc is enabled
    if (!oidcService.isOidcEnabled()) {
        forwardToMessagePage(httpServletRequest, httpServletResponse, "OpenId Connect is not configured.");
        return;
    }
    final String oidcRequestIdentifier = UUID.randomUUID().toString();
    // generate a cookie to associate this login sequence
    final Cookie cookie = new Cookie(OIDC_REQUEST_IDENTIFIER, oidcRequestIdentifier);
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    cookie.setMaxAge(60);
    cookie.setSecure(true);
    httpServletResponse.addCookie(cookie);
    // get the state for this request
    final State state = oidcService.createState(oidcRequestIdentifier);
    // build the authorization uri
    final URI authorizationUri = UriBuilder.fromUri(oidcService.getAuthorizationEndpoint()).queryParam("client_id", oidcService.getClientId()).queryParam("response_type", "code").queryParam("scope", oidcService.getScope().toString()).queryParam("state", state.getValue()).queryParam("redirect_uri", getOidcCallback()).build();
    // generate the response
    httpServletResponse.sendRedirect(authorizationUri.toString());
}
Also used : Cookie(javax.servlet.http.Cookie) State(com.nimbusds.oauth2.sdk.id.State) URI(java.net.URI) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 5 with Scope

use of com.nimbusds.oauth2.sdk.Scope in project ddf by codice.

the class OAuthSecurityImpl method getNewAccessToken.

/**
 * Gets an access token from the configured OAuth provider, saves it to the token storage and
 * returns it
 *
 * @param id The ID to use when storing tokens
 * @param sourceId The ID of the source using OAuth to use when storing tokens
 * @param encodedClientIdSecret The base 64 encoded clientId:secret
 * @param discoveryUrl The URL where the Oauth provider's metadata is hosted
 * @param grantType The OAuth grand type to use
 * @param queryParameters Query parameters to send
 * @return a client access token or null if one could not be returned
 */
private String getNewAccessToken(String id, String sourceId, String encodedClientIdSecret, String discoveryUrl, String grantType, Map<String, String> queryParameters, OIDCProviderMetadata metadata) {
    WebClient webClient = createWebClient(metadata.getTokenEndpointURI());
    webClient.header(AUTHORIZATION, BASIC + encodedClientIdSecret);
    webClient.accept(APPLICATION_JSON);
    Form formParam = new Form(GRANT_TYPE, grantType);
    formParam.param(SCOPE, OPENID_SCOPE);
    queryParameters.forEach(formParam::param);
    javax.ws.rs.core.Response response = webClient.form(formParam);
    String body;
    try {
        body = IOUtils.toString((InputStream) response.getEntity(), UTF_8);
    } catch (IOException e) {
        LOGGER.debug("Unable to retrieve system access token.", e);
        return null;
    }
    if (response.getStatus() != HttpStatus.SC_OK) {
        LOGGER.debug("Unable to retrieve system access token. {}", body);
        if (LOGGER.isTraceEnabled()) {
            sanitizeFormParameters(formParam);
            LOGGER.trace("Unable to retrieve system access token. Headers: {}, Request: {}, Status: {}, Response: {}", webClient.getHeaders(), formParam.asMap(), response.getStatus(), body);
        }
        return null;
    }
    Map<String, String> map = GSON.fromJson(body, MAP_STRING_TO_OBJECT_TYPE);
    String idToken = map.get(ID_TOKEN);
    String accessToken = map.get(ACCESS_TOKEN);
    String refreshToken = map.get(REFRESH_TOKEN);
    JWT jwt = null;
    try {
        if (idToken != null) {
            jwt = SignedJWT.parse(idToken);
        }
    } catch (java.text.ParseException e) {
        LOGGER.debug("Error parsing ID token.", e);
    }
    try {
        OidcTokenValidator.validateAccessToken(new BearerAccessToken(accessToken), jwt, resourceRetriever, metadata, null);
    } catch (OidcValidationException e) {
        LOGGER.warn("Error validating system access token.", e);
        return null;
    }
    LOGGER.debug("Successfully retrieved system access token.");
    int status = tokenStorage.create(id, sourceId, accessToken, refreshToken, discoveryUrl);
    if (status != SC_OK) {
        LOGGER.debug("Error storing user token.");
    }
    return accessToken;
}
Also used : Form(javax.ws.rs.core.Form) InputStream(java.io.InputStream) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) IOException(java.io.IOException) WebClient(org.apache.cxf.jaxrs.client.WebClient) OidcValidationException(org.codice.ddf.security.oidc.validator.OidcValidationException) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken)

Aggregations

ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)4 URI (java.net.URI)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)3 AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)2 Scope (com.nimbusds.oauth2.sdk.Scope)2 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)2 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)2 Secret (com.nimbusds.oauth2.sdk.auth.Secret)2 Audience (com.nimbusds.oauth2.sdk.id.Audience)2 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)2 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)2 Instant (java.time.Instant)2 ArrayList (java.util.ArrayList)2 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)2 JWT (com.nimbusds.jwt.JWT)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 AccessTokenResponse (com.nimbusds.oauth2.sdk.AccessTokenResponse)1 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)1 AuthorizationCodeGrant (com.nimbusds.oauth2.sdk.AuthorizationCodeGrant)1