use of org.forgerock.oauth2.core.exceptions.NotFoundException in project OpenAM by OpenRock.
the class OpenAMTokenStoreTest method shouldFailWhenNoProvider.
@Test(expectedExceptions = NotFoundException.class)
public void shouldFailWhenNoProvider() throws Exception {
//Given
OAuth2Request request = oAuth2RequestFactory.create(this.request);
doThrow(NotFoundException.class).when(providerSettingsFactory).get(request);
//When
openAMtokenStore.createAccessToken(null, null, null, null, null, null, null, null, null, null, request);
//Then
//Expected NotFoundException
}
use of org.forgerock.oauth2.core.exceptions.NotFoundException in project OpenAM by OpenRock.
the class Saml2GrantTypeHandler method handle.
public AccessToken handle(OAuth2Request request) throws InvalidGrantException, InvalidClientException, InvalidRequestException, ServerException, InvalidScopeException, NotFoundException {
String clientId = request.getParameter(OAuth2Constants.Params.CLIENT_ID);
Reject.ifTrue(isEmpty(clientId), "Missing parameter, 'client_id'");
final ClientRegistration clientRegistration = clientRegistrationStore.get(clientId, request);
Reject.ifTrue(isEmpty(request.<String>getParameter("assertion")), "Missing parameter, 'assertion'");
final String assertion = request.getParameter(OAuth2Constants.SAML20.ASSERTION);
logger.trace("Assertion:\n" + assertion);
final byte[] decodedAssertion = Base64.decode(assertion.replace(" ", "+"));
if (decodedAssertion == null) {
logger.error("Decoding assertion failed\nassertion:" + assertion);
}
final String finalAssertion = new String(decodedAssertion);
logger.trace("Decoded assertion:\n" + finalAssertion);
final Assertion assertionObject;
final boolean valid;
try {
final AssertionFactory factory = AssertionFactory.getInstance();
assertionObject = factory.createAssertion(finalAssertion);
valid = validAssertion(assertionObject, getDeploymentUrl(request));
} catch (SAML2Exception e) {
logger.error("Error parsing assertion", e);
throw new InvalidGrantException("Assertion is invalid");
}
if (!valid) {
logger.error("Error parsing assertion");
throw new InvalidGrantException("Assertion is invalid.");
}
logger.trace("Assertion is valid");
final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
final String validatedClaims = providerSettings.validateRequestedClaims((String) request.getParameter(OAuth2Constants.Custom.CLAIMS));
final String grantType = request.getParameter(OAuth2Constants.Params.GRANT_TYPE);
final Set<String> scope = splitScope(request.<String>getParameter(OAuth2Constants.Params.SCOPE));
final Set<String> validatedScope = providerSettings.validateAccessTokenScope(clientRegistration, scope, request);
logger.trace("Granting scope: " + validatedScope.toString());
logger.trace("Creating token with data: " + clientRegistration.getAccessTokenType() + "\n" + validatedScope.toString() + "\n" + normaliseRealm(request.<String>getParameter(OAuth2Constants.Params.REALM)) + "\n" + assertionObject.getSubject().getNameID().getValue() + "\n" + clientRegistration.getClientId());
final AccessToken accessToken = tokenStore.createAccessToken(grantType, BEARER, null, assertionObject.getSubject().getNameID().getValue(), clientRegistration.getClientId(), null, validatedScope, null, null, validatedClaims, request);
logger.trace("Token created: " + accessToken.toString());
providerSettings.additionalDataToReturnFromTokenEndpoint(accessToken, request);
if (validatedScope != null && !validatedScope.isEmpty()) {
accessToken.put(SCOPE, joinScope(validatedScope));
}
tokenStore.updateAccessToken(accessToken);
return accessToken;
}
use of org.forgerock.oauth2.core.exceptions.NotFoundException in project OpenAM by OpenRock.
the class ClientAuthenticatorImpl method authenticate.
/**
* {@inheritDoc}
*/
public ClientRegistration authenticate(OAuth2Request request, String endpoint) throws InvalidClientException, InvalidRequestException, NotFoundException {
final ClientCredentials clientCredentials = clientCredentialsReader.extractCredentials(request, endpoint);
Reject.ifTrue(isEmpty(clientCredentials.getClientId()), "Missing parameter, 'client_id'");
final String realm = realmNormaliser.normalise(request.<String>getParameter(OAuth2Constants.Custom.REALM));
boolean authenticated = false;
try {
final ClientRegistration clientRegistration = clientRegistrationStore.get(clientCredentials.getClientId(), request);
// Do not need to authenticate public clients
if (!clientRegistration.isConfidential()) {
return clientRegistration;
}
if (!clientCredentials.isAuthenticated() && !authenticate(request, clientCredentials.getClientId(), clientCredentials.getClientSecret(), realm)) {
logger.error("ClientVerifierImpl::Unable to verify password for: " + clientCredentials.getClientId());
throw failureFactory.getException(request, "Client authentication failed");
}
authenticated = true;
return clientRegistration;
} finally {
if (auditLogger.isAuditLogEnabled()) {
if (authenticated) {
String[] obs = { clientCredentials.getClientId() };
auditLogger.logAccessMessage("AUTHENTICATED_CLIENT", obs, null);
} else {
String[] obs = { clientCredentials.getClientId() };
auditLogger.logErrorMessage("FAILED_AUTHENTICATE_CLIENT", obs, null);
}
}
}
}
use of org.forgerock.oauth2.core.exceptions.NotFoundException in project OpenAM by OpenRock.
the class ClientCredentialsReader method extractCredentials.
/**
* Extracts the client's credentials from the OAuth2 request.
*
* @param request The OAuth2 request.
* @param endpoint The endpoint this request should be for, or null to disable audience verification.
* @return The client's credentials.
* @throws InvalidRequestException If the request contains multiple client credentials.
* @throws InvalidClientException If the request does not contain the client's id.
*/
public ClientCredentials extractCredentials(OAuth2Request request, String endpoint) throws InvalidRequestException, InvalidClientException, NotFoundException {
final Request req = request.getRequest();
boolean basicAuth = false;
if (req.getChallengeResponse() != null) {
basicAuth = true;
}
final ClientCredentials client;
Client.TokenEndpointAuthMethod method = CLIENT_SECRET_POST;
//jwt type first
if (JWT_PROFILE_CLIENT_ASSERTION_TYPE.equalsIgnoreCase(request.<String>getParameter(CLIENT_ASSERTION_TYPE))) {
client = verifyJwtBearer(request, basicAuth, endpoint);
method = PRIVATE_KEY_JWT;
} else {
String clientId = request.getParameter(OAuth2Constants.Params.CLIENT_ID);
String clientSecret = request.getParameter(OAuth2Constants.Params.CLIENT_SECRET);
if (basicAuth && clientId != null) {
logger.error("Client (" + clientId + ") using multiple authentication methods");
throw new InvalidRequestException("Client authentication failed");
}
if (req.getChallengeResponse() != null) {
final ChallengeResponse challengeResponse = req.getChallengeResponse();
clientId = challengeResponse.getIdentifier();
clientSecret = "";
if (challengeResponse.getSecret() != null && challengeResponse.getSecret().length > 0) {
clientSecret = String.valueOf(req.getChallengeResponse().getSecret());
}
method = CLIENT_SECRET_BASIC;
}
if (clientId == null || clientId.isEmpty()) {
logger.error("Client Id is not set");
throw failureFactory.getException(request, "Client authentication failed");
}
client = new ClientCredentials(clientId, clientSecret == null ? null : clientSecret.toCharArray(), false, basicAuth);
}
final OpenIdConnectClientRegistration cr = clientRegistrationStore.get(client.getClientId(), request);
final Set<String> scopes = cr.getAllowedScopes();
//if we're accessing the token endpoint, check we're authenticating using the appropriate method
if (scopes.contains(OAuth2Constants.Params.OPENID) && req.getResourceRef().getLastSegment().equals(OAuth2Constants.Params.ACCESS_TOKEN) && !cr.getTokenEndpointAuthMethod().equals(method.getType())) {
throw failureFactory.getException(request, "Invalid authentication method for accessing this endpoint.");
}
return client;
}
use of org.forgerock.oauth2.core.exceptions.NotFoundException in project OpenAM by OpenRock.
the class OpenIDConnectProviderDiscovery method discover.
/**
* Returns the response to a request to discover the OpenId Connect provider.
*
* @param resource The resource.
* @param rel The rel.
* @param deploymentUrl The deployment url of the OpenId Connect provider.
* @param request The OAuth2 request.
* @return A {@code Map} of the OpenId Connect provider urls.
* @throws BadRequestException If the request is malformed.
* @throws NotFoundException If the user cannot be found.
*/
public Map<String, Object> discover(String resource, String rel, String deploymentUrl, OAuth2Request request) throws BadRequestException, NotFoundException {
if (resource == null || resource.isEmpty()) {
logger.error("No resource provided in discovery.");
throw new BadRequestException("No resource provided in discovery.");
}
if (rel == null || rel.isEmpty() || !rel.equalsIgnoreCase("http://openid.net/specs/connect/1.0/issuer")) {
logger.error("No or invalid rel provided in discovery.");
throw new BadRequestException("No or invalid rel provided in discovery.");
}
String userid = null;
//test if the resource is a uri
try {
final URI object = new URI(resource);
if (object.getScheme().equalsIgnoreCase("https") || object.getScheme().equalsIgnoreCase("http")) {
//resource is of the form of https://example.com/
if (!object.getPath().isEmpty()) {
//resource is of the form of https://example.com/joe
userid = object.getPath();
userid = userid.substring(1, userid.length());
}
} else if (object.getScheme().equalsIgnoreCase("acct")) {
//resource is not uri so only option is it is an email of form acct:joe@example.com
String s = new String(resource);
s = s.replaceFirst("acct:", "");
final int firstAt = s.indexOf('@');
userid = s.substring(0, firstAt);
} else {
logger.error("Invalid parameters.");
throw new BadRequestException("Invalid parameters.");
}
} catch (Exception e) {
logger.error("Invalid parameters.", e);
throw new BadRequestException("Invalid parameters.");
}
if (userid != null) {
if (!openIDConnectProvider.isUserValid(userid, request)) {
logger.error("Invalid parameters.");
throw new NotFoundException("Invalid parameters.");
}
}
final Map<String, Object> response = new HashMap<String, Object>();
response.put("subject", resource);
final Set<Object> set = new HashSet<Object>();
final Map<String, Object> objectMap = new HashMap<String, Object>();
objectMap.put("rel", rel);
objectMap.put("href", deploymentUrl + "/oauth2");
set.add(objectMap);
response.put("links", set);
return response;
}
Aggregations