Search in sources :

Example 36 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project chipster-web-server by chipster.

the class OidcProvidersImpl method createValidator.

public IDTokenValidator createValidator(String issuerString, String clientIdString, URI jwkSetURI, JWKSet jwkSet) throws URISyntaxException, IOException {
    if (jwkSetURI == null && jwkSet == null) {
        throw new IllegalStateException("OpenID Connect jwk_uri is null, cannot verify login tokens without it");
    } else {
        logger.info("download OpenID Connect keys from " + jwkSetURI);
    }
    Issuer issuer = new Issuer(issuerString);
    ClientID clientID = new ClientID(clientIdString);
    JWSAlgorithm algorithm = JWSAlgorithm.RS256;
    // Create validator for signed ID tokens
    if (jwkSetURI != null) {
        // it should download the token signing keys and keep them updated (e.g. daily for google)
        return new IDTokenValidator(issuer, clientID, algorithm, jwkSetURI.toURL());
    } else {
        // give keys directly in tests
        return new IDTokenValidator(issuer, clientID, algorithm, jwkSet);
    }
}
Also used : Issuer(com.nimbusds.oauth2.sdk.id.Issuer) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) IDTokenValidator(com.nimbusds.openid.connect.sdk.validators.IDTokenValidator)

Example 37 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project di-ipv-cri-uk-passport-back by alphagov.

the class AccessTokenServiceTest method shouldPersistAccessToken.

@Test
void shouldPersistAccessToken() {
    String testResourceId = UUID.randomUUID().toString();
    AccessToken accessToken = new BearerAccessToken();
    AccessTokenResponse accessTokenResponse = new AccessTokenResponse(new Tokens(accessToken, null));
    ArgumentCaptor<AccessTokenItem> accessTokenItemArgCaptor = ArgumentCaptor.forClass(AccessTokenItem.class);
    accessTokenService.persistAccessToken(accessTokenResponse, testResourceId);
    verify(mockDataStore).create(accessTokenItemArgCaptor.capture());
    AccessTokenItem capturedAccessTokenItem = accessTokenItemArgCaptor.getValue();
    assertNotNull(capturedAccessTokenItem);
    assertEquals(testResourceId, capturedAccessTokenItem.getResourceId());
    assertEquals(accessTokenResponse.getTokens().getBearerAccessToken().toAuthorizationHeader(), capturedAccessTokenItem.getAccessToken());
}
Also used : AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) AccessTokenItem(uk.gov.di.ipv.cri.passport.library.persistence.item.AccessTokenItem) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) Tokens(com.nimbusds.oauth2.sdk.token.Tokens) Test(org.junit.jupiter.api.Test)

Example 38 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project Application-Gateway by gianlucafrei.

the class OidcDriver method loadTokens.

@Override
protected Tokens loadTokens(ClientAuthentication clientAuth, URI tokenEndpoint, AuthorizationGrant codeGrant) throws AuthenticationException {
    TokenRequest request = new TokenRequest(tokenEndpoint, clientAuth, codeGrant);
    TokenResponse tokenResponse;
    HTTPResponse httpResponse;
    try {
        httpResponse = request.toHTTPRequest().send();
        tokenResponse = OIDCTokenResponseParser.parse(httpResponse);
    } catch (IOException | ParseException ex) {
        log.warn("Load token failed: {}", ex.getMessage());
        throw new SystemException("Could not load tokens", ex);
    }
    if (!tokenResponse.indicatesSuccess()) {
        // We got an error response...
        TokenErrorResponse errorResponse = tokenResponse.toErrorResponse();
        if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND.value()) {
            log.warn("404 response from token endpoint");
        }
        String message = errorResponse.getErrorObject().getDescription();
        throw new AuthenticationException(message);
    }
    OIDCTokenResponse successResponse = (OIDCTokenResponse) tokenResponse.toSuccessResponse();
    OIDCTokens oidcTokens = successResponse.getOIDCTokens();
    return oidcTokens;
}
Also used : OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) SystemException(org.owasp.oag.exception.SystemException) AuthenticationException(org.owasp.oag.exception.AuthenticationException) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) IOException(java.io.IOException)

Example 39 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project asgardeo-java-oidc-sdk by asgardeo.

the class IDTokenValidator method getIDTokenValidator.

private com.nimbusds.openid.connect.sdk.validators.IDTokenValidator getIDTokenValidator(JWSAlgorithm jwsAlgorithm) throws SSOAgentServerException {
    Issuer issuer = oidcAgentConfig.getIssuer();
    URI jwkSetURI = oidcAgentConfig.getJwksEndpoint();
    ClientID clientID = oidcAgentConfig.getConsumerKey();
    Secret clientSecret = oidcAgentConfig.getConsumerSecret();
    int httpConnectTimeout = oidcAgentConfig.getHttpConnectTimeout();
    int httpReadTimeout = oidcAgentConfig.getHttpReadTimeout();
    int httpSizeLimit = oidcAgentConfig.getHttpSizeLimit();
    com.nimbusds.openid.connect.sdk.validators.IDTokenValidator validator;
    ResourceRetriever resourceRetriever = new DefaultResourceRetriever(httpConnectTimeout, httpReadTimeout, httpSizeLimit);
    // Creates a new validator for RSA, EC or ED protected ID tokens.
    if (JWSAlgorithm.Family.RSA.contains(jwsAlgorithm) || JWSAlgorithm.Family.EC.contains(jwsAlgorithm) || JWSAlgorithm.Family.ED.contains(jwsAlgorithm)) {
        try {
            validator = new com.nimbusds.openid.connect.sdk.validators.IDTokenValidator(issuer, clientID, jwsAlgorithm, jwkSetURI.toURL(), resourceRetriever);
        } catch (Exception e) {
            throw new SSOAgentServerException(e.getMessage(), e.getCause());
        }
    // Creates a new validator for HMAC protected ID tokens.
    } else if (JWSAlgorithm.Family.HMAC_SHA.contains(jwsAlgorithm)) {
        validator = new com.nimbusds.openid.connect.sdk.validators.IDTokenValidator(issuer, clientID, jwsAlgorithm, clientSecret);
    } else {
        throw new SSOAgentServerException(String.format("Unsupported algorithm: %s.", jwsAlgorithm.getName()));
    }
    return validator;
}
Also used : Issuer(com.nimbusds.oauth2.sdk.id.Issuer) DefaultResourceRetriever(com.nimbusds.jose.util.DefaultResourceRetriever) ResourceRetriever(com.nimbusds.jose.util.ResourceRetriever) SSOAgentServerException(io.asgardeo.java.oidc.sdk.exception.SSOAgentServerException) URI(java.net.URI) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) SSOAgentServerException(io.asgardeo.java.oidc.sdk.exception.SSOAgentServerException) Secret(com.nimbusds.oauth2.sdk.auth.Secret) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) DefaultResourceRetriever(com.nimbusds.jose.util.DefaultResourceRetriever)

Example 40 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project asgardeo-java-oidc-sdk by asgardeo.

the class DefaultOIDCManagerTest method testHandleOIDCCallback.

@Test
public void testHandleOIDCCallback() throws Exception {
    AccessToken accessToken = new AccessToken(AccessTokenType.BEARER, "sampleAccessToken") {

        @Override
        public String toAuthorizationHeader() {
            return null;
        }
    };
    RefreshToken refreshToken = new RefreshToken("sampleRefreshToken");
    Tokens tokens = new Tokens(accessToken, refreshToken);
    Map<String, Object> customParameters = new HashMap<>();
    String parsedIdToken = "eyJ4NXQiOiJNell4TW1Ga09HWXdNV0kwWldObU5EY3hOR1l3WW1NNFpUQTNNV0kyTkRBelpHUXpOR00wWkdS" + "bE5qSmtPREZrWkRSaU9URmtNV0ZoTXpVMlpHVmxOZyIsImtpZCI6Ik16WXhNbUZrT0dZd01XSTBaV05tTkRjeE5HWXdZbU00WlR" + "BM01XSTJOREF6WkdRek5HTTBaR1JsTmpKa09ERmtaRFJpT1RGa01XRmhNelUyWkdWbE5nX1JTMjU2IiwiYWxnIjoiUlMyNTYifQ" + ".eyJhdF9oYXNoIjoiSEJOUlJOeTlaVy1CMXF3dFdLRkJEZyIsInN1YiI6ImFsZXhAY2FyYm9uLnN1cGVyIiwiY291bnRyeSI6Ik" + "xLIiwiYW1yIjpbIkJhc2ljQXV0aGVudGljYXRvciJdLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0NDNcL29hdXRoMlwvd" + "G9rZW4iLCJzaWQiOiJkYmJhNGNkMC0wNWRjLTQxN2QtYTcwYy1lOGNmYmNiNDlhMDMiLCJhdWQiOiJLRTRPWWVZX2dmWXd6UWJK" + "YTl0R2hqMWhaSk1hIiwiY19oYXNoIjoiWXhUQ25rZ2UtOG9PSWZ3RUpmS2tfdyIsIm5iZiI6MTYwMjIyNjA5MSwiYXpwIjoiS0U" + "0T1llWV9nZll3elFiSmE5dEdoajFoWkpNYSIsImV4cCI6MTYwMjIyOTY5MSwiaWF0IjoxNjAyMjI2MDkxLCJlbWFpbCI6ImFsZX" + "hAd3NvMi5jb20ifQ.pHwsQqn64tif2J6iYcRShK_85WO3aBuL7Pz8urcHErXjyh6zvroOqSWD9KbSxJPocyoIshdqWdAEhdURKL" + "tXiw-l73HlvnX4qJKYT71VKXMTC26Z8dlk4TgytXiskmj8OpAcem3czuEWTrTLVbYzIw71p9kx-5Xxb9WNvzBg1YpwGC8MK3dkW" + "TfmUsu6oncIvHyv-gbX3kJebgMserp";
    JWT idToken = JWTParser.parse(parsedIdToken);
    customParameters.put(SSOAgentConstants.ID_TOKEN, parsedIdToken);
    when(requestResolver.isError()).thenReturn(false);
    when(requestResolver.isAuthorizationCodeResponse()).thenReturn(true);
    MockedStatic<AuthorizationResponse> mockedAuthorizationResponse = mockStatic(AuthorizationResponse.class);
    MockedStatic<ServletUtils> mockedServletUtils = mockStatic(ServletUtils.class);
    MockedStatic<TokenResponse> mockedTokenResponse = mockStatic(TokenResponse.class);
    HTTPRequest httpRequest = mock(HTTPRequest.class);
    AuthorizationResponse authorizationResponse = mock(AuthorizationResponse.class);
    AuthorizationSuccessResponse successResponse = mock(AuthorizationSuccessResponse.class);
    AuthorizationCode authorizationCode = mock(AuthorizationCode.class);
    TokenResponse tokenResponse = mock(TokenResponse.class);
    AccessTokenResponse accessTokenResponse = mock(AccessTokenResponse.class);
    when(ServletUtils.createHTTPRequest(request)).thenReturn(httpRequest);
    when(AuthorizationResponse.parse(httpRequest)).thenReturn(authorizationResponse);
    when(authorizationResponse.indicatesSuccess()).thenReturn(true);
    when(authorizationResponse.toSuccessResponse()).thenReturn(successResponse);
    when(successResponse.getAuthorizationCode()).thenReturn(authorizationCode);
    when(TokenResponse.parse((HTTPResponse) any())).thenReturn(tokenResponse);
    when(tokenResponse.indicatesSuccess()).thenReturn(true);
    when(tokenResponse.toSuccessResponse()).thenReturn(accessTokenResponse);
    when(accessTokenResponse.getTokens()).thenReturn(tokens);
    when(accessTokenResponse.getCustomParameters()).thenReturn(customParameters);
    HttpSession session = mock(HttpSession.class);
    when(request.getSession(false)).thenReturn(session);
    when(session.getAttribute(SSOAgentConstants.NONCE)).thenReturn(new Nonce());
    RequestContext requestContext = new RequestContext(new State("state"), new Nonce());
    OIDCManager oidcManager = new DefaultOIDCManager(oidcAgentConfig);
    SessionContext sessionContext = oidcManager.handleOIDCCallback(request, response, requestContext);
    assertEquals(sessionContext.getAccessToken(), accessToken.toJSONString());
    assertEquals(sessionContext.getRefreshToken(), refreshToken.getValue());
    assertEquals(sessionContext.getIdToken(), parsedIdToken);
    assertEquals(sessionContext.getUser().getSubject(), "alex@carbon.super");
    mockedAuthorizationResponse.close();
    mockedServletUtils.close();
    mockedTokenResponse.close();
}
Also used : HashMap(java.util.HashMap) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) AuthorizationSuccessResponse(com.nimbusds.oauth2.sdk.AuthorizationSuccessResponse) RequestContext(io.asgardeo.java.oidc.sdk.bean.RequestContext) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) Tokens(com.nimbusds.oauth2.sdk.token.Tokens) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) JWT(com.nimbusds.jwt.JWT) HttpSession(javax.servlet.http.HttpSession) AuthorizationResponse(com.nimbusds.oauth2.sdk.AuthorizationResponse) Nonce(com.nimbusds.openid.connect.sdk.Nonce) ServletUtils(com.nimbusds.oauth2.sdk.http.ServletUtils) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) State(com.nimbusds.oauth2.sdk.id.State) SessionContext(io.asgardeo.java.oidc.sdk.bean.SessionContext) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

URI (java.net.URI)18 OIDCTokens (com.nimbusds.openid.connect.sdk.token.OIDCTokens)17 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)15 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)15 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)15 TokenResponse (com.nimbusds.oauth2.sdk.TokenResponse)14 TokenRequest (com.nimbusds.oauth2.sdk.TokenRequest)13 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)13 Secret (com.nimbusds.oauth2.sdk.auth.Secret)12 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)12 Tokens (com.nimbusds.oauth2.sdk.token.Tokens)11 TokenErrorResponse (com.nimbusds.oauth2.sdk.TokenErrorResponse)10 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)10 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)10 IOException (java.io.IOException)10 AccessTokenResponse (com.nimbusds.oauth2.sdk.AccessTokenResponse)8 Scope (com.nimbusds.oauth2.sdk.Scope)8 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)8 HashMap (java.util.HashMap)8 Test (org.testng.annotations.Test)8