Java源码示例:org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO
示例1
@BeforeClass
public void init() throws NoSuchFieldException {
bstAuthenticator = new BSTAuthenticator();
properties = new Properties();
headersField = org.apache.coyote.Request.class.getDeclaredField("headers");
headersField.setAccessible(true);
oAuth2TokenValidationService = Mockito
.mock(OAuth2TokenValidationService.class, Mockito.CALLS_REAL_METHODS);
oAuth2ClientApplicationDTO = Mockito
.mock(OAuth2ClientApplicationDTO.class, Mockito.CALLS_REAL_METHODS);
OAuth2TokenValidationResponseDTO authorizedValidationResponse = new OAuth2TokenValidationResponseDTO();
authorizedValidationResponse.setValid(true);
authorizedValidationResponse.setAuthorizedUser("[email protected]" + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService)
.findOAuthConsumerIfTokenIsValid(Mockito.any());
oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(authorizedValidationResponse);
AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService);
}
示例2
/**
* This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
* containing the validity and user details if valid.
*
* @param token which need to be validated.
* @return OAuthValidationResponse with the validated results.
*/
public OAuthValidationResponse validateToken(String token) throws RemoteException{
OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken =
validationRequest.new OAuth2AccessToken();
accessToken.setTokenType(BEARER_TOKEN_TYPE);
accessToken.setIdentifier(token);
validationRequest.setAccessToken(accessToken);
OAuth2TokenValidationResponseDTO tokenValidationResponse = OAuthAuthenticatorDataHolder.getInstance().
getOAuth2TokenValidationService().findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
boolean isValid = tokenValidationResponse.isValid();
String userName = null;
String tenantDomain = null;
if (isValid) {
userName = MultitenantUtils.getTenantAwareUsername(
tokenValidationResponse.getAuthorizedUser());
tenantDomain =
MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser());
}
return new OAuthValidationResponse(userName, tenantDomain, isValid);
}
示例3
/**
* This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
* containing the validity and user details if valid.
*
* @param token which need to be validated.
* @return OAuthValidationResponse with the validated results.
*/
public OAuthValidationResponse validateToken(String token) {
OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken =
validationRequest.new OAuth2AccessToken();
accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE);
accessToken.setIdentifier(token);
validationRequest.setAccessToken(accessToken);
OAuth2TokenValidationResponseDTO tokenValidationResponse = OAuthAuthenticatorDataHolder.getInstance().
getOAuth2TokenValidationService().findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
boolean isValid = tokenValidationResponse.isValid();
String userName = null;
String tenantDomain = null;
if (isValid) {
userName = MultitenantUtils.getTenantAwareUsername(
tokenValidationResponse.getAuthorizedUser());
tenantDomain =
MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser());
}
return new OAuthValidationResponse(userName, tenantDomain, isValid);
}
示例4
@Override
public String getResponseString(OAuth2TokenValidationResponseDTO tokenResponse)
throws UserInfoEndpointException {
Map<ClaimMapping, String> userAttributes = getUserAttributesFromCache(tokenResponse);
Map<String, Object> claims = null;
if (userAttributes == null || userAttributes.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("User attributes not found in cache. Trying to retrieve from user store.");
}
claims = ClaimUtil.getClaimsFromUserStore(tokenResponse);
} else {
UserInfoClaimRetriever retriever = UserInfoEndpointConfig.getInstance().getUserInfoClaimRetriever();
claims = retriever.getClaimsMap(userAttributes);
}
if(claims == null){
claims = new HashMap<String,Object>();
}
if(!claims.containsKey("sub") || StringUtils.isBlank((String) claims.get("sub"))) {
claims.put("sub", tokenResponse.getAuthorizedUser());
}
return JSONUtils.buildJSON(claims);
}
示例5
/**
* @param validationReqDTO
* @return
*/
public OAuth2ClientApplicationDTO findOAuthConsumerIfTokenIsValid(OAuth2TokenValidationRequestDTO validationReqDTO) {
TokenValidationHandler validationHandler = TokenValidationHandler.getInstance();
try {
return validationHandler.findOAuthConsumerIfTokenIsValid(validationReqDTO);
} catch (IdentityOAuth2Exception e) {
log.error("Error occurred while validating the OAuth2 access token", e);
OAuth2ClientApplicationDTO appDTO = new OAuth2ClientApplicationDTO();
OAuth2TokenValidationResponseDTO errRespDTO = new OAuth2TokenValidationResponseDTO();
errRespDTO.setValid(false);
errRespDTO.setErrorMsg(e.getMessage());
appDTO.setAccessTokenValidationResponse(errRespDTO);
return appDTO;
}
}
示例6
@Test(description = "This method tests the authenticate method of BST Authenticator when all the relevant "
+ "details", dependsOnMethods = "testInitWithRemote")
public void testAuthenticate() throws NoSuchFieldException, IllegalAccessException, IOException {
Request request = createSoapRequest("CorrectBST.xml");
org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
uriMB.setAccessible(true);
MessageBytes bytes = MessageBytes.newInstance();
bytes.setString("test");
uriMB.set(coyoteRequest, bytes);
request.setCoyoteRequest(coyoteRequest);
bstAuthenticator.canHandle(request);
AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null);
Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
"Authentication status of authentication info is wrong");
Assert.assertEquals(authenticationInfo.getUsername(), "admin",
"User name in the authentication info is different than original user");
OAuth2TokenValidationResponseDTO unAuthorizedValidationRespose = new OAuth2TokenValidationResponseDTO();
unAuthorizedValidationRespose.setValid(false);
unAuthorizedValidationRespose.setErrorMsg("User is not authorized");
Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService)
.findOAuthConsumerIfTokenIsValid(Mockito.any());
oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(unAuthorizedValidationRespose);
AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService);
authenticationInfo = bstAuthenticator.authenticate(request, null);
Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE,
"Un-authorized user got authenticated with BST");
}
示例7
/**
* Validates the access token with WSO2 IS token validation OSGI service.
* Scope is checked.
*/
@Override
public OAuth2TokenValidationResponseDTO validateToken(String accessTokenIdentifier)
throws UserInfoEndpointException {
OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken = dto.new OAuth2AccessToken();
accessToken.setTokenType("bearer");
accessToken.setIdentifier(accessTokenIdentifier);
dto.setAccessToken(accessToken);
OAuth2TokenValidationResponseDTO response =
EndpointUtil.getOAuth2TokenValidationService()
.validate(dto);
// invalid access token
if (!response.isValid()) {
throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_TOKEN,
"Access token validation failed");
}
// check the scope
boolean isOpenIDScope = false;
String[] scope = response.getScope();
for (String curScope : scope) {
if ("openid".equals(curScope)) {
isOpenIDScope = true;
}
}
if (!isOpenIDScope) {
throw new UserInfoEndpointException(OAuthError.ResourceResponse.INSUFFICIENT_SCOPE,
"Access token does not have the openid scope");
}
if (response.getAuthorizedUser() == null) {
throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_TOKEN,
"Access token is not valid. No authorized user found. Invalid grant");
}
OAuth2TokenValidationResponseDTO.AuthorizationContextToken authorizationContextToken = response.new AuthorizationContextToken(accessToken.getTokenType(), accessToken.getIdentifier());
response.setAuthorizationContextToken(authorizationContextToken);
return response;
}
示例8
private Map<ClaimMapping, String> getUserAttributesFromCache(OAuth2TokenValidationResponseDTO tokenResponse) {
AuthorizationGrantCacheKey cacheKey = new AuthorizationGrantCacheKey(tokenResponse.getAuthorizationContextToken()
.getTokenString());
AuthorizationGrantCacheEntry cacheEntry = (AuthorizationGrantCacheEntry) AuthorizationGrantCache.getInstance()
.getValueFromCacheByToken(cacheKey);
if (cacheEntry == null) {
return new HashMap<ClaimMapping, String>();
}
return cacheEntry.getUserAttributes();
}
示例9
@Override
public String getResponseString(OAuth2TokenValidationResponseDTO tokenResponse)
throws UserInfoEndpointException, OAuthSystemException {
Map<ClaimMapping, String> userAttributes = getUserAttributesFromCache(tokenResponse);
Map<String, Object> claims = null;
if (userAttributes.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("User attributes not found in cache. Trying to retrieve from user store.");
}
claims = ClaimUtil.getClaimsFromUserStore(tokenResponse);
} else {
UserInfoClaimRetriever retriever = UserInfoEndpointConfig.getInstance().getUserInfoClaimRetriever();
claims = retriever.getClaimsMap(userAttributes);
}
if(claims == null){
claims = new HashMap<String,Object>();
}
if(!claims.containsKey("sub") || StringUtils.isBlank((String) claims.get("sub"))) {
claims.put("sub", tokenResponse.getAuthorizedUser());
}
JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
jwtClaimsSet.setAllClaims(claims);
return new PlainJWT(jwtClaimsSet).serialize();
}
示例10
private Map<ClaimMapping, String> getUserAttributesFromCache(OAuth2TokenValidationResponseDTO tokenResponse) {
Map<ClaimMapping,String> claims = new HashMap<ClaimMapping,String>();
AuthorizationGrantCacheKey cacheKey =
new AuthorizationGrantCacheKey(tokenResponse.getAuthorizationContextToken().getTokenString());
AuthorizationGrantCacheEntry cacheEntry =
(AuthorizationGrantCacheEntry) AuthorizationGrantCache.getInstance().getValueFromCacheByToken(cacheKey);
if (cacheEntry != null) {
claims = cacheEntry.getUserAttributes();
}
return claims;
}
示例11
/**
* @param validationReqDTO
* @return
*/
public OAuth2TokenValidationResponseDTO validate(OAuth2TokenValidationRequestDTO validationReqDTO) {
TokenValidationHandler validationHandler = TokenValidationHandler.getInstance();
try {
return validationHandler.validate(validationReqDTO);
} catch (IdentityOAuth2Exception e) {
log.error("Error occurred while validating the OAuth2 access token", e);
OAuth2TokenValidationResponseDTO errRespDTO = new OAuth2TokenValidationResponseDTO();
errRespDTO.setValid(false);
errRespDTO.setErrorMsg("Server error occurred while validating the OAuth2 access token");
return errRespDTO;
}
}
示例12
/**
* @param requestDTO
* @return
* @throws IdentityOAuth2Exception
*/
public OAuth2TokenValidationResponseDTO validate(OAuth2TokenValidationRequestDTO requestDTO)
throws IdentityOAuth2Exception {
OAuth2ClientApplicationDTO appToken = findOAuthConsumerIfTokenIsValid(requestDTO);
return appToken.getAccessTokenValidationResponse();
}
示例13
/**
*
* @param errorMessage
* @return
*/
private OAuth2ClientApplicationDTO buildClientAppErrorResponse(String errorMessage) {
OAuth2TokenValidationResponseDTO responseDTO = new OAuth2TokenValidationResponseDTO();
OAuth2ClientApplicationDTO clientApp = new OAuth2ClientApplicationDTO();
if (log.isDebugEnabled()) {
log.debug(errorMessage);
}
responseDTO.setValid(false);
responseDTO.setErrorMsg(errorMessage);
clientApp.setAccessTokenValidationResponse(responseDTO);
return clientApp;
}
示例14
@Override
public OAuthValidationResponse validateToken(String accessToken, String resource)
throws OAuthTokenValidationException {
OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO.OAuth2AccessToken oauthToken =
validationRequest.new OAuth2AccessToken();
oauthToken.setTokenType(OAuthConstants.BEARER_TOKEN_TYPE);
oauthToken.setIdentifier(accessToken);
validationRequest.setAccessToken(oauthToken);
//Set the resource context param. This will be used in scope validation.
OAuth2TokenValidationRequestDTO.TokenValidationContextParam
resourceContextParam = validationRequest.new TokenValidationContextParam();
resourceContextParam.setKey(OAuthConstants.RESOURCE_KEY);
resourceContextParam.setValue(resource);
OAuth2TokenValidationRequestDTO.TokenValidationContextParam[]
tokenValidationContextParams =
new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1];
tokenValidationContextParams[0] = resourceContextParam;
validationRequest.setContext(tokenValidationContextParams);
OAuth2TokenValidationResponseDTO tokenValidationResponse = AuthenticatorFrameworkDataHolder.getInstance().
getOAuth2TokenValidationService().findOAuthConsumerIfTokenIsValid(
validationRequest).getAccessTokenValidationResponse();
boolean isValid = tokenValidationResponse.isValid();
String userName;
String tenantDomain;
if (isValid) {
userName = MultitenantUtils.getTenantAwareUsername(
tokenValidationResponse.getAuthorizedUser());
tenantDomain =
MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser());
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
tenantDomain = MultitenantUtils.getTenantDomain(userName);
}
return new OAuthValidationResponse(userName, tenantDomain, true);
} else {
OAuthValidationResponse oAuthValidationResponse = new OAuthValidationResponse();
oAuthValidationResponse.setErrorMsg(tokenValidationResponse.getErrorMsg());
return oAuthValidationResponse;
}
}
示例15
@Override
protected void processAuthenticationResponse(HttpServletRequest request,
HttpServletResponse response, AuthenticationContext context)
throws AuthenticationFailedException {
String headerValue = (String) request.getSession().getAttribute(AUTHORIZATION_HEADER_NAME);
String token = null;
if (headerValue != null) {
token = headerValue.trim().split(" ")[1];
} else {
token = request.getParameter(ACCESS_TOKEN);
}
try {
OAuth2TokenValidationService validationService = new OAuth2TokenValidationService();
OAuth2TokenValidationRequestDTO validationReqDTO = new OAuth2TokenValidationRequestDTO();
OAuth2AccessToken accessToken = validationReqDTO.new OAuth2AccessToken();
accessToken.setIdentifier(token);
accessToken.setTokenType("bearer");
validationReqDTO.setAccessToken(accessToken);
OAuth2TokenValidationResponseDTO validationResponse = validationService.validate(validationReqDTO);
if (!validationResponse.isValid()) {
log.error("RequestPath OAuth authentication failed");
throw new AuthenticationFailedException("Authentication Failed");
}
String user = validationResponse.getAuthorizedUser();
String tenantDomain = MultitenantUtils.getTenantDomain(user);
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
user = MultitenantUtils.getTenantAwareUsername(user);
}
Map<String, Object> authProperties = context.getProperties();
if (authProperties == null) {
authProperties = new HashMap<String, Object>();
context.setProperties(authProperties);
}
// TODO: user tenant domain has to be an attribute in the
// AuthenticationContext
authProperties.put("user-tenant-domain", tenantDomain);
if (log.isDebugEnabled()) {
log.debug("Authenticated user " + user);
}
context.setSubject(AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(user));
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new AuthenticationFailedException(e.getMessage(), e);
}
}
示例16
public static Map<String, Object> getClaimsFromUserStore(OAuth2TokenValidationResponseDTO tokenResponse) throws
UserInfoEndpointException {
String username = tokenResponse.getAuthorizedUser();
String tenantDomain = MultitenantUtils.getTenantDomain(tokenResponse.getAuthorizedUser());
UserRealm realm;
List<String> claimURIList = new ArrayList<>();
Map<String, Object> mappedAppClaims = new HashMap<>();
try {
realm = IdentityTenantUtil.getRealm(tenantDomain, username);
if (realm == null) {
log.warn("No valid tenant domain provider. Empty claim returned back");
return new HashMap<>();
}
Map<String, String> spToLocalClaimMappings;
UserStoreManager userstore = realm.getUserStoreManager();
// need to get all the requested claims
Map<String, String> requestedLocalClaimMap = ClaimManagerHandler.getInstance()
.getMappingsMapFromOtherDialectToCarbon(SP_DIALECT, null, tenantDomain, true);
if (MapUtils.isNotEmpty(requestedLocalClaimMap)) {
for (String s : requestedLocalClaimMap.keySet()) {
claimURIList.add(s);
}
if (log.isDebugEnabled()) {
log.debug("Requested number of local claims: " + claimURIList.size());
}
spToLocalClaimMappings = ClaimManagerHandler.getInstance().getMappingsMapFromOtherDialectToCarbon
(SP_DIALECT, null, tenantDomain, false);
Map<String, String> userClaims = userstore.getUserClaimValues(MultitenantUtils.getTenantAwareUsername
(username), claimURIList.toArray(new String[claimURIList.size()]), null);
if (log.isDebugEnabled()) {
log.debug("User claims retrieved from user store: " + userClaims.size());
}
if (MapUtils.isEmpty(userClaims)) {
return new HashMap<>();
}
for (Map.Entry<String, String> entry : spToLocalClaimMappings.entrySet()) {
String value = userClaims.get(entry.getValue());
if (value != null) {
mappedAppClaims.put(entry.getKey(), value);
if (log.isDebugEnabled() &&
IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
log.debug("Mapped claim: key - " + entry.getKey() + " value -" + value);
}
}
}
}
} catch (Exception e) {
if(e instanceof UserStoreException){
if (e.getMessage().contains("UserNotFound")) {
if (log.isDebugEnabled()) {
log.debug("User " + username + " not found in user store");
}
}
} else {
log.error("Error while retrieving the claims from user store for " + username, e);
throw new UserInfoEndpointException("Error while retrieving the claims from user store for " + username);
}
}
return mappedAppClaims;
}
示例17
public OAuth2TokenValidationMessageContext(OAuth2TokenValidationRequestDTO requestDTO,
OAuth2TokenValidationResponseDTO responseDTO) {
this.requestDTO = requestDTO;
this.responseDTO = responseDTO;
}
示例18
public OAuth2TokenValidationResponseDTO getResponseDTO() {
return responseDTO;
}
示例19
public boolean isAuthenticated(Message message, ClassResourceInfo classResourceInfo) {
// get the map of protocol headers
Map protocolHeaders = (TreeMap) message.get(Message.PROTOCOL_HEADERS);
// get the value for Authorization Header
List authzHeaders = (ArrayList) protocolHeaders
.get(SCIMConstants.AUTHORIZATION_HEADER);
if (authzHeaders != null) {
// get the authorization header value, if provided
String authzHeader = (String) authzHeaders.get(0);
// extract access token
String accessToken = authzHeader.trim().substring(7).trim();
// validate access token
try {
OAuth2ClientApplicationDTO validationApp = this.validateAccessToken(accessToken);
OAuth2TokenValidationResponseDTO validationResponse = null;
if (validationApp != null) {
validationResponse = validationApp.getAccessTokenValidationResponse();
}
if (validationResponse != null && validationResponse.isValid()) {
String userName = validationResponse.getAuthorizedUser();
authzHeaders.set(0, userName);
// setup thread local variable to be consumed by the provisioning framework.
RealmService realmService = (RealmService) PrivilegedCarbonContext
.getThreadLocalCarbonContext().getOSGiService(RealmService.class);
ThreadLocalProvisioningServiceProvider serviceProvider = new ThreadLocalProvisioningServiceProvider();
serviceProvider.setServiceProviderName(validationApp.getConsumerKey());
serviceProvider
.setServiceProviderType(ProvisioningServiceProviderType.OAUTH);
serviceProvider.setClaimDialect(SCIMProviderConstants.DEFAULT_SCIM_DIALECT);
serviceProvider.setTenantDomain(MultitenantUtils.getTenantDomain(userName));
IdentityApplicationManagementUtil
.setThreadLocalProvisioningServiceProvider(serviceProvider);
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String tenantDomain = MultitenantUtils.getTenantDomain(userName);
carbonContext.setUsername(MultitenantUtils.getTenantAwareUsername(userName));
carbonContext.setTenantId(realmService.getTenantManager().getTenantId(tenantDomain));
carbonContext.setTenantDomain(tenantDomain);
return true;
}
} catch (Exception e) {
String error = "Error in validating OAuth access token.";
log.error(error, e);
}
}
return false;
}
示例20
private OAuth2ClientApplicationDTO validateAccessToken(String accessTokenIdentifier)
throws Exception {
// if it is specified to use local authz server (i.e: local://services)
if (remoteServiceURL.startsWith(LOCAL_PREFIX)) {
OAuth2TokenValidationRequestDTO oauthValidationRequest = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken = oauthValidationRequest.new OAuth2AccessToken();
accessToken.setTokenType(OAuthServiceClient.BEARER_TOKEN_TYPE);
accessToken.setIdentifier(accessTokenIdentifier);
oauthValidationRequest.setAccessToken(accessToken);
OAuth2TokenValidationService oauthValidationService = new OAuth2TokenValidationService();
OAuth2ClientApplicationDTO oauthValidationResponse = oauthValidationService
.findOAuthConsumerIfTokenIsValid(oauthValidationRequest);
return oauthValidationResponse;
}
// else do a web service call to the remote authz server
try {
ConfigurationContext configContext = ConfigurationContextFactory
.createConfigurationContextFromFileSystem(null, null);
OAuthServiceClient oauthClient = new OAuthServiceClient(getOAuthAuthzServerURL(),
userName, password, configContext);
org.wso2.carbon.identity.oauth2.stub.dto.OAuth2ClientApplicationDTO validationResponse;
validationResponse = oauthClient.findOAuthConsumerIfTokenIsValid(accessTokenIdentifier);
OAuth2ClientApplicationDTO appDTO = new OAuth2ClientApplicationDTO();
appDTO.setConsumerKey(validationResponse.getConsumerKey());
OAuth2TokenValidationResponseDTO validationDto = new OAuth2TokenValidationResponseDTO();
validationDto.setAuthorizedUser(validationResponse.getAccessTokenValidationResponse()
.getAuthorizedUser());
validationDto
.setValid(validationResponse.getAccessTokenValidationResponse().getValid());
appDTO.setAccessTokenValidationResponse(validationDto);
return appDTO;
} catch (AxisFault axisFault) {
throw axisFault;
} catch (Exception exception) {
throw exception;
}
}
示例21
public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
AccessTokenInfo tokenInfo = new AccessTokenInfo();
OAuth2TokenValidationRequestDTO requestDTO = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO.OAuth2AccessToken token = requestDTO.new OAuth2AccessToken();
token.setIdentifier(accessToken);
token.setTokenType("bearer");
requestDTO.setAccessToken(token);
OAuth2TokenValidationRequestDTO.TokenValidationContextParam[] contextParams =
new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1];
requestDTO.setContext(contextParams);
OAuth2ClientApplicationDTO clientApplicationDTO = findOAuthConsumerIfTokenIsValid(requestDTO);
OAuth2TokenValidationResponseDTO responseDTO = clientApplicationDTO.getAccessTokenValidationResponse();
if (!responseDTO.isValid()) {
tokenInfo.setTokenValid(responseDTO.isValid());
log.error("Invalid OAuth Token : " + responseDTO.getErrorMsg());
tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
return tokenInfo;
}
tokenInfo.setTokenValid(responseDTO.isValid());
tokenInfo.setEndUserName(responseDTO.getAuthorizedUser());
tokenInfo.setConsumerKey(clientApplicationDTO.getConsumerKey());
// Convert Expiry Time to milliseconds.
if (responseDTO.getExpiryTime() == Long.MAX_VALUE) {
tokenInfo.setValidityPeriod(Long.MAX_VALUE);
} else {
tokenInfo.setValidityPeriod(responseDTO.getExpiryTime() * 1000L);
}
tokenInfo.setIssuedTime(System.currentTimeMillis());
tokenInfo.setScope(responseDTO.getScope());
// If token has am_application_scope, consider the token as an Application token.
String[] scopes = responseDTO.getScope();
String applicationTokenScope = getConfigurationElementValue(APIConstants.APPLICATION_TOKEN_SCOPE);
if (scopes != null && applicationTokenScope != null && !applicationTokenScope.isEmpty()) {
if (Arrays.asList(scopes).contains(applicationTokenScope)) {
tokenInfo.setApplicationToken(true);
}
}
return tokenInfo;
}
示例22
/**
* @param tokenResponse
* @return
* @throws org.apache.oltu.oauth2.common.exception.OAuthSystemException
* @throws org.apache.oltu.oauth2.common.exception.OAuthProblemException TODO
*/
public String getResponseString(OAuth2TokenValidationResponseDTO tokenResponse)
throws UserInfoEndpointException, OAuthSystemException;
示例23
/**
* Validates the access token and returns the token info
*
* @param accessToken
* @return
* @throws UserInfoEndpointException
*/
public OAuth2TokenValidationResponseDTO validateToken(String accessToken)
throws UserInfoEndpointException;