org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration Java Examples

The following examples show how to use org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TokenValidationHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
    * 
    * @param accessTokenDO
    * @return
    */
   private long getAccessTokenExpirationTime(AccessTokenDO accessTokenDO) {
long expiryTime = OAuth2Util.getAccessTokenExpireMillis(accessTokenDO);

if (OAuthConstants.UserType.APPLICATION_USER.equals(accessTokenDO.getTokenType())
	&& OAuthServerConfiguration.getInstance().getUserAccessTokenValidityPeriodInSeconds() < 0) {
    return Long.MAX_VALUE;
} else if (OAuthConstants.UserType.APPLICATION.equals(accessTokenDO.getTokenType())
	&& OAuthServerConfiguration.getInstance().getApplicationAccessTokenValidityPeriodInSeconds() < 0) {
    return Long.MAX_VALUE;
} else if (expiryTime < 0) {
    return Long.MAX_VALUE;
}

return expiryTime / 1000;
   }
 
Example #2
Source File: OAuthServiceComponent.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
protected void activate(ComponentContext context) {
    // initialize the OAuth Server configuration
    OAuthServerConfiguration oauthServerConfig = OAuthServerConfiguration.getInstance();

    if (oauthServerConfig.isCacheEnabled()) {
        log.debug("OAuth Caching is enabled. Initializing the cache.");
        // initialize the cache
        OAuthCache cache = OAuthCache.getInstance();
        if (cache != null) {
            log.debug("OAuth Cache initialization was successful.");
        } else {
            log.debug("OAuth Cache initialization was unsuccessful.");
        }
    }

    listener = new IdentityOathEventListener();
    serviceRegistration = context.getBundleContext().registerService(UserOperationEventListener.class.getName(),
            listener, null);
    log.debug("Identity Oath Event Listener is enabled");

    if (log.isDebugEnabled()) {
        log.info("Identity OAuth bundle is activated");
    }
}
 
Example #3
Source File: OAuthAdminService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public String[] getAllowedGrantTypes() {
    if (allowedGrants == null) {
        synchronized (OAuthAdminService.class) {
            if (allowedGrants == null) {
                Set<String> allowedGrantSet =
                        OAuthServerConfiguration.getInstance().getSupportedGrantTypes().keySet();
                Set<String> modifiableGrantSet = new HashSet(allowedGrantSet);
                if (OAuthServerConfiguration.getInstance().getSupportedResponseTypes().containsKey("token")) {
                    modifiableGrantSet.add(IMPLICIT);
                }
                allowedGrants = new ArrayList<>(modifiableGrantSet);
            }
        }
    }
    return allowedGrants.toArray(new String[allowedGrants.size()]);
}
 
Example #4
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static AccessTokenDO validateAccessTokenDO(AccessTokenDO accessTokenDO) {

        long validityPeriodMillis = accessTokenDO.getValidityPeriodInMillis();
        long issuedTime = accessTokenDO.getIssuedTime().getTime();
        long currentTime = System.currentTimeMillis();

        //check the validity of cached OAuth2AccessToken Response
        long skew = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000;
        if (issuedTime + validityPeriodMillis - (currentTime + skew) > 1000) {
            long refreshValidity = OAuthServerConfiguration.getInstance()
                    .getRefreshTokenValidityPeriodInSeconds() * 1000;
            if (issuedTime + refreshValidity - currentTime + skew > 1000) {
                //Set new validity period to response object
                accessTokenDO.setValidityPeriod((issuedTime + validityPeriodMillis - (currentTime + skew)) / 1000);
                accessTokenDO.setValidityPeriodInMillis(issuedTime + validityPeriodMillis - (currentTime + skew));
                //Set issued time period to response object
                accessTokenDO.setIssuedTime(new Timestamp(currentTime));
                return accessTokenDO;
            }
        }
        //returns null if cached OAuth2AccessToken response object is expired
        return null;
    }
 
Example #5
Source File: CarbonOAuthTokenRequest.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize a grant type validator
 *
 * @return an instance of OAuthValidator
 * @throws OAuthProblemException
 * @throws OAuthSystemException
 */
@Override
protected OAuthValidator<HttpServletRequest> initValidator() throws OAuthProblemException, OAuthSystemException {

    String requestTypeValue = getParam(OAuth.OAUTH_GRANT_TYPE);
    if (OAuthUtils.isEmpty(requestTypeValue)) {
        throw OAuthUtils.handleOAuthProblemException("Missing grant_type parameter value");
    }

    Class<? extends OAuthValidator<HttpServletRequest>> clazz = OAuthServerConfiguration
            .getInstance().getSupportedGrantTypeValidators().get(requestTypeValue);

    if (clazz == null) {
        if (log.isDebugEnabled()) {
            //Do not change this log format as these logs use by external applications
            log.debug("Unsupported Grant Type : " + requestTypeValue +
                    " for client id : " + getClientId());
        }
        throw OAuthUtils.handleOAuthProblemException("Invalid grant_type parameter value");
    }

    return OAuthUtils.instantiateClass(clazz);
}
 
Example #6
Source File: CarbonOAuthAuthzRequest.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
protected OAuthValidator<HttpServletRequest> initValidator() throws OAuthProblemException, OAuthSystemException {

        String responseTypeValue = getParam(OAuth.OAUTH_RESPONSE_TYPE);
        if (OAuthUtils.isEmpty(responseTypeValue)) {
            throw OAuthUtils.handleOAuthProblemException("Missing response_type parameter value");
        }

        Class<? extends OAuthValidator<HttpServletRequest>> clazz = OAuthServerConfiguration
                .getInstance().getSupportedResponseTypeValidators().get(responseTypeValue);

        if (clazz == null) {
            if (log.isDebugEnabled()) {
                //Do not change this log format as these logs use by external applications
                log.debug("Unsupported Response Type : " + responseTypeValue +
                        " for client id : " + getClientId());
            }
            throw OAuthUtils.handleOAuthProblemException("Invalid response_type parameter value");
        }

        return OAuthUtils.instantiateClass(clazz);
    }
 
Example #7
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private long getTTL() {
    if (ttl != -1) {
        return ttl;
    }

    synchronized (JWTTokenGenerator.class) {
        if (ttl != -1) {
            return ttl;
        }
        String ttlValue = OAuthServerConfiguration.getInstance().getAuthorizationContextTTL();
        if (ttlValue != null) {
            ttl = Long.parseLong(ttlValue);
        } else {
            ttl = 15L;
        }
        return ttl;
    }
}
 
Example #8
Source File: ApiKeyAuthenticator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the jwt token is expired or not.
 *
 * @param payload The payload of the JWT token
 * @return returns true if the JWT token is expired
 */
private static boolean isJwtTokenExpired(JWTClaimsSet payload) {

    int timestampSkew = (int) OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds();

    DefaultJWTClaimsVerifier jwtClaimsSetVerifier = new DefaultJWTClaimsVerifier();
    jwtClaimsSetVerifier.setMaxClockSkew(timestampSkew);
    try {
        jwtClaimsSetVerifier.verify(payload);
        if (log.isDebugEnabled()) {
            log.debug("Token is not expired. User: " + payload.getSubject());
        }
    } catch (BadJWTException e) {
        if ("Expired JWT".equals(e.getMessage())) {
            return true;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Token is not expired. User: " + payload.getSubject());
    }
    return false;
}
 
Example #9
Source File: ImportApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This extracts information for creating an APIKey from an OAuthApplication
 *
 * @param type                 Type of the OAuthApp(SANDBOX or PRODUCTION)
 * @param oAuthApplicationInfo OAuth Application information
 * @return An APIKey containing keys from OAuthApplication
 */
private APIKey getAPIKeyFromOauthApp(String type, OAuthApplicationInfo oAuthApplicationInfo) {
    APIKey apiKey = new APIKey();
    apiKey.setType(type);
    apiKey.setConsumerKey(oAuthApplicationInfo.getClientId());
    apiKey.setConsumerSecret(oAuthApplicationInfo.getClientSecret());
    apiKey.setGrantTypes((String) oAuthApplicationInfo.getParameter(GRANT_TYPES));
    if (apiKey.getGrantTypes().contains(GRANT_TYPE_IMPLICIT) && apiKey.getGrantTypes().contains(GRANT_TYPE_CODE)) {
        apiKey.setCallbackUrl((String) oAuthApplicationInfo.getParameter(REDIRECT_URIS));
    }

    long validityPeriod = OAuthServerConfiguration.getInstance().getApplicationAccessTokenValidityPeriodInSeconds();
    apiKey.setValidityPeriod(validityPeriod);
    apiKey.setTokenScope(DEFAULT_TOKEN_SCOPE);
    return apiKey;
}
 
Example #10
Source File: APIMgtDAOTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    String dbConfigPath = System.getProperty("APIManagerDBConfigurationPath");
    APIManagerConfiguration config = new APIManagerConfiguration();
    initializeDatabase(dbConfigPath);
    config.load(dbConfigPath);
    ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(new APIManagerConfigurationServiceImpl
            (config));
    List<Notifier> notifierList = new ArrayList<>();
    SubscriptionsNotifier subscriptionsNotifier = new SubscriptionsNotifier();
    notifierList.add(subscriptionsNotifier);
    ServiceReferenceHolder.getInstance().getNotifiersMap().put(subscriptionsNotifier.getType(), notifierList);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    keyManager = Mockito.mock(KeyManager.class);
    APIMgtDBUtil.initialize();
    apiMgtDAO = ApiMgtDAO.getInstance();
    IdentityTenantUtil.setRealmService(new TestRealmService());
    String identityConfigPath = System.getProperty("IdentityConfigurationPath");
    IdentityConfigParser.getInstance(identityConfigPath);
    OAuthServerConfiguration oAuthServerConfiguration = OAuthServerConfiguration.getInstance();
    ServiceReferenceHolder.getInstance().setOauthServerConfiguration(oAuthServerConfiguration);

}
 
Example #11
Source File: ImportApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This extracts information for creating an APIKey from an OAuthApplication
 * @param type Type of the OAuthApp(SANDBOX or PRODUCTION)
 * @param keyManagerName
 * @param oAuthApplicationInfo OAuth Application information
 * @return An APIKey containing keys from OAuthApplication
 */
private APIKey getAPIKeyFromOauthApp(String type, String keyManagerName,
                                     OAuthApplicationInfo oAuthApplicationInfo){
    APIKey apiKey = new APIKey();
    apiKey.setType(type);
    apiKey.setConsumerKey(oAuthApplicationInfo.getClientId());
    apiKey.setConsumerSecret(oAuthApplicationInfo.getClientSecret());
    apiKey.setGrantTypes((String) oAuthApplicationInfo.getParameter(GRANT_TYPES));
    apiKey.setKeyManager(keyManagerName);
    if (apiKey.getGrantTypes().contains(GRANT_TYPE_IMPLICIT) && apiKey.getGrantTypes().contains(GRANT_TYPE_CODE)){
        apiKey.setCallbackUrl((String) oAuthApplicationInfo.getParameter(REDIRECT_URIS));
    }

    long validityPeriod = OAuthServerConfiguration.getInstance().getApplicationAccessTokenValidityPeriodInSeconds();
    apiKey.setValidityPeriod(validityPeriod);
    apiKey.setTokenScope(DEFAULT_TOKEN_SCOPE);
    apiKey.setAdditionalProperties(oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES));
    return apiKey;
}
 
Example #12
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private void validateExpiryTime(JWTClaimsSet claimsSet) throws IdentityOAuth2Exception {

        long timeStampSkewMillis = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000;
        long expirationTimeInMillis = claimsSet.getExpirationTime().getTime();
        long currentTimeInMillis = System.currentTimeMillis();
        if ((currentTimeInMillis + timeStampSkewMillis) > expirationTimeInMillis) {
            if (log.isDebugEnabled()) {
                log.debug("Token is expired." +
                        ", Expiration Time(ms) : " + expirationTimeInMillis +
                        ", TimeStamp Skew : " + timeStampSkewMillis +
                        ", Current Time : " + currentTimeInMillis + ". Token Rejected and validation terminated.");
            }
            throw new IdentityOAuth2Exception("Token is expired.");
        }

        if (log.isDebugEnabled()) {
            log.debug("Expiration Time(exp) of Token was validated successfully.");
        }
    }
 
Example #13
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private void validateNotBeforeTime(JWTClaimsSet claimsSet) throws IdentityOAuth2Exception {

        Date notBeforeTime = claimsSet.getNotBeforeTime();
        if (notBeforeTime != null) {
            long timeStampSkewMillis = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000;
            long notBeforeTimeMillis = notBeforeTime.getTime();
            long currentTimeInMillis = System.currentTimeMillis();
            if (currentTimeInMillis + timeStampSkewMillis < notBeforeTimeMillis) {
                if (log.isDebugEnabled()) {
                    log.debug("Token is used before Not_Before_Time." +
                            ", Not Before Time(ms) : " + notBeforeTimeMillis +
                            ", TimeStamp Skew : " + timeStampSkewMillis +
                            ", Current Time : " + currentTimeInMillis + ". Token Rejected and validation terminated.");
                }
                throw new IdentityOAuth2Exception("Token is used before Not_Before_Time.");
            }
            if (log.isDebugEnabled()) {
                log.debug("Not Before Time(nbf) of Token was validated successfully.");
            }
        }
    }
 
Example #14
Source File: DefaultOAuth2TokenValidator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateScope(OAuth2TokenValidationMessageContext messageContext)
        throws IdentityOAuth2Exception {

    OAuth2ScopeValidator scopeValidator = OAuthServerConfiguration.getInstance().getoAuth2ScopeValidator();

    //If a scope validator is engaged through the configuration
    if (scopeValidator != null && messageContext.getRequestDTO() != null &&
        messageContext.getRequestDTO().getContext() != null) {
        
        String resource = null;

        //Iterate the array of context params to find the 'resource' context param.
        for (OAuth2TokenValidationRequestDTO.TokenValidationContextParam resourceParam :
                messageContext.getRequestDTO().getContext()) {
            //If the context param is the resource that is being accessed
            if (resourceParam != null && "resource".equals(resourceParam.getKey())) {
                resource = resourceParam.getValue();
                break;
            }
        }

        //Return True if there is no resource to validate the token against
        //OR if the token has a valid scope to access the resource. False otherwise.
        return resource == null ||
                scopeValidator.validateScope((AccessTokenDO) messageContext.getProperty("AccessTokenDO"), resource);
    }
    return true;
}
 
Example #15
Source File: TokenResponseTypeHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void buildIdToken(OAuthAuthzReqMessageContext msgCtx, OAuth2AuthorizeRespDTO authzRespDTO)
        throws IdentityOAuth2Exception{

    if (StringUtils.contains(msgCtx.getAuthorizationReqDTO().getResponseType(), "id_token") &&
            msgCtx.getApprovedScope() != null && OAuth2Util.isOIDCAuthzRequest(msgCtx.getApprovedScope())) {
        IDTokenBuilder builder = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenBuilder();
        authzRespDTO.setIdToken(builder.buildIDToken(msgCtx, authzRespDTO));
    }
}
 
Example #16
Source File: ClientCredentialsGrantHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
protected String signJWT(String payLoad, OAuthTokenReqMessageContext request)
        throws IdentityOAuth2Exception {
    JWSAlgorithm jwsAlgorithm =
            mapSignatureAlgorithm(OAuthServerConfiguration.getInstance()
                    .getSignatureAlgorithm());
    if (JWSAlgorithm.RS256.equals(jwsAlgorithm) || JWSAlgorithm.RS384.equals(jwsAlgorithm) ||
            JWSAlgorithm.RS512.equals(jwsAlgorithm)) {
        return signJWTWithRSA(payLoad, jwsAlgorithm, request);
    }
    log.error("UnSupported Signature Algorithm");
    throw new IdentityOAuth2Exception("UnSupported Signature Algorithm");
}
 
Example #17
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getIDTokenIssuer() {
    String issuer = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenIssuerIdentifier();
    if (StringUtils.isBlank(issuer)) {
        issuer = OAuthURL.getOAuth2TokenEPUrl();
    }
    return issuer;
}
 
Example #18
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getOAuth1RequestTokenUrl() {
    String oauth1RequestTokenUrl = OAuthServerConfiguration.getInstance().getOAuth1RequestTokenUrl();
    if(StringUtils.isBlank(oauth1RequestTokenUrl)){
        oauth1RequestTokenUrl = IdentityUtil.getServerURL("oauth/request-token", true, true);
    }
    return oauth1RequestTokenUrl;
}
 
Example #19
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getOAuth1AuthorizeUrl() {
    String oauth1AuthorizeUrl = OAuthServerConfiguration.getInstance().getOAuth1AuthorizeUrl();
    if(StringUtils.isBlank(oauth1AuthorizeUrl)){
        oauth1AuthorizeUrl = IdentityUtil.getServerURL("oauth/authorize-url", true, true);
    }
    return oauth1AuthorizeUrl;
}
 
Example #20
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getOAuth1AccessTokenUrl() {
    String oauth1AccessTokenUrl = OAuthServerConfiguration.getInstance().getOAuth1AccessTokenUrl();
    if(StringUtils.isBlank(oauth1AccessTokenUrl)){
        oauth1AccessTokenUrl = IdentityUtil.getServerURL("oauth/access-token", true, true);
    }
    return oauth1AccessTokenUrl;
}
 
Example #21
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getOAuth2AuthzEPUrl() {
    String oauth2AuthzEPUrl = OAuthServerConfiguration.getInstance().getOAuth2AuthzEPUrl();
    if(StringUtils.isBlank(oauth2AuthzEPUrl)){
        oauth2AuthzEPUrl = IdentityUtil.getServerURL("oauth2/authorize", true, false);
    }
    return oauth2AuthzEPUrl;
}
 
Example #22
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getOAuth2TokenEPUrl() {
    String oauth2TokenEPUrl = OAuthServerConfiguration.getInstance().getOAuth2TokenEPUrl();
    if(StringUtils.isBlank(oauth2TokenEPUrl)){
        oauth2TokenEPUrl = IdentityUtil.getServerURL("oauth2/token", true, false);
    }
    return oauth2TokenEPUrl;
}
 
Example #23
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getOAuth2UserInfoEPUrl() {
    String oauth2UserInfoEPUrl = OAuthServerConfiguration.getInstance().getOauth2UserInfoEPUrl();
    if(StringUtils.isBlank(oauth2UserInfoEPUrl)){
        oauth2UserInfoEPUrl = IdentityUtil.getServerURL("oauth2/userinfo", true, false);
    }
    return oauth2UserInfoEPUrl;
}
 
Example #24
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getOIDCConsentPageUrl() {
    String OIDCConsentPageUrl = OAuthServerConfiguration.getInstance().getOIDCConsentPageUrl();
    if(StringUtils.isBlank(OIDCConsentPageUrl)){
        OIDCConsentPageUrl = IdentityUtil.getServerURL("/authenticationendpoint/oauth2_consent.do", false,
                false);
    }
    return OIDCConsentPageUrl;
}
 
Example #25
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getOAuth2ConsentPageUrl() {
    String oAuth2ConsentPageUrl = OAuthServerConfiguration.getInstance().getOauth2ConsentPageUrl();
    if(StringUtils.isBlank(oAuth2ConsentPageUrl)){
        oAuth2ConsentPageUrl = IdentityUtil.getServerURL("/authenticationendpoint/oauth2_authz.do", false,
                false);
    }
    return oAuth2ConsentPageUrl;
}
 
Example #26
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getOAuth2ErrorPageUrl() {
    String oAuth2ErrorPageUrl = OAuthServerConfiguration.getInstance().getOauth2ErrorPageUrl();
    if(StringUtils.isBlank(oAuth2ErrorPageUrl)){
        oAuth2ErrorPageUrl = IdentityUtil.getServerURL("/authenticationendpoint/oauth2_error.do", false, false);
    }
    return oAuth2ErrorPageUrl;
}
 
Example #27
Source File: APIManagerComponent.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the Oauth Server configuration Service Service dependency
 *
 * @param oauthServerConfiguration Output EventAdapter Service reference
 */
@Reference(
        name = "oauth.config.service",
        service = OAuthServerConfiguration.class,
        cardinality = ReferenceCardinality.MANDATORY,
        policy = ReferencePolicy.DYNAMIC,
        unbind = "unsetOauthServerConfiguration")
protected void setOauthServerConfiguration(OAuthServerConfiguration oauthServerConfiguration) {
    ServiceReferenceHolder.getInstance().setOauthServerConfiguration(oauthServerConfiguration);
}
 
Example #28
Source File: AccessTokenIssuer.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Private constructor which will not allow to create objects of this class from outside
 */
private AccessTokenIssuer() throws IdentityOAuth2Exception {

    authzGrantHandlers = OAuthServerConfiguration.getInstance().getSupportedGrantTypes();
    clientAuthenticationHandlers = OAuthServerConfiguration.getInstance().getSupportedClientAuthHandlers();
    appInfoCache = AppInfoCache.getInstance();
    if (appInfoCache != null) {
        if (log.isDebugEnabled()) {
            log.debug("Successfully created AppInfoCache under " + OAuthConstants.OAUTH_CACHE_MANAGER);
        }
    } else {
        log.error("Error while creating AppInfoCache");
    }

}
 
Example #29
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Build a signed jwt token from authorization request message context
 *
 * @param request Oauth authorization message context
 * @return Signed jwt string
 * @throws IdentityOAuth2Exception
 */
protected String buildIDToken(OAuthAuthzReqMessageContext request)
        throws IdentityOAuth2Exception {

    String issuer = OAuth2Util.getIDTokenIssuer();
    long lifetimeInMillis = OAuthServerConfiguration.getInstance().
            getApplicationAccessTokenValidityPeriodInSeconds() * 1000;
    long curTimeInMillis = Calendar.getInstance().getTimeInMillis();
    // setting subject
    String subject = request.getAuthorizationReqDTO().getUser().getAuthenticatedSubjectIdentifier();

    if (!StringUtils.isNotBlank(subject)) {
        subject = request.getAuthorizationReqDTO().getUser().getUserName();
    }

    JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
    jwtClaimsSet.setIssuer(issuer);
    jwtClaimsSet.setSubject(subject);
    jwtClaimsSet.setAudience(Arrays.asList(request.getAuthorizationReqDTO().getConsumerKey()));
    jwtClaimsSet.setClaim(Constants.AUTHORIZATION_PARTY, request.getAuthorizationReqDTO().getConsumerKey());
    jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis));
    jwtClaimsSet.setIssueTime(new Date(curTimeInMillis));
    addUserClaims(jwtClaimsSet, request.getAuthorizationReqDTO().getUser());

    if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) {
        return new PlainJWT(jwtClaimsSet).serialize();
    }
    return signJWT(jwtClaimsSet, request);
}
 
Example #30
Source File: OAuthUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static void clearOAuthCache(String oauthCacheKey) {
    if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
        OAuthCache oauthCache = OAuthCache.getInstance();
        OAuthCacheKey cacheKey = new OAuthCacheKey(oauthCacheKey);
        oauthCache.clearCacheEntry(cacheKey);
    }
}