Search in sources :

Example 1 with JWTTokenIssuer

use of org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer in project identity-inbound-auth-oauth by wso2-extensions.

the class UserInfoResponseBaseTest method mockObjectsRelatedToTokenValidation.

protected void mockObjectsRelatedToTokenValidation() throws Exception {
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(OAuthServerConfiguration.getInstance().getOAuthTokenGenerator()).thenReturn(oAuthIssuer);
    when(OAuthServerConfiguration.getInstance().getSignatureAlgorithm()).thenReturn("SHA256withRSA");
    when(OAuth2Util.getAccessTokenIdentifier(any())).thenCallRealMethod();
    when(OAuth2Util.findAccessToken(anyString(), anyBoolean())).thenCallRealMethod();
    when(OAuth2Util.class, "getAccessTokenDOFromMatchingTokenIssuer", anyString(), anyMap(), anyBoolean()).thenCallRealMethod();
    AccessTokenDO accessTokenDO = new AccessTokenDO();
    accessTokenDO.setAccessToken(accessToken);
    when(OAuth2Util.getAccessTokenDOFromTokenIdentifier(anyString(), anyBoolean())).thenReturn(accessTokenDO);
    Map<String, OauthTokenIssuer> oauthTokenIssuerMap = new HashMap<>();
    oauthTokenIssuerMap.put(DEFAULT_TOKEN_TYPE, new OauthTokenIssuerImpl());
    oauthTokenIssuerMap.put(JWT_TOKEN_TYPE, new JWTTokenIssuer());
    when(OAuthServerConfiguration.getInstance().getOauthTokenIssuerMap()).thenReturn(oauthTokenIssuerMap);
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) JWTTokenIssuer(org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer) HashMap(java.util.HashMap) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) OauthTokenIssuerImpl(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuerImpl) Matchers.anyString(org.mockito.Matchers.anyString)

Example 2 with JWTTokenIssuer

use of org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer in project identity-inbound-auth-oauth by wso2-extensions.

the class ResponseTypeHandlerUtil method generateAccessToken.

/**
 * Generates access token for the given oauth issuer.
 *
 * @param oauthAuthzMsgCtx
 * @param cacheEnabled
 * @param oauthIssuerImpl
 * @return
 * @throws IdentityOAuth2Exception
 */
public static AccessTokenDO generateAccessToken(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled, OauthTokenIssuer oauthIssuerImpl) throws IdentityOAuth2Exception {
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
    String consumerKey = authorizationReqDTO.getConsumerKey();
    String authorizedUserId;
    try {
        authorizedUserId = authorizationReqDTO.getUser().getUserId();
    } catch (UserIdNotFoundException e) {
        throw new IdentityOAuth2Exception("Error occurred while retrieving the user id for user: " + authorizationReqDTO.getUser().getLoggableUserId());
    }
    synchronized ((consumerKey + ":" + authorizedUserId + ":" + scope).intern()) {
        AccessTokenDO existingTokenBean = getExistingToken(oauthAuthzMsgCtx, authorizedUserId, cacheEnabled);
        // Return a new access token in each request when JWTTokenIssuer is used.
        if (isNotRenewAccessTokenPerRequest(oauthIssuerImpl, oauthAuthzMsgCtx)) {
            if (existingTokenBean != null) {
                // Revoke token if RenewTokenPerRequest configuration is enabled.
                if (OAuthServerConfiguration.getInstance().isTokenRenewalPerRequestEnabled()) {
                    if (log.isDebugEnabled()) {
                        log.debug("RenewTokenPerRequest configuration active. " + "Proceeding to revoke any existing active tokens for client Id: " + consumerKey + ", user: " + authorizationReqDTO.getUser().getLoggableUserId() + " and scope: " + scope + ".");
                    }
                    revokeExistingToken(existingTokenBean.getConsumerKey(), existingTokenBean.getAccessToken());
                    // When revoking the token state will be set as REVOKED.
                    // existingTokenBean.setTokenState(TOKEN_STATE_REVOKED) can be used instead of 'null' but
                    // then the token state will again be updated to EXPIRED when a new token is generated.
                    existingTokenBean = null;
                }
                // Return existing token if it is still valid.
                if (isAccessTokenValid(existingTokenBean)) {
                    return existingTokenBean;
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("No active access token found for client Id: " + consumerKey + ", user: " + authorizationReqDTO.getUser().getLoggableUserId() + " and scope: " + scope + ". Therefore issuing new token");
            }
        }
        // Issue a new access token.
        return generateNewAccessToken(oauthAuthzMsgCtx, existingTokenBean, oauthIssuerImpl, authorizedUserId, cacheEnabled);
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 3 with JWTTokenIssuer

use of org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer in project identity-inbound-auth-oauth by wso2-extensions.

the class JWTTokenIssuerTest method testHandleCustomClaimsForAuthzMsgContext.

@Test
public void testHandleCustomClaimsForAuthzMsgContext() throws Exception {
    mockCustomClaimsCallbackHandler();
    when(oAuthServerConfiguration.getSignatureAlgorithm()).thenReturn(SHA256_WITH_RSA);
    JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder();
    OAuth2AuthorizeReqDTO reqDTO = new OAuth2AuthorizeReqDTO();
    OAuthAuthzReqMessageContext authzReqMessageContext = new OAuthAuthzReqMessageContext(reqDTO);
    JWTTokenIssuer jwtTokenIssuer = new JWTTokenIssuer();
    JWTClaimsSet jwtClaimsSet = jwtTokenIssuer.handleCustomClaims(jwtClaimsSetBuilder, authzReqMessageContext);
    assertNotNull(jwtClaimsSet);
    assertEquals(jwtClaimsSet.getClaims().size(), 1);
    assertNotNull(jwtClaimsSet.getClaim("AUTHZ_CONTEXT_CLAIM"));
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OAuthAuthzReqMessageContext(org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 4 with JWTTokenIssuer

use of org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer in project identity-inbound-auth-oauth by wso2-extensions.

the class JWTTokenIssuerTest method testCreateJWTClaimSet.

@Test(dataProvider = "createJWTClaimSetDataProvider")
public void testCreateJWTClaimSet(Object authzReqMessageContext, Object tokenReqMessageContext, String sub, long expectedExpiry) throws Exception {
    OAuthAppDO appDO = spy(new OAuthAppDO());
    mockGrantHandlers();
    mockCustomClaimsCallbackHandler();
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getAppInformationByClientId(anyString())).thenReturn(appDO);
    when(OAuth2Util.getIDTokenIssuer()).thenReturn(ID_TOKEN_ISSUER);
    when(OAuth2Util.getIdTokenIssuer(anyString())).thenReturn(ID_TOKEN_ISSUER);
    when(OAuth2Util.getOIDCAudience(anyString(), anyObject())).thenReturn(Collections.singletonList(DUMMY_CLIENT_ID));
    when(oAuthServerConfiguration.getSignatureAlgorithm()).thenReturn(SHA256_WITH_HMAC);
    when(oAuthServerConfiguration.getUserAccessTokenValidityPeriodInSeconds()).thenReturn(DEFAULT_USER_ACCESS_TOKEN_EXPIRY_TIME);
    when(oAuthServerConfiguration.getApplicationAccessTokenValidityPeriodInSeconds()).thenReturn(DEFAULT_APPLICATION_ACCESS_TOKEN_EXPIRY_TIME);
    JWTTokenIssuer jwtTokenIssuer = PowerMockito.spy(new JWTTokenIssuer());
    PowerMockito.doReturn(sub).when(jwtTokenIssuer, "getSubjectClaim", anyString(), anyString(), any());
    JWTClaimsSet jwtClaimSet = jwtTokenIssuer.createJWTClaimSet((OAuthAuthzReqMessageContext) authzReqMessageContext, (OAuthTokenReqMessageContext) tokenReqMessageContext, DUMMY_CLIENT_ID);
    assertNotNull(jwtClaimSet);
    assertEquals(jwtClaimSet.getIssuer(), ID_TOKEN_ISSUER);
    assertEquals(jwtClaimSet.getSubject(), sub);
    assertEquals(jwtClaimSet.getClaim("azp"), DUMMY_CLIENT_ID);
    assertEquals(jwtClaimSet.getClaim(CLAIM_CLIENT_ID), DUMMY_CLIENT_ID);
    // Assert whether client id is among audiences
    assertNotNull(jwtClaimSet.getAudience());
    assertTrue(jwtClaimSet.getAudience().contains(DUMMY_CLIENT_ID));
    // Validate expiry
    assertNotNull(jwtClaimSet.getIssueTime());
    assertNotNull(jwtClaimSet.getExpirationTime());
    if (tokenReqMessageContext != null && ((OAuthTokenReqMessageContext) tokenReqMessageContext).getProperty(EXPIRY_TIME_JWT) != null) {
        assertTrue(jwtClaimSet.getExpirationTime().compareTo((Date) ((OAuthTokenReqMessageContext) tokenReqMessageContext).getProperty(EXPIRY_TIME_JWT)) >= 0);
    } else {
        assertEquals(new Duration(jwtClaimSet.getIssueTime().getTime(), jwtClaimSet.getExpirationTime().getTime()).getMillis(), expectedExpiry);
    }
}
Also used : OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Duration(org.joda.time.Duration) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 5 with JWTTokenIssuer

use of org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer in project identity-inbound-auth-oauth by wso2-extensions.

the class JWTTokenIssuerTest method testCreateJWTClaimSetForInvalidClient.

@Test(expectedExceptions = IdentityOAuth2Exception.class)
public void testCreateJWTClaimSetForInvalidClient() throws Exception {
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getAppInformationByClientId(anyString())).thenThrow(new InvalidOAuthClientException("INVALID_CLIENT"));
    when(oAuthServerConfiguration.getSignatureAlgorithm()).thenReturn(SHA256_WITH_HMAC);
    JWTTokenIssuer jwtTokenIssuer = new JWTTokenIssuer();
    jwtTokenIssuer.createJWTClaimSet(null, null, null);
}
Also used : InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Aggregations

PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 Test (org.testng.annotations.Test)10 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)10 Matchers.anyString (org.mockito.Matchers.anyString)6 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)5 OAuth2AuthorizeReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO)5 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)4 OauthTokenIssuer (org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer)4 HashMap (java.util.HashMap)3 InvalidOAuthClientException (org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)3 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)3 OAuthAuthzReqMessageContext (org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext)3 OAuth2AccessTokenReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)3 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)3 JWTTokenIssuer (org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer)3 PlainJWT (com.nimbusds.jwt.PlainJWT)2 UserIdNotFoundException (org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)2 OauthTokenIssuerImpl (org.wso2.carbon.identity.oauth2.token.OauthTokenIssuerImpl)2 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 JWSSigner (com.nimbusds.jose.JWSSigner)1