use of org.forgerock.oauth2.core.ResourceOwner in project OpenAM by OpenRock.
the class OpenAMResourceOwnerSessionValidator method validate.
/**
* {@inheritDoc}
*/
public ResourceOwner validate(OAuth2Request request) throws ResourceOwnerAuthenticationRequired, AccessDeniedException, BadRequestException, InteractionRequiredException, LoginRequiredException, ServerException, NotFoundException {
final OpenIdPrompt openIdPrompt = new OpenIdPrompt(request);
if (!openIdPrompt.isValid()) {
String message = "Invalid prompt parameter \"" + openIdPrompt.getOriginalValue() + "\"";
logger.message(message);
throw new BadRequestException(message);
}
SSOToken token = null;
try {
token = ssoTokenManager.createSSOToken(getHttpServletRequest(request.<Request>getRequest()));
} catch (SSOException e) {
logger.warning("Error authenticating user against OpenAM: ", e);
}
try {
if (token == null) {
token = ssoTokenManager.createSSOToken(request.getSession());
}
} catch (SSOException e) {
logger.warning("Error authenticating user against OpenAM: ", e);
}
try {
if (token != null) {
try {
// As the organization in the token is stored in lowercase, we need to lower case the auth2realm
String auth2Realm = dnWrapper.orgNameToDN(realmNormaliser.normalise((String) request.getParameter("realm"))).toLowerCase();
String tokenRealm = token.getProperty("Organization");
// auth2Realm can't be null as we would have an error earlier
if (!auth2Realm.equals(tokenRealm)) {
throw authenticationRequired(request);
}
} catch (SSOException e) {
throw new AccessDeniedException(e);
}
if (openIdPrompt.containsLogin()) {
throw authenticationRequired(request, token);
}
final String acrValuesStr = request.getParameter(ACR_VALUES);
if (acrValuesStr != null) {
setCurrentAcr(token, request, acrValuesStr);
}
try {
final long authTime = stringToDate(token.getProperty(ISAuthConstants.AUTH_INSTANT)).getTime();
if (isPastMaxAge(getMaxAge(request), authTime)) {
alterMaxAge(request);
throw authenticationRequired(request, token);
}
final AMIdentity id = IdUtils.getIdentity(AccessController.doPrivileged(AdminTokenAction.getInstance()), token.getProperty(Constants.UNIVERSAL_IDENTIFIER));
return new OpenAMResourceOwner(id.getName(), id, authTime);
} catch (Exception e) {
//Exception as chance of MANY exception types here.
logger.error("Error authenticating user against OpenAM: ", e);
throw new LoginRequiredException();
}
} else if (PASSWORD.equals(request.getParameter(GRANT_TYPE))) {
// been null from the attempted creation in L148.
return getResourceOwner(request.getToken(AccessToken.class));
} else {
if (openIdPrompt.containsNone()) {
logger.error("Not pre-authenticated and prompt parameter equals none.");
if (request.getParameter(OAuth2Constants.Params.RESPONSE_TYPE) != null) {
throw new InteractionRequiredException(Utils.isOpenIdConnectFragmentErrorType(splitResponseType(request.<String>getParameter(RESPONSE_TYPE))) ? FRAGMENT : QUERY);
} else {
throw new InteractionRequiredException();
}
} else if (!isRefreshToken(request)) {
throw authenticationRequired(request);
} else {
return getResourceOwner(request.getToken(RefreshToken.class));
}
}
} catch (SSOException | UnsupportedEncodingException | URISyntaxException e) {
throw new AccessDeniedException(e);
}
}
use of org.forgerock.oauth2.core.ResourceOwner in project OpenAM by OpenRock.
the class OpenAMResourceOwnerAuthenticator method authenticate.
private ResourceOwner authenticate(String username, char[] password, String realm, String service) {
ResourceOwner ret = null;
AuthContext lc = null;
try {
lc = new AuthContext(realm);
if (service != null) {
lc.login(AuthContext.IndexType.SERVICE, service, null, ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
} else {
lc.login(ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
}
while (lc.hasMoreRequirements()) {
Callback[] callbacks = lc.getRequirements();
ArrayList missing = new ArrayList();
// loop through the requires setting the needs..
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) callbacks[i];
nc.setName(username);
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword(password);
} else {
missing.add(callbacks[i]);
}
}
// there's missing requirements not filled by this
if (missing.size() > 0) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Missing requirements");
}
lc.submitRequirements(callbacks);
}
// validate the password..
if (lc.getStatus() == AuthContext.Status.SUCCESS) {
try {
// package up the token for transport..
ret = createResourceOwner(lc);
} catch (Exception e) {
logger.error("Unable to get SSOToken", e);
// because the system is likely down..
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
}
}
} catch (AuthLoginException le) {
logger.error("AuthException", le);
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, le);
} finally {
if (lc != null && AuthContext.Status.SUCCESS.equals(lc.getStatus())) {
try {
lc.logout();
logger.message("Logged user out.");
} catch (AuthLoginException e) {
logger.error("Exception caught logging out of AuthContext after successful login", e);
}
}
}
return ret;
}
use of org.forgerock.oauth2.core.ResourceOwner 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;
}
use of org.forgerock.oauth2.core.ResourceOwner 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.ResourceOwner in project OpenAM by OpenRock.
the class AuthorizationRequestEndpoint method requestAuthorization.
@Post
public Representation requestAuthorization(JsonRepresentation entity) throws BadRequestException, UmaException, EntitlementException, ServerException, NotFoundException {
UmaProviderSettings umaProviderSettings = umaProviderSettingsFactory.get(this.getRequest());
final OAuth2Request oauth2Request = requestFactory.create(getRequest());
OAuth2ProviderSettings oauth2ProviderSettings = oauth2ProviderSettingsFactory.get(oauth2Request);
OAuth2Uris oAuth2Uris = oAuth2UrisFactory.get(oauth2Request);
final UmaTokenStore umaTokenStore = umaProviderSettings.getUmaTokenStore();
String realm = oauth2Request.getParameter("realm");
JsonValue requestBody = json(toMap(entity));
PermissionTicket permissionTicket = getPermissionTicket(umaTokenStore, requestBody);
validatePermissionTicketHolder(umaTokenStore, permissionTicket);
final String resourceSetId = permissionTicket.getResourceSetId();
final Request request = getRequest();
final String resourceOwnerId = getResourceOwnerId(oauth2ProviderSettings, resourceSetId);
AMIdentity resourceOwner = createIdentity(resourceOwnerId, realm);
String requestingPartyId = null;
try {
requestingPartyId = getRequestingPartyId(umaProviderSettings, oAuth2Uris, requestBody);
} finally {
auditLogger.log(resourceSetId, resourceOwner, UmaAuditType.REQUEST, request, requestingPartyId == null ? getAuthorisationApiToken().getResourceOwnerId() : requestingPartyId);
}
if (isEntitled(umaProviderSettings, oauth2ProviderSettings, permissionTicket, requestingPartyId)) {
getResponse().setStatus(new Status(200));
auditLogger.log(resourceSetId, resourceOwner, UmaAuditType.GRANTED, request, requestingPartyId);
return createJsonRpt(umaTokenStore, permissionTicket);
} else {
try {
if (verifyPendingRequestDoesNotAlreadyExist(resourceSetId, resourceOwnerId, permissionTicket.getRealm(), requestingPartyId, permissionTicket.getScopes())) {
auditLogger.log(resourceSetId, resourceOwner, UmaAuditType.DENIED, request, requestingPartyId);
throw new UmaException(403, UmaConstants.NOT_AUTHORISED_ERROR_CODE, "The client is not authorised to access the requested resource set");
} else {
pendingRequestsService.createPendingRequest(ServletUtils.getRequest(getRequest()), resourceSetId, auditLogger.getResourceName(resourceSetId, request), resourceOwnerId, requestingPartyId, permissionTicket.getRealm(), permissionTicket.getScopes());
auditLogger.log(resourceSetId, resourceOwner, UmaAuditType.REQUEST_SUBMITTED, request, requestingPartyId);
}
} catch (org.forgerock.openam.sm.datalayer.store.ServerException e) {
logger.error("Failed to create pending request", e);
throw new UmaException(403, UmaConstants.NOT_AUTHORISED_ERROR_CODE, "Failed to create pending request");
}
throw newRequestSubmittedException();
}
}
Aggregations