use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class TokenResource method queryCollection.
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest queryRequest, QueryResourceHandler handler) {
try {
JsonValue response;
Collection<QueryFilter<CoreTokenField>> query = new ArrayList<QueryFilter<CoreTokenField>>();
//get uid of submitter
AMIdentity uid;
try {
uid = getUid(context);
if (!uid.equals(adminUserId)) {
query.add(QueryFilter.equalTo(USERNAME_FIELD, uid.getName()));
query.add(QueryFilter.equalTo(REALM_FIELD, DNMapper.orgNameToRealmName(uid.getRealm())));
}
} catch (Exception e) {
if (debug.errorEnabled()) {
debug.error("TokenResource :: QUERY : Unable to query collection as no UID discovered " + "for requesting user.");
}
return new PermanentException(401, "Unauthorized", e).asPromise();
}
String id = queryRequest.getQueryId();
String queryString;
if (id.equals("access_token")) {
queryString = "tokenName=access_token";
} else {
queryString = id;
}
String[] constraints = queryString.split(",");
boolean userNamePresent = false;
for (String constraint : constraints) {
String[] params = constraint.split("=");
if (params.length == 2) {
if (OAuthTokenField.USER_NAME.getOAuthField().equals(params[0])) {
userNamePresent = true;
}
query.add(QueryFilter.equalTo(getOAuth2TokenField(params[0]), params[1]));
}
}
if (adminUserId.equals(uid)) {
if (!userNamePresent) {
return new BadRequestException("userName field MUST be set in _queryId").asPromise();
}
} else if (userNamePresent) {
return new BadRequestException("userName field MUST NOT be set in _queryId").asPromise();
}
response = tokenStore.query(QueryFilter.and(query));
return handleResponse(handler, response, context);
} catch (UnauthorizedClientException e) {
debug.error("TokenResource :: QUERY : Unable to query collection as the client is not authorized.", e);
return new PermanentException(401, e.getMessage(), e).asPromise();
} catch (CoreTokenException e) {
debug.error("TokenResource :: QUERY : Unable to query collection as the token store is not available.", e);
return new ServiceUnavailableException(e.getMessage(), e).asPromise();
} catch (InternalServerErrorException e) {
debug.error("TokenResource :: QUERY : Unable to query collection as writing the response failed.", e);
return e.asPromise();
} catch (NotFoundException e) {
debug.error("TokenResource :: QUERY : Unable to query collection as realm does not have OAuth 2 provider.", e);
return e.asPromise();
}
}
use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class TokenResource method readInstance.
@Override
public Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request) {
try {
AMIdentity uid = getUid(context);
JsonValue response;
ResourceResponse resource;
try {
response = tokenStore.read(resourceId);
} catch (CoreTokenException e) {
if (debug.errorEnabled()) {
debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
}
throw new NotFoundException("Could not find valid token with given ID", e);
}
if (response == null) {
if (debug.errorEnabled()) {
debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
}
throw new NotFoundException("Could not find valid token with given ID");
}
JsonValue expireTimeValue = response.get(OAuth2Constants.CoreTokenParams.EXPIRE_TIME);
long expireTime;
if (expireTimeValue.isNumber()) {
expireTime = expireTimeValue.asLong();
} else {
Set<String> expireTimeSet = (Set<String>) expireTimeValue.getObject();
expireTime = Long.parseLong(expireTimeSet.iterator().next());
}
if (System.currentTimeMillis() > expireTime) {
throw new NotFoundException("Could not find valid token with given ID");
}
String grantType = getAttributeValue(response, GRANT_TYPE);
if (grantType != null && grantType.equalsIgnoreCase(OAuth2Constants.TokenEndpoint.CLIENT_CREDENTIALS)) {
resource = newResourceResponse(OAuth2Constants.Params.ID, String.valueOf(System.currentTimeMillis()), response);
return newResultPromise(resource);
} else {
String realm = getAttributeValue(response, REALM);
String username = getAttributeValue(response, USERNAME);
if (username == null || username.isEmpty()) {
if (debug.errorEnabled()) {
debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
}
throw new NotFoundException("Could not find valid token with given ID");
}
AMIdentity uid2 = identityManager.getResourceOwnerIdentity(username, realm);
if (uid.equals(adminUserId) || uid.equals(uid2)) {
resource = newResourceResponse(OAuth2Constants.Params.ID, String.valueOf(System.currentTimeMillis()), response);
return newResultPromise(resource);
} else {
if (debug.errorEnabled()) {
debug.error("TokenResource :: READ : Only the resource owner or an administrator may perform " + "a read on the token with ID, " + resourceId + ".");
}
throw new PermanentException(401, "Unauthorized", null);
}
}
} catch (ResourceException e) {
return e.asPromise();
} catch (SSOException e) {
debug.error("TokenResource :: READ : Unable to query collection as the IdRepo " + "failed to return a valid user.", e);
return new PermanentException(401, "Unauthorized", e).asPromise();
} catch (IdRepoException e) {
debug.error("TokenResource :: READ : Unable to query collection as the IdRepo " + "failed to return a valid user.", e);
return new PermanentException(401, "Unauthorized", e).asPromise();
} catch (UnauthorizedClientException e) {
debug.error("TokenResource :: READ : Unable to query collection as the client is not authorized.", e);
return new PermanentException(401, "Unauthorized", e).asPromise();
}
}
use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class TokenResponseType method createToken.
public CoreToken createToken(Token accessToken, Map<String, Object> data) throws NotFoundException {
final String tokenType = (String) data.get(OAuth2Constants.CoreTokenParams.TOKEN_TYPE);
final Set<String> scope = (Set<String>) data.get(OAuth2Constants.CoreTokenParams.SCOPE);
final OAuth2Request request = requestFactory.create(Request.getCurrent());
final ResourceOwner resourceOwner = ownerAuthenticator.authenticate(request, true);
final String clientId = (String) data.get(OAuth2Constants.CoreTokenParams.CLIENT_ID);
final String redirectUri = (String) data.get(OAuth2Constants.CoreTokenParams.REDIRECT_URI);
final String codeChallenge = (String) data.get(OAuth2Constants.Custom.CODE_CHALLENGE);
final String codeChallengeMethod = (String) data.get(OAuth2Constants.Custom.CODE_CHALLENGE_METHOD);
try {
final Map.Entry<String, Token> tokenEntry = handler.handle(tokenType, scope, resourceOwner, clientId, redirectUri, null, requestFactory.create(Request.getCurrent()), codeChallenge, codeChallengeMethod);
return new LegacyAccessTokenAdapter((AccessToken) tokenEntry.getValue());
} catch (ServerException e) {
throw OAuthProblemException.OAuthError.SERVER_ERROR.handle(Request.getCurrent(), e.getMessage());
}
}
use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class CheckSessionImpl method getValidSession.
/**
* {@inheritDoc}
*/
public boolean getValidSession(HttpServletRequest request) {
SignedJwt jwt = getIDToken(request);
if (jwt == null) {
return false;
}
try {
final ClientRegistration clientRegistration = getClientRegistration(jwt);
if (clientRegistration != null && !isJwtValid(jwt, clientRegistration)) {
return false;
}
String opsId = (String) jwt.getClaimsSet().getClaim(OPS);
if (opsId == null) {
opsId = (String) jwt.getClaimsSet().getClaim(LEGACY_OPS);
}
JsonValue idTokenUserSessionToken = tokenAdapter.fromToken(cts.read(opsId));
String sessionId = idTokenUserSessionToken.get(LEGACY_OPS).asString();
SSOToken ssoToken = ssoTokenManager.createSSOToken(sessionId);
return ssoTokenManager.isValidToken(ssoToken);
} catch (Exception e) {
logger.error("Unable to get the SSO token", e);
return false;
}
}
use of org.forgerock.oauth2.core.Token in project OpenAM by OpenRock.
the class OpenAMOpenIDConnectProvider method destroySession.
/**
* {@inheritDoc}
*/
public void destroySession(String opsId) throws ServerException {
try {
final Token opsToken = cts.read(opsId);
if (opsToken == null) {
throw new CoreTokenException("Unable to find id_token");
}
JsonValue idTokenUserSessionToken = tokenAdapter.fromToken(opsToken);
cts.delete(opsId);
String sessionId = idTokenUserSessionToken.get(OAuth2Constants.JWTTokenParams.LEGACY_OPS).asSet(String.class).iterator().next();
// for some grant type, there is no OpenAM session associated with a id_token
if (sessionId != null) {
final SSOToken token = tokenManager.createSSOToken(sessionId);
tokenManager.destroyToken(token);
}
} catch (CoreTokenException e) {
logger.error("Unable to get id_token meta data", e);
throw new ServerException("Unable to get id_token meta data");
} catch (Exception e) {
logger.error("Unable to get SsoTokenManager", e);
throw new ServerException("Unable to get SsoTokenManager");
}
}
Aggregations