Java源码示例:org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO
示例1
/**
* Add user attributes to cache.
*
* @param tokenReqDTO
* @param tokenRespDTO
*/
private void addUserAttributesToCache(OAuth2AccessTokenReqDTO tokenReqDTO, OAuth2AccessTokenRespDTO tokenRespDTO) {
AuthorizationGrantCacheKey oldCacheKey = new AuthorizationGrantCacheKey(tokenReqDTO.getAuthorizationCode());
//checking getUserAttributesId value of cacheKey before retrieve entry from cache as it causes to NPE
if (oldCacheKey.getUserAttributesId() != null) {
AuthorizationGrantCacheEntry authorizationGrantCacheEntry = AuthorizationGrantCache.getInstance().getValueFromCacheByCode(oldCacheKey);
AuthorizationGrantCacheKey newCacheKey = new AuthorizationGrantCacheKey(tokenRespDTO.getAccessToken());
authorizationGrantCacheEntry.setTokenId(tokenRespDTO.getTokenId());
if (AuthorizationGrantCache.getInstance().getValueFromCacheByToken(newCacheKey) == null) {
if(log.isDebugEnabled()){
log.debug("No AuthorizationGrantCache entry found for the access token:"+ newCacheKey.getUserAttributesId()+
", hence adding to cache");
}
AuthorizationGrantCache.getInstance().addToCacheByToken(newCacheKey, authorizationGrantCacheEntry);
AuthorizationGrantCache.getInstance().clearCacheEntryByCode(oldCacheKey);
} else{
//if the user attributes are already saved for access token, no need to add again.
}
}
}
示例2
@Override
public boolean authenticateClient(OAuthTokenReqMessageContext tokReqMsgCtx)
throws IdentityOAuth2Exception {
OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
//Skipping credential validation for saml2 bearer if not configured as needed
if (StringUtils.isEmpty(oAuth2AccessTokenReqDTO.getClientSecret()) && org.wso2.carbon.identity.oauth.common
.GrantType.SAML20_BEARER.toString().equals(oAuth2AccessTokenReqDTO.getGrantType()) && JavaUtils
.isFalseExplicitly(authConfig)) {
if (log.isDebugEnabled()) {
log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType() + " " +
"Strict client validation set to : " + authConfig + " Authenticating without client secret");
}
return true;
}
if (log.isDebugEnabled()) {
log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType() + " " +
"Strict client validation set to : " + authConfig);
}
return false;
}
示例3
private OAuth2AccessTokenRespDTO getAccessToken(CarbonOAuthTokenRequest oauthRequest) {
OAuth2AccessTokenReqDTO tokenReqDTO = new OAuth2AccessTokenReqDTO();
String grantType = oauthRequest.getGrantType();
tokenReqDTO.setGrantType(grantType);
tokenReqDTO.setClientId(oauthRequest.getClientId());
tokenReqDTO.setClientSecret(oauthRequest.getClientSecret());
tokenReqDTO.setCallbackURI(oauthRequest.getRedirectURI());
tokenReqDTO.setScope(oauthRequest.getScopes().toArray(new String[oauthRequest.getScopes().size()]));
tokenReqDTO.setTenantDomain(oauthRequest.getTenantDomain());
// Check the grant type and set the corresponding parameters
if (GrantType.AUTHORIZATION_CODE.toString().equals(grantType)) {
tokenReqDTO.setAuthorizationCode(oauthRequest.getCode());
} else if (GrantType.PASSWORD.toString().equals(grantType)) {
tokenReqDTO.setResourceOwnerUsername(oauthRequest.getUsername());
tokenReqDTO.setResourceOwnerPassword(oauthRequest.getPassword());
} else if (GrantType.REFRESH_TOKEN.toString().equals(grantType)) {
tokenReqDTO.setRefreshToken(oauthRequest.getRefreshToken());
} else if (org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString().equals(grantType)) {
tokenReqDTO.setAssertion(oauthRequest.getAssertion());
} else if (org.wso2.carbon.identity.oauth.common.GrantType.IWA_NTLM.toString().equals(grantType)) {
tokenReqDTO.setWindowsToken(oauthRequest.getWindowsToken());
} else {
// Set all request parameters to the OAuth2AccessTokenReqDTO
tokenReqDTO.setRequestParameters(oauthRequest.getRequestParameters());
}
return EndpointUtil.getOAuth2Service().issueAccessToken(tokenReqDTO);
}
示例4
/**
* Get Oauth application information
*
* @param tokenReqDTO
* @return Oauth app information
* @throws IdentityOAuth2Exception
* @throws InvalidOAuthClientException
*/
private OAuthAppDO getAppInformation(OAuth2AccessTokenReqDTO tokenReqDTO) throws IdentityOAuth2Exception, InvalidOAuthClientException {
OAuthAppDO oAuthAppDO = appInfoCache.getValueFromCache(tokenReqDTO.getClientId());
if (oAuthAppDO != null) {
return oAuthAppDO;
} else {
oAuthAppDO = new OAuthAppDAO().getAppInformation(tokenReqDTO.getClientId());
appInfoCache.addToCache(tokenReqDTO.getClientId(), oAuthAppDO);
return oAuthAppDO;
}
}
示例5
@Override
public boolean canAuthenticate(OAuthTokenReqMessageContext tokReqMsgCtx)
throws IdentityOAuth2Exception {
OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
if (StringUtils.isNotEmpty(oAuth2AccessTokenReqDTO.getClientId()) &&
StringUtils.isNotEmpty(oAuth2AccessTokenReqDTO.getClientSecret())) {
if (log.isDebugEnabled()) {
log.debug("Can authenticate with client ID and Secret." +
" Client ID: "+ oAuth2AccessTokenReqDTO.getClientId());
}
return true;
} else {
if (org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString().equals(
oAuth2AccessTokenReqDTO.getGrantType())) {
//Getting configured value for client credential validation requirements
authConfig = properties.getProperty(
OAuthConstants.CLIENT_AUTH_CREDENTIAL_VALIDATION);
if (log.isDebugEnabled()) {
log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType());
}
//If user has set strict validation to false, can authenticate without credentials
if (StringUtils.isNotEmpty(authConfig) && JavaUtils.isFalseExplicitly(authConfig)) {
if (log.isDebugEnabled()) {
log.debug("Client auth credential validation set to : " + authConfig + ". " +
"can authenticate without client secret");
}
return true;
}
}
}
return false;
}
示例6
protected void storeAccessToken(OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO, String userStoreDomain,
AccessTokenDO newAccessTokenDO, String newAccessToken, AccessTokenDO
existingAccessTokenDO) throws IdentityOAuth2Exception {
try {
tokenMgtDAO.storeAccessToken(newAccessToken, oAuth2AccessTokenReqDTO.getClientId(),
newAccessTokenDO, existingAccessTokenDO, userStoreDomain);
} catch (IdentityException e) {
throw new IdentityOAuth2Exception(
"Error occurred while storing new access token : " + newAccessToken, e);
}
}
示例7
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
throws IdentityOAuth2Exception {
OAuth2AccessTokenReqDTO tokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
String grantType = tokenReqDTO.getGrantType();
// Load application data from the cache
AppInfoCache appInfoCache = AppInfoCache.getInstance();
OAuthAppDO oAuthAppDO = appInfoCache.getValueFromCache(tokenReqDTO.getClientId());
if (oAuthAppDO == null) {
try {
oAuthAppDO = new OAuthAppDAO().getAppInformation(tokenReqDTO.getClientId());
appInfoCache.addToCache(tokenReqDTO.getClientId(), oAuthAppDO);
} catch (InvalidOAuthClientException e) {
throw new IdentityOAuth2Exception(e.getMessage(), e);
}
}
// If the application has defined a limited set of grant types, then check the grant
if (oAuthAppDO.getGrantTypes() != null && !oAuthAppDO.getGrantTypes().contains(grantType)) {
if (log.isDebugEnabled()) {
//Do not change this log format as these logs use by external applications
log.debug("Unsupported Grant Type : " + grantType + " for client id : " + tokenReqDTO.getClientId());
}
return false;
}
return true;
}
示例8
@Override
protected void storeAccessToken(OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO, String userStoreDomain,
AccessTokenDO newAccessTokenDO, String newAccessToken, AccessTokenDO
existingAccessTokenDO)
throws IdentityOAuth2Exception {
try {
newAccessTokenDO.setAuthorizationCode(oAuth2AccessTokenReqDTO.getAuthorizationCode());
tokenMgtDAO.storeAccessToken(newAccessToken, oAuth2AccessTokenReqDTO.getClientId(),
newAccessTokenDO, existingAccessTokenDO, userStoreDomain);
} catch (IdentityException e) {
throw new IdentityOAuth2Exception(
"Error occurred while storing new access token", e);
}
}
示例9
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
if (!super.validateGrant(tokReqMsgCtx)) {
return false;
} else {
OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
String username = null;
String userTenantDomain = null;
String clientId = oAuth2AccessTokenReqDTO.getClientId();
String spTenantDomain = null;
OAuthValidationResponse response;
ServiceProvider serviceProvider;
boolean authStatus = false;
String accessToken = null;
RequestParameter[] parameters = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();
for (RequestParameter parameter : parameters) {
if (TOKEN_GRANT_PARAM.equals(parameter.getKey())) {
if (parameter.getValue() != null && parameter.getValue().length > 0) {
accessToken = parameter.getValue()[0];
}
}
}
if (accessToken != null && !accessToken.isEmpty()) {
try {
response = tokenValidator.validateToken(accessToken);
} catch (RemoteException e) {
log.error("Failed to validate the OAuth token provided.", e);
return false;
}
if (response != null && response.isValid()) {
authStatus = true;
username = response.getUserName() + "@" + response.getTenantDomain();
userTenantDomain = MultitenantUtils.getTenantDomain(username);
spTenantDomain = response.getTenantDomain();
} else if (response != null && !response.isValid()) {
throw new IdentityOAuth2Exception("Authentication failed for the provided access token");
}
}
try {
serviceProvider = OAuth2ServiceComponentHolder.getApplicationMgtService()
.getServiceProviderByClientId(clientId, "oauth2", spTenantDomain);
} catch (IdentityApplicationManagementException var15) {
throw new IdentityOAuth2Exception("Error occurred while retrieving OAuth2 application data for client id "
+ clientId, var15);
}
if (!serviceProvider.isSaasApp() && !userTenantDomain.equals(spTenantDomain)) {
if (log.isDebugEnabled()) {
log.debug("Non-SaaS service provider tenant domain is not same as user tenant domain; "
+ spTenantDomain + " != " + userTenantDomain);
}
return false;
} else {
String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
username = tenantAwareUserName + "@" + userTenantDomain;
if (authStatus) {
if (!username.contains("/") && StringUtils.isNotBlank(UserCoreUtil.getDomainFromThreadLocal())) {
username = UserCoreUtil.getDomainFromThreadLocal() + "/" + username;
}
AuthenticatedUser user = OAuth2Util.getUserFromUserName(username);
user.setAuthenticatedSubjectIdentifier(user.toString());
tokReqMsgCtx.setAuthorizedUser(user);
tokReqMsgCtx.setScope(oAuth2AccessTokenReqDTO.getScope());
return authStatus;
} else {
throw new IdentityOAuth2Exception("Authentication failed for " + username);
}
}
}
}
示例10
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
throws IdentityOAuth2Exception {
if(!super.validateGrant(tokReqMsgCtx)){
return false;
}
OAuth2AccessTokenReqDTO tokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
String refreshToken = tokenReqDTO.getRefreshToken();
RefreshTokenValidationDataDO validationDataDO = tokenMgtDAO.validateRefreshToken(
tokenReqDTO.getClientId(), refreshToken);
if (validationDataDO.getAccessToken() == null) {
log.debug("Invalid Refresh Token provided for Client with " +
"Client Id : " + tokenReqDTO.getClientId());
return false;
}
if (validationDataDO.getRefreshTokenState() != null &&
!OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(
validationDataDO.getRefreshTokenState()) &&
!OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED.equals(
validationDataDO.getRefreshTokenState())) {
if(log.isDebugEnabled()) {
log.debug("Access Token is not in 'ACTIVE' or 'EXPIRED' state for Client with " +
"Client Id : " + tokenReqDTO.getClientId());
}
return false;
}
String userStoreDomain = null;
if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) {
try {
userStoreDomain = OAuth2Util.getUserStoreDomainFromUserId(validationDataDO.getAuthorizedUser().toString());
} catch (IdentityOAuth2Exception e) {
String errorMsg = "Error occurred while getting user store domain for User ID : " + validationDataDO.getAuthorizedUser();
log.error(errorMsg, e);
throw new IdentityOAuth2Exception(errorMsg, e);
}
}
AccessTokenDO accessTokenDO = tokenMgtDAO.retrieveLatestAccessToken(tokenReqDTO.getClientId(),
validationDataDO.getAuthorizedUser(),
userStoreDomain, OAuth2Util.buildScopeString(validationDataDO.getScope()), true);
if (accessTokenDO == null){
if(log.isDebugEnabled()){
log.debug("Error while retrieving the latest refresh token");
}
return false;
}else if(!refreshToken.equals(accessTokenDO.getRefreshToken())){
if(log.isDebugEnabled()){
log.debug("Refresh token is not the latest.");
}
return false;
}
if (log.isDebugEnabled()) {
log.debug("Refresh token validation successful for " +
"Client id : " + tokenReqDTO.getClientId() +
", Authorized User : " + validationDataDO.getAuthorizedUser() +
", Token Scope : " + OAuth2Util.buildScopeString(validationDataDO.getScope()));
}
tokReqMsgCtx.setAuthorizedUser(validationDataDO.getAuthorizedUser());
tokReqMsgCtx.setScope(validationDataDO.getScope());
// Store the old access token as a OAuthTokenReqMessageContext property, this is already
// a preprocessed token.
tokReqMsgCtx.addProperty(PREV_ACCESS_TOKEN, validationDataDO);
return true;
}
示例11
public OAuthTokenReqMessageContext(OAuth2AccessTokenReqDTO oauth2AccessTokenReqDTO) {
this.oauth2AccessTokenReqDTO = oauth2AccessTokenReqDTO;
}
示例12
public OAuth2AccessTokenReqDTO getOauth2AccessTokenReqDTO() {
return oauth2AccessTokenReqDTO;
}