use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class BackchannelAuthorizeRestWebServiceImpl method requestBackchannelAuthorizationPost.
@Override
public Response requestBackchannelAuthorizationPost(String clientId, String scope, String clientNotificationToken, String acrValues, String loginHintToken, String idTokenHint, String loginHint, String bindingMessage, String userCodeParam, Integer requestedExpiry, String request, String requestUri, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
// it may be encoded
scope = ServerUtil.urlDecode(scope);
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.BACKCHANNEL_AUTHENTICATION);
oAuth2AuditLog.setClientId(clientId);
oAuth2AuditLog.setScope(scope);
// ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final,
// there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
log.debug("Attempting to request backchannel authorization: " + "clientId = {}, scope = {}, clientNotificationToken = {}, acrValues = {}, loginHintToken = {}, " + "idTokenHint = {}, loginHint = {}, bindingMessage = {}, userCodeParam = {}, requestedExpiry = {}, " + "request= {}", clientId, scope, clientNotificationToken, acrValues, loginHintToken, idTokenHint, loginHint, bindingMessage, userCodeParam, requestedExpiry, request);
log.debug("Attempting to request backchannel authorization: " + "isSecure = {}", securityContext.isSecure());
Response.ResponseBuilder builder = Response.ok();
if (!appConfiguration.getCibaEnabled()) {
log.warn("Trying to register a CIBA request, however CIBA config is disabled.");
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
return builder.build();
}
SessionClient sessionClient = identity.getSessionClient();
Client client = null;
if (sessionClient != null) {
client = sessionClient.getClient();
}
if (client == null) {
// 401
builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(INVALID_CLIENT));
return builder.build();
}
if (!cibaRequestService.hasCibaCompatibility(client)) {
// 401
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
return builder.build();
}
List<String> scopes = new ArrayList<>();
if (StringHelper.isNotEmpty(scope)) {
Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
scopes.addAll(grantedScopes);
}
JwtAuthorizationRequest jwtRequest = null;
if (StringUtils.isNotBlank(request) || StringUtils.isNotBlank(requestUri)) {
jwtRequest = JwtAuthorizationRequest.createJwtRequest(request, requestUri, client, null, cryptoProvider, appConfiguration);
if (jwtRequest == null) {
log.error("The JWT couldn't be processed");
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
throw new WebApplicationException(builder.build());
}
authorizeRestWebServiceValidator.validateCibaRequestObject(jwtRequest, client.getClientId());
// JWT wins
if (!jwtRequest.getScopes().isEmpty()) {
scopes.addAll(scopeChecker.checkScopesPolicy(client, jwtRequest.getScopes()));
}
if (StringUtils.isNotBlank(jwtRequest.getClientNotificationToken())) {
clientNotificationToken = jwtRequest.getClientNotificationToken();
}
if (StringUtils.isNotBlank(jwtRequest.getAcrValues())) {
acrValues = jwtRequest.getAcrValues();
}
if (StringUtils.isNotBlank(jwtRequest.getLoginHintToken())) {
loginHintToken = jwtRequest.getLoginHintToken();
}
if (StringUtils.isNotBlank(jwtRequest.getIdTokenHint())) {
idTokenHint = jwtRequest.getIdTokenHint();
}
if (StringUtils.isNotBlank(jwtRequest.getLoginHint())) {
loginHint = jwtRequest.getLoginHint();
}
if (StringUtils.isNotBlank(jwtRequest.getBindingMessage())) {
bindingMessage = jwtRequest.getBindingMessage();
}
if (StringUtils.isNotBlank(jwtRequest.getUserCode())) {
userCodeParam = jwtRequest.getUserCode();
}
if (jwtRequest.getRequestedExpiry() != null) {
requestedExpiry = jwtRequest.getRequestedExpiry();
} else if (jwtRequest.getExp() != null) {
requestedExpiry = Math.toIntExact(jwtRequest.getExp() - System.currentTimeMillis() / 1000);
}
}
if (appConfiguration.getFapiCompatibility() && jwtRequest == null) {
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
return builder.build();
}
User user = null;
try {
if (Strings.isNotBlank(loginHint)) {
// login_hint
user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), loginHint);
} else if (Strings.isNotBlank(idTokenHint)) {
// id_token_hint
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
if (authorizationGrant == null) {
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
return builder.build();
}
user = authorizationGrant.getUser();
}
if (Strings.isNotBlank(loginHintToken)) {
// login_hint_token
Jwt jwt = Jwt.parse(loginHintToken);
SignatureAlgorithm algorithm = jwt.getHeader().getSignatureAlgorithm();
String keyId = jwt.getHeader().getKeyId();
if (algorithm == null || Strings.isBlank(keyId)) {
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
return builder.build();
}
boolean validSignature = false;
if (algorithm.getFamily() == AlgorithmFamily.RSA) {
RSAPublicKey publicKey = JwkClient.getRSAPublicKey(client.getJwksUri(), keyId);
RSASigner rsaSigner = new RSASigner(algorithm, publicKey);
validSignature = rsaSigner.validate(jwt);
} else if (algorithm.getFamily() == AlgorithmFamily.EC) {
ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(client.getJwksUri(), keyId);
ECDSASigner ecdsaSigner = new ECDSASigner(algorithm, publicKey);
validSignature = ecdsaSigner.validate(jwt);
}
if (!validSignature) {
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
return builder.build();
}
JSONObject subject = jwt.getClaims().getClaimAsJSON("subject");
if (subject == null || !subject.has("subject_type") || !subject.has(subject.getString("subject_type"))) {
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
return builder.build();
}
String subjectTypeKey = subject.getString("subject_type");
String subjectTypeValue = subject.getString(subjectTypeKey);
user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), subjectTypeValue);
}
} catch (InvalidJwtException e) {
log.error(e.getMessage(), e);
} catch (JSONException e) {
log.error(e.getMessage(), e);
}
if (user == null) {
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
return builder.build();
}
try {
String userCode = (String) user.getAttribute("oxAuthBackchannelUserCode", true, false);
DefaultErrorResponse cibaAuthorizeParamsValidation = cibaAuthorizeParamsValidatorService.validateParams(scopes, clientNotificationToken, client.getBackchannelTokenDeliveryMode(), loginHintToken, idTokenHint, loginHint, bindingMessage, client.getBackchannelUserCodeParameter(), userCodeParam, userCode, requestedExpiry);
if (cibaAuthorizeParamsValidation != null) {
builder = Response.status(cibaAuthorizeParamsValidation.getStatus());
builder.entity(errorResponseFactory.errorAsJson(cibaAuthorizeParamsValidation.getType(), cibaAuthorizeParamsValidation.getReason()));
return builder.build();
}
String deviceRegistrationToken = (String) user.getAttribute("oxAuthBackchannelDeviceRegistrationToken", true, false);
if (deviceRegistrationToken == null) {
// 401
builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(UNAUTHORIZED_END_USER_DEVICE));
return builder.build();
}
int expiresIn = requestedExpiry != null ? requestedExpiry : appConfiguration.getBackchannelAuthenticationResponseExpiresIn();
Integer interval = client.getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PUSH ? null : appConfiguration.getBackchannelAuthenticationResponseInterval();
long currentTime = new Date().getTime();
CibaRequestCacheControl cibaRequestCacheControl = new CibaRequestCacheControl(user, client, expiresIn, scopes, clientNotificationToken, bindingMessage, currentTime, acrValues);
cibaRequestService.save(cibaRequestCacheControl, expiresIn);
String authReqId = cibaRequestCacheControl.getAuthReqId();
// Notify End-User to obtain Consent/Authorization
cibaEndUserNotificationService.notifyEndUser(cibaRequestCacheControl.getScopesAsString(), cibaRequestCacheControl.getAcrValues(), authReqId, deviceRegistrationToken);
builder.entity(getJSONObject(authReqId, expiresIn, interval).toString(4).replace("\\/", "/"));
builder.type(MediaType.APPLICATION_JSON_TYPE);
builder.cacheControl(ServerUtil.cacheControl(true, false));
} catch (JSONException e) {
builder = Response.status(400);
builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
log.error(e.getMessage(), e);
} catch (InvalidClaimException e) {
builder = Response.status(400);
builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
log.error(e.getMessage(), e);
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class BackchannelDeviceRegistrationRestWebServiceImpl method requestBackchannelDeviceRegistrationPost.
@Override
public Response requestBackchannelDeviceRegistrationPost(String idTokenHint, String deviceRegistrationToken, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.BACKCHANNEL_DEVICE_REGISTRATION);
// ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final,
// there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
log.debug("Attempting to request backchannel device registration: " + "idTokenHint = {}, deviceRegistrationToken = {}, isSecure = {}", idTokenHint, deviceRegistrationToken, securityContext.isSecure());
Response.ResponseBuilder builder = Response.ok();
if (!appConfiguration.getCibaEnabled()) {
log.warn("Trying to register a CIBA device, however CIBA config is disabled.");
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
return builder.build();
}
DefaultErrorResponse cibaDeviceRegistrationValidation = cibaDeviceRegistrationValidatorService.validateParams(idTokenHint, deviceRegistrationToken);
if (cibaDeviceRegistrationValidation != null) {
builder = Response.status(cibaDeviceRegistrationValidation.getStatus());
builder.entity(errorResponseFactory.errorAsJson(cibaDeviceRegistrationValidation.getType(), cibaDeviceRegistrationValidation.getReason()));
return builder.build();
}
User user = null;
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
if (authorizationGrant == null) {
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(BackchannelAuthenticationErrorResponseType.UNKNOWN_USER_ID));
return builder.build();
}
user = authorizationGrant.getUser();
if (user == null) {
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
return builder.build();
}
userService.setCustomAttribute(user, "oxAuthBackchannelDeviceRegistrationToken", deviceRegistrationToken);
userService.updateUser(user);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class AuthorizeRestWebServiceImpl method requestAuthorization.
private Response requestAuthorization(String scope, String responseType, String clientId, String redirectUri, String state, String respMode, String nonce, String display, String prompt, Integer maxAge, String uiLocalesStr, String idTokenHint, String loginHint, String acrValuesStr, String amrValuesStr, String request, String requestUri, String requestSessionId, String sessionId, String method, String originHeaders, String codeChallenge, String codeChallengeMethod, String customRespHeaders, String claims, String authReqId, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
// it may be encoded in uma case
scope = ServerUtil.urlDecode(scope);
String tokenBindingHeader = httpRequest.getHeader("Sec-Token-Binding");
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.USER_AUTHORIZATION);
oAuth2AuditLog.setClientId(clientId);
oAuth2AuditLog.setScope(scope);
// ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final ,
// there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
log.debug("Attempting to request authorization: " + "responseType = {}, clientId = {}, scope = {}, redirectUri = {}, nonce = {}, " + "state = {}, request = {}, isSecure = {}, requestSessionId = {}, sessionId = {}", responseType, clientId, scope, redirectUri, nonce, state, request, securityContext.isSecure(), requestSessionId, sessionId);
log.debug("Attempting to request authorization: " + "acrValues = {}, amrValues = {}, originHeaders = {}, codeChallenge = {}, codeChallengeMethod = {}, " + "customRespHeaders = {}, claims = {}, tokenBindingHeader = {}", acrValuesStr, amrValuesStr, originHeaders, codeChallenge, codeChallengeMethod, customRespHeaders, claims, tokenBindingHeader);
ResponseBuilder builder = Response.ok();
List<String> uiLocales = Util.splittedStringAsList(uiLocalesStr, " ");
List<ResponseType> responseTypes = ResponseType.fromString(responseType, " ");
List<Prompt> prompts = Prompt.fromString(prompt, " ");
List<String> acrValues = Util.splittedStringAsList(acrValuesStr, " ");
List<String> amrValues = Util.splittedStringAsList(amrValuesStr, " ");
ResponseMode responseMode = ResponseMode.getByValue(respMode);
Map<String, String> customParameters = requestParameterService.getCustomParameters(QueryStringDecoder.decode(httpRequest.getQueryString(), true));
SessionId sessionUser = identity.getSessionId();
User user = sessionIdService.getUser(sessionUser);
try {
Map<String, String> customResponseHeaders = Util.jsonObjectArrayStringAsMap(customRespHeaders);
updateSessionForROPC(httpRequest, sessionUser);
Client client = authorizeRestWebServiceValidator.validateClient(clientId, state);
String deviceAuthzUserCode = deviceAuthorizationService.getUserCodeFromSession(httpRequest);
redirectUri = authorizeRestWebServiceValidator.validateRedirectUri(client, redirectUri, state, deviceAuthzUserCode, httpRequest);
log.trace("Validated URI: {}", redirectUri);
// check after redirect uri is validated
checkAcrChanged(acrValuesStr, prompts, sessionUser);
RedirectUriResponse redirectUriResponse = new RedirectUriResponse(new RedirectUri(redirectUri, responseTypes, responseMode), state, httpRequest, errorResponseFactory);
redirectUriResponse.setFapiCompatible(appConfiguration.getFapiCompatibility());
Set<String> scopes = scopeChecker.checkScopesPolicy(client, scope);
JwtAuthorizationRequest jwtRequest = null;
if (StringUtils.isNotBlank(request) || StringUtils.isNotBlank(requestUri)) {
try {
jwtRequest = JwtAuthorizationRequest.createJwtRequest(request, requestUri, client, redirectUriResponse, cryptoProvider, appConfiguration);
if (jwtRequest == null) {
throw createInvalidJwtRequestException(redirectUriResponse, "Failed to parse jwt.");
}
if (StringUtils.isNotBlank(jwtRequest.getState())) {
state = jwtRequest.getState();
redirectUriResponse.setState(state);
}
if (appConfiguration.getFapiCompatibility() && StringUtils.isBlank(jwtRequest.getState())) {
// #1250 - FAPI : discard state if in JWT we don't have state
state = "";
redirectUriResponse.setState("");
}
authorizeRestWebServiceValidator.validateRequestObject(jwtRequest, redirectUriResponse);
// MUST be equal
if (!jwtRequest.getResponseTypes().containsAll(responseTypes) || !responseTypes.containsAll(jwtRequest.getResponseTypes())) {
throw createInvalidJwtRequestException(redirectUriResponse, "The responseType parameter is not the same in the JWT");
}
if (StringUtils.isBlank(jwtRequest.getClientId()) || !jwtRequest.getClientId().equals(clientId)) {
throw createInvalidJwtRequestException(redirectUriResponse, "The clientId parameter is not the same in the JWT");
}
// JWT wins
if (!jwtRequest.getScopes().isEmpty()) {
if (!scopes.contains("openid")) {
// spec: Even if a scope parameter is present in the Request Object value, a scope parameter MUST always be passed using the OAuth 2.0 request syntax containing the openid scope value
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_SCOPE, state, "scope parameter does not contain openid value which is required.")).build());
}
scopes = scopeChecker.checkScopesPolicy(client, Lists.newArrayList(jwtRequest.getScopes()));
}
if (jwtRequest.getRedirectUri() != null && !jwtRequest.getRedirectUri().equals(redirectUri)) {
throw createInvalidJwtRequestException(redirectUriResponse, "The redirect_uri parameter is not the same in the JWT");
}
if (StringUtils.isNotBlank(jwtRequest.getNonce())) {
nonce = jwtRequest.getNonce();
}
if (jwtRequest.getDisplay() != null && StringUtils.isNotBlank(jwtRequest.getDisplay().getParamName())) {
display = jwtRequest.getDisplay().getParamName();
}
if (!jwtRequest.getPrompts().isEmpty()) {
prompts = Lists.newArrayList(jwtRequest.getPrompts());
}
final IdTokenMember idTokenMember = jwtRequest.getIdTokenMember();
if (idTokenMember != null) {
if (idTokenMember.getMaxAge() != null) {
maxAge = idTokenMember.getMaxAge();
}
final Claim acrClaim = idTokenMember.getClaim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE);
if (acrClaim != null && acrClaim.getClaimValue() != null) {
acrValuesStr = acrClaim.getClaimValue().getValueAsString();
acrValues = Util.splittedStringAsList(acrValuesStr, " ");
}
Claim userIdClaim = idTokenMember.getClaim(JwtClaimName.SUBJECT_IDENTIFIER);
if (userIdClaim != null && userIdClaim.getClaimValue() != null && userIdClaim.getClaimValue().getValue() != null) {
String userIdClaimValue = userIdClaim.getClaimValue().getValue();
if (user != null) {
String userId = user.getUserId();
if (!userId.equalsIgnoreCase(userIdClaimValue)) {
builder = redirectUriResponse.createErrorBuilder(AuthorizeErrorResponseType.USER_MISMATCHED);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
}
}
}
requestParameterService.getCustomParameters(jwtRequest, customParameters);
} catch (WebApplicationException e) {
throw e;
} catch (Exception e) {
log.error("Invalid JWT authorization request. Message : " + e.getMessage(), e);
throw createInvalidJwtRequestException(redirectUriResponse, "Invalid JWT authorization request");
}
}
if (!cibaRequestService.hasCibaCompatibility(client)) {
if (appConfiguration.getFapiCompatibility() && jwtRequest == null) {
throw redirectUriResponse.createWebException(AuthorizeErrorResponseType.INVALID_REQUEST);
}
authorizeRestWebServiceValidator.validateRequestJwt(request, requestUri, redirectUriResponse);
}
authorizeRestWebServiceValidator.validate(responseTypes, prompts, nonce, state, redirectUri, httpRequest, client, responseMode);
if (CollectionUtils.isEmpty(acrValues) && !ArrayUtils.isEmpty(client.getDefaultAcrValues())) {
acrValues = Lists.newArrayList(client.getDefaultAcrValues());
}
if (scopes.contains(ScopeConstants.OFFLINE_ACCESS) && !client.getTrustedClient()) {
if (!responseTypes.contains(ResponseType.CODE)) {
log.trace("Removed (ignored) offline_scope. Can't find `code` in response_type which is required.");
scopes.remove(ScopeConstants.OFFLINE_ACCESS);
}
if (scopes.contains(ScopeConstants.OFFLINE_ACCESS) && !prompts.contains(Prompt.CONSENT)) {
log.error("Removed offline_access. Can't find prompt=consent. Consent is required for offline_access.");
scopes.remove(ScopeConstants.OFFLINE_ACCESS);
}
}
final boolean isResponseTypeValid = AuthorizeParamsValidator.validateResponseTypes(responseTypes, client) && AuthorizeParamsValidator.validateGrantType(responseTypes, client.getGrantTypes(), appConfiguration.getGrantTypesSupported());
if (!isResponseTypeValid) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.UNSUPPORTED_RESPONSE_TYPE, state, "")).build());
}
AuthorizationGrant authorizationGrant = null;
if (user == null) {
identity.logout();
if (prompts.contains(Prompt.NONE)) {
if (authenticationFilterService.isEnabled()) {
Map<String, String> params;
if (method.equals(HttpMethod.GET)) {
params = QueryStringDecoder.decode(httpRequest.getQueryString());
} else {
params = getGenericRequestMap(httpRequest);
}
String userDn = authenticationFilterService.processAuthenticationFilters(params);
if (userDn != null) {
Map<String, String> genericRequestMap = getGenericRequestMap(httpRequest);
Map<String, String> parameterMap = Maps.newHashMap(genericRequestMap);
Map<String, String> requestParameterMap = requestParameterService.getAllowedParameters(parameterMap);
sessionUser = sessionIdService.generateAuthenticatedSessionId(httpRequest, userDn, prompt);
sessionUser.setSessionAttributes(requestParameterMap);
cookieService.createSessionIdCookie(sessionUser, httpRequest, httpResponse, false);
sessionIdService.updateSessionId(sessionUser);
user = userService.getUserByDn(sessionUser.getUserDn());
} else {
builder = redirectUriResponse.createErrorBuilder(AuthorizeErrorResponseType.LOGIN_REQUIRED);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
} else {
builder = redirectUriResponse.createErrorBuilder(AuthorizeErrorResponseType.LOGIN_REQUIRED);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
} else {
if (prompts.contains(Prompt.LOGIN)) {
unauthenticateSession(sessionId, httpRequest);
sessionId = null;
prompts.remove(Prompt.LOGIN);
}
return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
}
}
boolean validAuthenticationMaxAge = authorizeRestWebServiceValidator.validateAuthnMaxAge(maxAge, sessionUser, client);
if (!validAuthenticationMaxAge) {
unauthenticateSession(sessionId, httpRequest);
sessionId = null;
return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
}
oAuth2AuditLog.setUsername(user.getUserId());
ExternalPostAuthnContext postAuthnContext = new ExternalPostAuthnContext(client, sessionUser, httpRequest, httpResponse);
final boolean forceReAuthentication = externalPostAuthnService.externalForceReAuthentication(client, postAuthnContext);
if (forceReAuthentication) {
unauthenticateSession(sessionId, httpRequest);
sessionId = null;
return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
}
final boolean forceAuthorization = externalPostAuthnService.externalForceAuthorization(client, postAuthnContext);
if (forceAuthorization) {
return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
}
ClientAuthorization clientAuthorization = null;
boolean clientAuthorizationFetched = false;
if (scopes.size() > 0) {
if (prompts.contains(Prompt.CONSENT)) {
return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
}
if (client.getTrustedClient()) {
sessionUser.addPermission(clientId, true);
sessionIdService.updateSessionId(sessionUser);
} else {
clientAuthorization = clientAuthorizationsService.find(user.getAttribute("inum"), client.getClientId());
clientAuthorizationFetched = true;
if (clientAuthorization != null && clientAuthorization.getScopes() != null) {
log.trace("ClientAuthorization - scope: " + scope + ", dn: " + clientAuthorization.getDn() + ", requestedScope: " + scopes);
if (Arrays.asList(clientAuthorization.getScopes()).containsAll(scopes)) {
sessionUser.addPermission(clientId, true);
sessionIdService.updateSessionId(sessionUser);
} else {
return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
}
}
}
}
if (prompts.contains(Prompt.LOGIN)) {
// workaround for #1030 - remove only authenticated session, for set up acr we set it unauthenticated and then drop in AuthorizeAction
if (identity.getSessionId().getState() == SessionIdState.AUTHENTICATED) {
unauthenticateSession(sessionId, httpRequest);
}
sessionId = null;
prompts.remove(Prompt.LOGIN);
return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
}
if (prompts.contains(Prompt.CONSENT) || !sessionUser.isPermissionGrantedForClient(clientId)) {
if (!clientAuthorizationFetched) {
clientAuthorization = clientAuthorizationsService.find(user.getAttribute("inum"), client.getClientId());
}
clientAuthorizationsService.clearAuthorizations(clientAuthorization, client.getPersistClientAuthorizations());
prompts.remove(Prompt.CONSENT);
return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
}
if (prompts.contains(Prompt.SELECT_ACCOUNT)) {
return redirectToSelectAccountPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
}
AuthorizationCode authorizationCode = null;
if (responseTypes.contains(ResponseType.CODE)) {
authorizationGrant = authorizationGrantList.createAuthorizationCodeGrant(user, client, sessionUser.getAuthenticationTime());
authorizationGrant.setNonce(nonce);
authorizationGrant.setJwtAuthorizationRequest(jwtRequest);
authorizationGrant.setTokenBindingHash(TokenBindingMessage.getTokenBindingIdHashFromTokenBindingMessage(tokenBindingHeader, client.getIdTokenTokenBindingCnf()));
authorizationGrant.setScopes(scopes);
authorizationGrant.setCodeChallenge(codeChallenge);
authorizationGrant.setCodeChallengeMethod(codeChallengeMethod);
authorizationGrant.setClaims(claims);
// Store acr_values
authorizationGrant.setAcrValues(getAcrForGrant(acrValuesStr, sessionUser));
authorizationGrant.setSessionDn(sessionUser.getDn());
// call save after object modification!!!
authorizationGrant.save();
authorizationCode = authorizationGrant.getAuthorizationCode();
redirectUriResponse.getRedirectUri().addResponseParameter("code", authorizationCode.getCode());
}
AccessToken newAccessToken = null;
if (responseTypes.contains(ResponseType.TOKEN)) {
if (authorizationGrant == null) {
authorizationGrant = authorizationGrantList.createImplicitGrant(user, client, sessionUser.getAuthenticationTime());
authorizationGrant.setNonce(nonce);
authorizationGrant.setJwtAuthorizationRequest(jwtRequest);
authorizationGrant.setScopes(scopes);
authorizationGrant.setClaims(claims);
// Store acr_values
authorizationGrant.setAcrValues(getAcrForGrant(acrValuesStr, sessionUser));
authorizationGrant.setSessionDn(sessionUser.getDn());
// call save after object modification!!!
authorizationGrant.save();
}
newAccessToken = authorizationGrant.createAccessToken(httpRequest.getHeader("X-ClientCert"), new ExecutionContext(httpRequest, httpResponse));
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.ACCESS_TOKEN, newAccessToken.getCode());
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.TOKEN_TYPE, newAccessToken.getTokenType().toString());
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.EXPIRES_IN, newAccessToken.getExpiresIn() + "");
}
if (responseTypes.contains(ResponseType.ID_TOKEN)) {
boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
if (authorizationGrant == null) {
includeIdTokenClaims = true;
authorizationGrant = authorizationGrantList.createImplicitGrant(user, client, sessionUser.getAuthenticationTime());
authorizationGrant.setNonce(nonce);
authorizationGrant.setJwtAuthorizationRequest(jwtRequest);
authorizationGrant.setScopes(scopes);
authorizationGrant.setClaims(claims);
// Store authentication acr values
authorizationGrant.setAcrValues(getAcrForGrant(acrValuesStr, sessionUser));
authorizationGrant.setSessionDn(sessionUser.getDn());
// call save after object modification, call is asynchronous!!!
authorizationGrant.save();
}
ExternalUpdateTokenContext context = new ExternalUpdateTokenContext(httpRequest, authorizationGrant, client, appConfiguration, attributeService);
Function<JsonWebResponse, Void> postProcessor = externalUpdateTokenService.buildModifyIdTokenProcessor(context);
IdToken idToken = authorizationGrant.createIdToken(nonce, authorizationCode, newAccessToken, null, state, authorizationGrant, includeIdTokenClaims, JwrService.wrapWithSidFunction(TokenBindingMessage.createIdTokenTokingBindingPreprocessing(tokenBindingHeader, client.getIdTokenTokenBindingCnf()), sessionUser.getOutsideSid()), postProcessor);
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.ID_TOKEN, idToken.getCode());
}
if (authorizationGrant != null && StringHelper.isNotEmpty(acrValuesStr) && !appConfiguration.getFapiCompatibility()) {
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.ACR_VALUES, acrValuesStr);
}
if (sessionUser.getId() == null) {
final SessionId newSessionUser = sessionIdService.generateAuthenticatedSessionId(httpRequest, sessionUser.getUserDn(), prompt);
String newSessionId = newSessionUser.getId();
sessionUser.setId(newSessionId);
log.trace("newSessionId = {}", newSessionId);
}
if (!appConfiguration.getFapiCompatibility() && appConfiguration.getSessionIdRequestParameterEnabled()) {
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.SESSION_ID, sessionUser.getId());
}
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.SID, sessionUser.getOutsideSid());
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.SESSION_STATE, sessionIdService.computeSessionState(sessionUser, clientId, redirectUri));
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.STATE, state);
if (scope != null && !scope.isEmpty() && authorizationGrant != null && !appConfiguration.getFapiCompatibility()) {
scope = authorizationGrant.checkScopesPolicy(scope);
redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.SCOPE, scope);
}
clientService.updateAccessTime(client, false);
oAuth2AuditLog.setSuccess(true);
log.trace("Preparing redirect to: {}", redirectUriResponse.getRedirectUri());
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse.getRedirectUri(), httpRequest);
if (appConfiguration.getCustomHeadersWithAuthorizationResponse()) {
for (String key : customResponseHeaders.keySet()) {
builder.header(key, customResponseHeaders.get(key));
}
}
if (StringUtils.isNotBlank(authReqId)) {
runCiba(authReqId, client, httpRequest, httpResponse);
}
if (StringUtils.isNotBlank(deviceAuthzUserCode)) {
processDeviceAuthorization(deviceAuthzUserCode, user);
}
} catch (WebApplicationException e) {
applicationAuditLogger.sendMessage(oAuth2AuditLog);
log.error(e.getMessage(), e);
throw e;
} catch (AcrChangedException e) {
// Acr changed
log.error("ACR is changed, please provide a supported and enabled acr value");
log.error(e.getMessage(), e);
RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.SESSION_SELECTION_REQUIRED, state));
redirectUriResponse.addResponseParameter("hint", "Use prompt=login in order to alter existing session.");
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest).build();
} catch (EntryPersistenceException e) {
// Invalid clientId
builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state, "")).type(MediaType.APPLICATION_JSON_TYPE);
log.error(e.getMessage(), e);
} catch (InvalidSessionStateException ex) {
// Allow to handle it via GlobalExceptionHandler
throw ex;
} catch (Exception e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class UserInfoRestWebServiceImpl method requestUserInfo.
private Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {
if (tokenService.isBearerAuthToken(authorization)) {
accessToken = tokenService.getBearerToken(authorization);
}
log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
Response.ResponseBuilder builder = Response.ok();
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);
try {
if (!UserInfoParamsValidator.validateParams(accessToken)) {
return response(400, UserInfoErrorResponseType.INVALID_REQUEST, "access token is not valid.");
}
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
if (authorizationGrant == null) {
log.trace("Failed to find authorization grant by access_token: " + accessToken);
return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
}
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);
final AbstractToken accessTokenObject = authorizationGrant.getAccessToken(accessToken);
if (accessTokenObject == null || !accessTokenObject.isValid()) {
log.trace("Invalid access token object, access_token: {}, isNull: {}, isValid: {}", accessToken, accessTokenObject == null, false);
return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
}
if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Grant object has client_credentials grant_type which is not valid.");
}
if (appConfiguration.getOpenidScopeBackwardCompatibility() && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Both openid and profile scopes are not present.");
}
if (!appConfiguration.getOpenidScopeBackwardCompatibility() && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString())) {
return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Missed openid scope.");
}
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
builder.cacheControl(ServerUtil.cacheControlWithNoStoreTransformAndPrivate());
builder.header("Pragma", "no-cache");
User currentUser = authorizationGrant.getUser();
try {
currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
} catch (EntryPersistenceException ex) {
log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
}
if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
builder.type("application/jwt");
builder.entity(getJweResponse(keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
} else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
builder.type("application/jwt");
builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
} else {
builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes()));
}
return builder.build();
} catch (Exception e) {
log.error(e.getMessage(), e);
// 500
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} finally {
applicationAuditLogger.sendMessage(oAuth2AuditLog);
}
}
use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class RegisterRestWebServiceImpl method requestClientRead.
@Override
public Response requestClientRead(String clientId, String authorization, HttpServletRequest httpRequest, SecurityContext securityContext) {
String accessToken = tokenService.getToken(authorization);
log.debug("Attempting to read client: clientId = {}, registrationAccessToken = {} isSecure = {}", clientId, accessToken, securityContext.isSecure());
Response.ResponseBuilder builder = Response.ok();
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.CLIENT_READ);
oAuth2AuditLog.setClientId(clientId);
try {
if (appConfiguration.getDynamicRegistrationEnabled()) {
if (registerParamsValidator.validateParamsClientRead(clientId, accessToken)) {
Client client = clientService.getClient(clientId, accessToken);
if (client != null) {
oAuth2AuditLog.setScope(clientScopesToString(client));
oAuth2AuditLog.setSuccess(true);
builder.entity(clientAsEntity(client));
} else {
log.trace("The Access Token is not valid for the Client ID, returns invalid_token error.");
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()).type(MediaType.APPLICATION_JSON_TYPE);
builder.entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_TOKEN, "The Access Token is not valid for the Client"));
}
} else {
log.trace("Client ID or Access Token is not valid.");
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Client ID or Access Token is not valid.");
}
} else {
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Dynamic registration is disabled.");
}
} catch (JSONException e) {
log.error(e.getMessage(), e);
throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Failed to parse json.");
} catch (StringEncrypter.EncryptionException e) {
log.error(e.getMessage(), e);
throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Encryption exception occurred.");
}
builder.cacheControl(ServerUtil.cacheControl(true, false));
builder.header("Pragma", "no-cache");
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
Aggregations