Search in sources :

Example 16 with AccessToken

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

the class CustomOidcProfileCreator method create.

@Override
public Optional<UserProfile> create(OidcCredentials credentials, WebContext context) {
    init();
    final OidcProfile profile = (OidcProfile) getProfileDefinition().newProfile();
    final AccessToken accessToken = credentials.getAccessToken();
    if (accessToken != null && !accessToken.getValue().isEmpty()) {
        profile.setAccessToken(accessToken);
    }
    final RefreshToken refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
        LOGGER.debug("Found refresh token");
    }
    final JWT idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());
    try {
        JWTClaimsSet claimsSet = idToken.getJWTClaimsSet();
        assertNotNull("claimsSet", claimsSet);
        profile.setId(ProfileHelper.sanitizeIdentifier(profile, claimsSet.getSubject()));
        for (final Map.Entry<String, Object> entry : claimsSet.getClaims().entrySet()) {
            if (!JwtClaims.SUBJECT.equals(entry.getKey()) && profile.getAttribute(entry.getKey()) == null) {
                getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, entry.getKey(), entry.getValue());
            }
        }
        profile.setTokenExpirationAdvance(configuration.getTokenExpirationAdvance());
        return Optional.of(profile);
    } catch (final java.text.ParseException e) {
        throw new AuthenticationException(e);
    }
}
Also used : RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) AuthenticationException(org.apache.shiro.authc.AuthenticationException) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) JWT(com.nimbusds.jwt.JWT) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OidcProfile(org.pac4j.oidc.profile.OidcProfile) WebContext(org.pac4j.core.context.WebContext) Map(java.util.Map)

Example 17 with AccessToken

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

the class OidcRealmTest method setup.

@Before
public void setup() throws Exception {
    realm = new OidcRealm();
    // Generate the RSA key pair
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    KeyPair keyPair = gen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
    invalidAlgorithm = Algorithm.HMAC256("WRONG");
    JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
    String jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
    OIDCProviderMetadata oidcProviderMetadata = mock(OIDCProviderMetadata.class);
    when(oidcProviderMetadata.getIDTokenJWSAlgs()).thenReturn(ImmutableList.of(JWSAlgorithm.RS256));
    when(oidcProviderMetadata.getIssuer()).thenReturn(new Issuer("http://localhost:8080/auth/realms/master"));
    when(oidcProviderMetadata.getJWKSetURI()).thenReturn(new URI("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs"));
    ResourceRetriever resourceRetriever = mock(ResourceRetriever.class);
    Resource resource = new Resource(jwk, APPLICATION_JSON);
    when(resourceRetriever.retrieveResource(any())).thenReturn(resource);
    OidcConfiguration configuration = mock(OidcConfiguration.class);
    when(configuration.getClientId()).thenReturn("ddf-client");
    when(configuration.getSecret()).thenReturn("secret");
    when(configuration.isUseNonce()).thenReturn(true);
    when(configuration.getResponseType()).thenReturn("code");
    when(configuration.findProviderMetadata()).thenReturn(oidcProviderMetadata);
    when(configuration.findResourceRetriever()).thenReturn(resourceRetriever);
    OidcHandlerConfiguration handlerConfiguration = mock(OidcHandlerConfiguration.class);
    when(handlerConfiguration.getOidcConfiguration()).thenReturn(configuration);
    when(handlerConfiguration.getOidcClient(any())).thenReturn(mock(OidcClient.class));
    realm.setOidcHandlerConfiguration(handlerConfiguration);
    realm.setUsernameAttributeList(Collections.singletonList("preferred_username"));
    JWT jwt = mock(JWT.class);
    AccessToken accessToken = new BearerAccessToken(getAccessTokenBuilder().sign(validAlgorithm));
    AuthorizationCode authorizationCode = new AuthorizationCode();
    WebContext webContext = getWebContext();
    oidcCredentials = mock(OidcCredentials.class);
    when(oidcCredentials.getIdToken()).thenReturn(jwt);
    when(oidcCredentials.getIdToken()).thenReturn(jwt);
    when(oidcCredentials.getAccessToken()).thenReturn(accessToken);
    when(oidcCredentials.getCode()).thenReturn(authorizationCode);
    authenticationToken = mock(OidcAuthenticationToken.class);
    when(authenticationToken.getCredentials()).thenReturn(oidcCredentials);
    when(authenticationToken.getContext()).thenReturn(webContext);
}
Also used : OidcHandlerConfiguration(org.codice.ddf.security.handler.api.OidcHandlerConfiguration) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) KeyPair(java.security.KeyPair) WebContext(org.pac4j.core.context.WebContext) Issuer(com.nimbusds.oauth2.sdk.id.Issuer) ResourceRetriever(com.nimbusds.jose.util.ResourceRetriever) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) Resource(com.nimbusds.jose.util.Resource) OidcAuthenticationToken(org.codice.ddf.security.handler.OidcAuthenticationToken) KeyPairGenerator(java.security.KeyPairGenerator) URI(java.net.URI) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) RSAPublicKey(java.security.interfaces.RSAPublicKey) OidcClient(org.pac4j.oidc.client.OidcClient) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) OIDCProviderMetadata(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWK(com.nimbusds.jose.jwk.JWK) Before(org.junit.Before)

Example 18 with AccessToken

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

the class CustomOAuthCredentialsExtractor method getOauthCredentialsAsOidcCredentials.

public OidcCredentials getOauthCredentialsAsOidcCredentials(final WebContext context) {
    OidcCredentials credentials = new OidcCredentials();
    try {
        final String codeParam = context.getRequestParameter(OAuth20Configuration.OAUTH_CODE).orElse(null);
        if (codeParam != null) {
            credentials.setCode(new AuthorizationCode(URLDecoder.decode(codeParam, StandardCharsets.UTF_8.name())));
        } else {
            LOGGER.debug("No OAuth2 code found on request.");
        }
        final String accessTokenParam = context.getRequestParameter("access_token").orElse(null);
        final String accessTokenHeader = getAccessTokenFromHeader(context);
        final String accessToken = accessTokenParam != null ? accessTokenParam : accessTokenHeader;
        if (isNotBlank(accessToken)) {
            credentials.setAccessToken(new BearerAccessToken(URLDecoder.decode(accessToken, StandardCharsets.UTF_8.name())));
        } else {
            LOGGER.debug("No OAuth2 access token found on request.");
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.debug("Error decoding the authorization code/access token from url parameters.", e);
    }
    return credentials;
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken)

Example 19 with AccessToken

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

the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.

@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    // Build the authorization code grant request for the token endpoint
    AuthorizationCode authorizationCode = new AuthorizationCode(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationResponse().getCode());
    URI redirectUri = toURI(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationRequest().getRedirectUri());
    AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(authorizationCode, redirectUri);
    URI tokenUri = toURI(clientRegistration.getProviderDetails().getTokenUri());
    // Set the credentials to authenticate the client at the token endpoint
    ClientID clientId = new ClientID(clientRegistration.getClientId());
    Secret clientSecret = new Secret(clientRegistration.getClientSecret());
    boolean isPost = ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod()) || ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod());
    ClientAuthentication clientAuthentication = isPost ? new ClientSecretPost(clientId, clientSecret) : new ClientSecretBasic(clientId, clientSecret);
    com.nimbusds.oauth2.sdk.TokenResponse tokenResponse = getTokenResponse(authorizationCodeGrant, tokenUri, clientAuthentication);
    if (!tokenResponse.indicatesSuccess()) {
        TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
        ErrorObject errorObject = tokenErrorResponse.getErrorObject();
        throw new OAuth2AuthorizationException(getOAuthError(errorObject));
    }
    AccessTokenResponse accessTokenResponse = (AccessTokenResponse) tokenResponse;
    String accessToken = accessTokenResponse.getTokens().getAccessToken().getValue();
    OAuth2AccessToken.TokenType accessTokenType = null;
    if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessTokenResponse.getTokens().getAccessToken().getType().getValue())) {
        accessTokenType = OAuth2AccessToken.TokenType.BEARER;
    }
    long expiresIn = accessTokenResponse.getTokens().getAccessToken().getLifetime();
    // As per spec, in section 5.1 Successful Access Token Response
    // https://tools.ietf.org/html/rfc6749#section-5.1
    // If AccessTokenResponse.scope is empty, then default to the scope
    // originally requested by the client in the Authorization Request
    Set<String> scopes = getScopes(authorizationGrantRequest, accessTokenResponse);
    String refreshToken = null;
    if (accessTokenResponse.getTokens().getRefreshToken() != null) {
        refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
    }
    Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
    // @formatter:off
    return OAuth2AccessTokenResponse.withToken(accessToken).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).refreshToken(refreshToken).additionalParameters(additionalParameters).build();
// @formatter:on
}
Also used : URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) LinkedHashMap(java.util.LinkedHashMap) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) ClientSecretPost(com.nimbusds.oauth2.sdk.auth.ClientSecretPost) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Secret(com.nimbusds.oauth2.sdk.auth.Secret) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject)

Example 20 with AccessToken

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

the class OAuth2AccessTokenResponseBodyExtractor method oauth2AccessTokenResponse.

private static OAuth2AccessTokenResponse oauth2AccessTokenResponse(AccessTokenResponse accessTokenResponse) {
    AccessToken accessToken = accessTokenResponse.getTokens().getAccessToken();
    OAuth2AccessToken.TokenType accessTokenType = null;
    if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessToken.getType().getValue())) {
        accessTokenType = OAuth2AccessToken.TokenType.BEARER;
    }
    long expiresIn = accessToken.getLifetime();
    Set<String> scopes = (accessToken.getScope() != null) ? new LinkedHashSet<>(accessToken.getScope().toStringList()) : Collections.emptySet();
    String refreshToken = null;
    if (accessTokenResponse.getTokens().getRefreshToken() != null) {
        refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
    }
    Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
    // @formatter:off
    return OAuth2AccessTokenResponse.withToken(accessToken.getValue()).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).refreshToken(refreshToken).additionalParameters(additionalParameters).build();
// @formatter:on
}
Also used : AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) JSONObject(net.minidev.json.JSONObject) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)12 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)12 JWT (com.nimbusds.jwt.JWT)10 PlainJWT (com.nimbusds.jwt.PlainJWT)5 SignedJWT (com.nimbusds.jwt.SignedJWT)5 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)5 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)5 OidcValidationException (org.codice.ddf.security.oidc.validator.OidcValidationException)5 Test (org.junit.Test)5 ParseException (com.nimbusds.oauth2.sdk.ParseException)4 URI (java.net.URI)4 IOException (java.io.IOException)3 WebClient (org.apache.cxf.jaxrs.client.WebClient)3 TechnicalException (org.pac4j.core.exception.TechnicalException)3 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 AccessTokenResponse (com.nimbusds.oauth2.sdk.AccessTokenResponse)2 AuthorizationCodeGrant (com.nimbusds.oauth2.sdk.AuthorizationCodeGrant)2 AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)2 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)2 TokenErrorResponse (com.nimbusds.oauth2.sdk.TokenErrorResponse)2