use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.
the class OpenAMTokenStore method createAccessToken.
/**
* {@inheritDoc}
*/
public AccessToken createAccessToken(String grantType, String accessTokenType, String authorizationCode, String resourceOwnerId, String clientId, String redirectUri, Set<String> scope, RefreshToken refreshToken, String nonce, String claims, OAuth2Request request) throws ServerException, NotFoundException {
OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
final String id = UUID.randomUUID().toString();
final String auditId = UUID.randomUUID().toString();
String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
long expiryTime = 0;
if (clientRegistration == null) {
expiryTime = providerSettings.getAccessTokenLifetime() + System.currentTimeMillis();
} else {
expiryTime = clientRegistration.getAccessTokenLifeTime(providerSettings) + System.currentTimeMillis();
}
final AccessToken accessToken;
if (refreshToken == null) {
accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, null, OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
} else {
accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, refreshToken.getTokenId(), OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
}
try {
tokenStore.create(accessToken);
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "CREATED_TOKEN", accessToken.toString() };
auditLogger.logAccessMessage("CREATED_TOKEN", obs, null);
}
} catch (CoreTokenException e) {
logger.error("Could not create token in CTS: " + e.getMessage());
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_TOKEN", accessToken.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_TOKEN", obs, null);
}
throw new ServerException("Could not create token in CTS: " + e.getMessage());
}
request.setToken(AccessToken.class, accessToken);
return accessToken;
}
use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.
the class OpenAMTokenStore method appendRequestedIdTokenClaims.
//See spec section 5.5. - add claims to id_token based on 'claims' parameter in the access token
private void appendRequestedIdTokenClaims(OAuth2Request request, OAuth2ProviderSettings providerSettings, OpenAMOpenIdConnectToken oidcToken) throws ServerException, NotFoundException, InvalidClientException {
AccessToken accessToken = request.getToken(AccessToken.class);
String claims;
if (accessToken != null) {
claims = (String) accessToken.toMap().get(OAuth2Constants.Custom.CLAIMS);
} else {
claims = request.getParameter(OAuth2Constants.Custom.CLAIMS);
}
if (claims != null) {
try {
JSONObject claimsObject = new JSONObject(claims);
JSONObject idTokenClaimsRequest = claimsObject.getJSONObject(OAuth2Constants.JWTTokenParams.ID_TOKEN);
Map<String, Object> userInfo = providerSettings.getUserInfo(accessToken, request).getValues();
Iterator<String> it = idTokenClaimsRequest.keys();
while (it.hasNext()) {
String keyName = it.next();
if (userInfo.containsKey(keyName)) {
oidcToken.put(keyName, userInfo.get(keyName));
}
}
} catch (UnauthorizedClientException e) {
throw failureFactory.getException(request, e.getMessage());
} catch (JSONException e) {
//if claims object not found, fall through
}
}
}
use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.
the class DeviceCodeGrantTypeHandlerTest method setup.
@BeforeMethod
public void setup() throws Exception {
initMocks(this);
OAuth2ProviderSettingsFactory providerSettingsFactory = mock(OAuth2ProviderSettingsFactory.class);
when(providerSettingsFactory.get(request)).thenReturn(providerSettings);
when(providerSettings.getDeviceCodePollInterval()).thenReturn(5);
when(providerSettings.validateRequestedClaims(anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return (String) invocation.getArguments()[0];
}
});
OAuth2UrisFactory oAuth2UrisFactory = mock(OAuth2UrisFactory.class);
when(oAuth2UrisFactory.get(request)).thenReturn(oAuth2Uris);
ClientAuthenticator clientAuthenticator = mock(ClientAuthenticator.class);
ClientRegistration clientRegistration = mock(ClientRegistration.class);
when(clientAuthenticator.authenticate(eq(request), anyString())).thenReturn(clientRegistration);
accessTokenGenerator = new GrantTypeAccessTokenGenerator(tokenStore);
when(tokenStore.createAccessToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anySetOf(String.class), any(RefreshToken.class), anyString(), anyString(), any(OAuth2Request.class))).thenReturn(accessToken);
when(tokenStore.createRefreshToken(anyString(), anyString(), anyString(), anyString(), anySetOf(String.class), any(OAuth2Request.class), anyString())).thenReturn(refreshToken);
ClientAuthenticationFailureFactory failureFactory = mock(ClientAuthenticationFailureFactory.class);
InvalidClientException expectedResult = mock(InvalidClientException.class);
when(expectedResult.getError()).thenReturn("invalid_client");
when(failureFactory.getException()).thenReturn(expectedResult);
when(failureFactory.getException(anyString())).thenReturn(expectedResult);
when(failureFactory.getException(any(OAuth2Request.class), anyString())).thenReturn(expectedResult);
grantTypeHandler = new DeviceCodeGrantTypeHandler(providerSettingsFactory, clientAuthenticator, tokenStore, clientRegistrationStore, failureFactory, oAuth2UrisFactory, accessTokenGenerator);
}
use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.
the class AccessTokenProtectionFilter method beforeHandle.
@Override
protected int beforeHandle(Request request, Response response) {
ChallengeResponse challengeResponse = request.getChallengeResponse();
Status failure = null;
if (challengeResponse == null) {
failure = new Status(401, new InvalidTokenException());
} else {
String tokenId = challengeResponse.getRawValue();
try {
OAuth2Request oAuth2Request = requestFactory.create(request);
AccessToken accessToken = tokenStore.readAccessToken(oAuth2Request, tokenId);
if (accessToken == null || accessToken.isExpired()) {
failure = new Status(401, new InvalidTokenException());
} else if (requiredScope != null && !accessToken.getScope().contains(requiredScope)) {
failure = new Status(403, new InsufficientScopeException(requiredScope));
} else {
oAuth2Request.setToken(AccessToken.class, accessToken);
}
} catch (ServerException e) {
failure = new Status(500, e);
} catch (NotFoundException e) {
debug.message("Error loading token with id: " + tokenId, e);
failure = new Status(404, e);
} catch (InvalidGrantException e) {
debug.message("Error loading token with id: " + tokenId, e);
failure = new Status(401, new InvalidTokenException());
}
}
if (failure != null) {
response.setStatus(failure);
return STOP;
}
return super.beforeHandle(request, response);
}
use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.
the class OpenAMScopeValidator method evaluateScope.
/**
* {@inheritDoc}
*/
public Map<String, Object> evaluateScope(AccessToken accessToken) {
final Map<String, Object> map = new HashMap<String, Object>();
final Set<String> scopes = accessToken.getScope();
if (scopes.isEmpty()) {
return map;
}
final String resourceOwner = accessToken.getResourceOwnerId();
final String clientId = accessToken.getClientId();
final String realm = accessToken.getRealm();
AMIdentity id = null;
try {
if (clientId != null && CLIENT_CREDENTIALS.equals(accessToken.getGrantType())) {
id = identityManager.getClientIdentity(clientId, realm);
} else if (resourceOwner != null) {
id = identityManager.getResourceOwnerIdentity(resourceOwner, realm);
}
} catch (Exception e) {
logger.error("Unable to get user identity", e);
}
if (id != null) {
for (String scope : scopes) {
try {
Set<String> attributes = id.getAttribute(scope);
StringBuilder builder = new StringBuilder();
if (CollectionUtils.isNotEmpty(attributes)) {
Iterator<String> iter = attributes.iterator();
while (iter.hasNext()) {
builder.append(iter.next());
if (iter.hasNext()) {
builder.append(MULTI_ATTRIBUTE_SEPARATOR);
}
}
}
map.put(scope, builder.toString());
} catch (Exception e) {
logger.error("Unable to get attribute", e);
}
}
}
return map;
}
Aggregations