Search in sources :

Example 1 with OAuthTokenReqMessageContext

use of org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext in project carbon-apimgt by wso2.

the class SystemScopesIssuer method configureForJWTGrant.

protected void configureForJWTGrant(OAuthTokenReqMessageContext tokReqMsgCtx) {
    SignedJWT signedJWT = null;
    JWTClaimsSet claimsSet = null;
    String[] roles = null;
    try {
        signedJWT = getSignedJWT(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
        log.error("Couldn't retrieve signed JWT", e);
    }
    if (signedJWT != null) {
        claimsSet = getClaimSet(signedJWT);
    }
    String jwtIssuer = claimsSet != null ? claimsSet.getIssuer() : null;
    String tenantDomain = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain();
    try {
        identityProvider = IdentityProviderManager.getInstance().getIdPByName(jwtIssuer, tenantDomain);
        if (identityProvider != null) {
            if (StringUtils.equalsIgnoreCase(identityProvider.getIdentityProviderName(), "default")) {
                identityProvider = this.getResidentIDPForIssuer(tenantDomain, jwtIssuer);
                if (identityProvider == null) {
                    log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
                }
            }
        } else {
            log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
        }
    } catch (IdentityProviderManagementException | IdentityOAuth2Exception e) {
        log.error("Couldn't initiate identity provider instance", e);
    }
    try {
        roles = claimsSet != null ? claimsSet.getStringArrayClaim(identityProvider.getClaimConfig().getRoleClaimURI()) : null;
    } catch (ParseException e) {
        log.error("Couldn't retrieve roles:", e);
    }
    List<String> updatedRoles = new ArrayList<>();
    if (roles != null) {
        for (String role : roles) {
            String updatedRoleClaimValue = getUpdatedRoleClaimValue(identityProvider, role);
            if (updatedRoleClaimValue != null) {
                updatedRoles.add(updatedRoleClaimValue);
            } else {
                updatedRoles.add(role);
            }
        }
    }
    AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
    Map<ClaimMapping, String> userAttributes = user.getUserAttributes();
    String roleClaim = identityProvider.getClaimConfig().getRoleClaimURI();
    if (roleClaim != null) {
        userAttributes.put(ClaimMapping.build(roleClaim, roleClaim, null, false), updatedRoles.toString().replace(" ", ""));
        tokReqMsgCtx.addProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM, roleClaim);
    }
    user.setUserAttributes(userAttributes);
    tokReqMsgCtx.setAuthorizedUser(user);
}
Also used : SignedJWT(com.nimbusds.jwt.SignedJWT) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 2 with OAuthTokenReqMessageContext

use of org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext in project carbon-apimgt by wso2.

the class SystemScopesIssuer method getSignedJWT.

/**
 * Method to parse the assertion and retrieve the signed JWT
 *
 * @param tokReqMsgCtx request
 * @return SignedJWT object
 * @throws IdentityOAuth2Exception exception thrown due to a parsing error
 */
private SignedJWT getSignedJWT(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    RequestParameter[] params = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();
    String assertion = null;
    SignedJWT signedJWT;
    for (RequestParameter param : params) {
        if (param.getKey().equals(APIConstants.SystemScopeConstants.OAUTH_JWT_ASSERTION)) {
            assertion = param.getValue()[0];
            break;
        }
    }
    if (StringUtils.isEmpty(assertion)) {
        String errorMessage = "Error while retrieving assertion";
        throw new IdentityOAuth2Exception(errorMessage);
    }
    try {
        signedJWT = SignedJWT.parse(assertion);
        if (log.isDebugEnabled()) {
            log.debug(signedJWT);
        }
    } catch (ParseException e) {
        String errorMessage = "Error while parsing the JWT.";
        throw new IdentityOAuth2Exception(errorMessage, e);
    }
    return signedJWT;
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) RequestParameter(org.wso2.carbon.identity.oauth2.model.RequestParameter) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException)

Example 3 with OAuthTokenReqMessageContext

use of org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext in project carbon-apimgt by wso2.

the class SystemScopesIssuer method getScopes.

/**
 * This method is used to retrieve the authorized scopes with respect to a token.
 *
 * @param tokReqMsgCtx token message context
 * @return authorized scopes list
 */
public List<String> getScopes(OAuthTokenReqMessageContext tokReqMsgCtx) {
    List<String> authorizedScopes = null;
    List<String> requestedScopes = new ArrayList<>(Arrays.asList(tokReqMsgCtx.getScope()));
    String clientId = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
    AuthenticatedUser authenticatedUser = tokReqMsgCtx.getAuthorizedUser();
    Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
    if (appScopes != null) {
        // If no scopes can be found in the context of the application
        if (isAppScopesEmpty(appScopes, clientId)) {
            return getAllowedScopes(requestedScopes);
        }
        String grantType = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType();
        String[] userRoles = null;
        // If GrantType is SAML20_BEARER and CHECK_ROLES_FROM_SAML_ASSERTION is true, or if GrantType is
        // JWT_BEARER and retrieveRolesFromUserStoreForScopeValidation system property is true,
        // use user roles from assertion or jwt otherwise use roles from userstore.
        String isSAML2Enabled = System.getProperty(APIConstants.SystemScopeConstants.CHECK_ROLES_FROM_SAML_ASSERTION);
        String isRetrieveRolesFromUserStoreForScopeValidation = System.getProperty(APIConstants.SystemScopeConstants.RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION);
        if (GrantType.SAML20_BEARER.toString().equals(grantType) && Boolean.parseBoolean(isSAML2Enabled)) {
            authenticatedUser.setUserStoreDomain("FEDERATED");
            tokReqMsgCtx.setAuthorizedUser(authenticatedUser);
            Assertion assertion = (Assertion) tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.SAML2_ASSERTION);
            userRoles = getRolesFromAssertion(assertion);
        } else if (APIConstants.SystemScopeConstants.OAUTH_JWT_BEARER_GRANT_TYPE.equals(grantType) && !(Boolean.parseBoolean(isRetrieveRolesFromUserStoreForScopeValidation))) {
            configureForJWTGrant(tokReqMsgCtx);
            Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes();
            if (tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM) != null) {
                userRoles = getRolesFromUserAttribute(userAttributes, tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM).toString());
            }
        } else {
            userRoles = getUserRoles(authenticatedUser);
        }
        authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
    }
    return authorizedScopes;
}
Also used : Assertion(org.opensaml.saml.saml2.core.Assertion) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 4 with OAuthTokenReqMessageContext

use of org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext in project carbon-apimgt by wso2.

the class SystemScopeIssuerImplTest method init.

@Before
public void init() throws IdentityOAuth2Exception {
    systemScopesIssuer = Mockito.mock(SystemScopesIssuer.class);
    oAuth2AuthorizeReqDTO = new OAuth2AuthorizeReqDTO();
    String[] scopes = { "test", "test1" };
    restAPIScopes.put("test", "test");
    authenticatedUser = Mockito.mock(AuthenticatedUser.class);
    Mockito.when(systemScopesIssuer.getAppScopes(Mockito.anyString(), Mockito.anyObject(), Mockito.anyList())).thenReturn(restAPIScopes);
    Mockito.when(systemScopesIssuer.validateScope((OAuthAuthzReqMessageContext) Mockito.anyObject())).thenReturn(true);
    oAuth2AuthorizeReqDTO.setScopes(scopes);
    oAuth2AuthorizeReqDTO.setUser(authenticatedUser);
    oAuthAuthzReqMessageContext = new OAuthAuthzReqMessageContext(oAuth2AuthorizeReqDTO);
    oAuth2AccessTokenReqDTO = new OAuth2AccessTokenReqDTO();
    oAuth2AccessTokenReqDTO.setScope(scopes);
    oAuthTokenReqMessageContext = new OAuthTokenReqMessageContext(oAuth2AccessTokenReqDTO);
    Mockito.when(systemScopesIssuer.validateScope((OAuthTokenReqMessageContext) Mockito.anyObject())).thenReturn(true);
    oAuth2TokenValidationRequestDTO = new OAuth2TokenValidationRequestDTO();
    oAuth2TokenValidationResponseDTO = new OAuth2TokenValidationResponseDTO();
    oAuth2TokenValidationMessageContext = new OAuth2TokenValidationMessageContext(oAuth2TokenValidationRequestDTO, oAuth2TokenValidationResponseDTO);
    Mockito.when(systemScopesIssuer.validateScope((OAuth2TokenValidationMessageContext) Mockito.anyObject())).thenReturn(true);
}
Also used : OAuth2TokenValidationMessageContext(org.wso2.carbon.identity.oauth2.validators.OAuth2TokenValidationMessageContext) OAuthTokenReqMessageContext(org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext) OAuthAuthzReqMessageContext(org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO) OAuth2TokenValidationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO) Before(org.junit.Before)

Aggregations

AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)3 SignedJWT (com.nimbusds.jwt.SignedJWT)2 ParseException (java.text.ParseException)2 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 Before (org.junit.Before)1 Assertion (org.opensaml.saml.saml2.core.Assertion)1 OAuthAuthzReqMessageContext (org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext)1 OAuth2AccessTokenReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)1 OAuth2AuthorizeReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO)1 OAuth2TokenValidationRequestDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO)1 OAuth2TokenValidationResponseDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO)1 RequestParameter (org.wso2.carbon.identity.oauth2.model.RequestParameter)1 OAuthTokenReqMessageContext (org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext)1 OAuth2TokenValidationMessageContext (org.wso2.carbon.identity.oauth2.validators.OAuth2TokenValidationMessageContext)1 IdentityProviderManagementException (org.wso2.carbon.idp.mgt.IdentityProviderManagementException)1