use of io.jans.as.common.model.common.User in project jans by JanssenProject.
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());
errorResponseFactory.validateComponentEnabled(ComponentType.CIBA);
Response.ResponseBuilder builder = Response.ok();
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.isFapi() && 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("jansBackchannelUsrCode", 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("jansBackchannelDeviceRegistrationTkn", 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 io.jans.as.common.model.common.User in project jans by JanssenProject.
the class SelectAccountAction method prepare.
@PostConstruct
public void prepare() {
currentSessions = Lists.newArrayList();
Set<String> uids = Sets.newHashSet();
for (SessionId session : sessionIdService.getCurrentSessions()) {
final User user = sessionIdService.getUser(session);
if (user == null) {
log.error("Failed to get user for session. Skipping it from current_sessions, id: {}", session.getId());
continue;
}
final String uid = StringUtils.isNotBlank(user.getUserId()) ? user.getUserId() : user.getDn();
if (!currentSessions.contains(session) && !uids.contains(uid)) {
log.trace("User: {}, sessionId: {}", uid, session.getId());
currentSessions.add(session);
uids.add(uid);
}
}
log.trace("Found {} sessions", currentSessions.size());
}
use of io.jans.as.common.model.common.User in project jans by JanssenProject.
the class SelectAccountAction method getName.
public String getName(SessionId sessionId) {
final User user = sessionId.getUser();
final String displayName = user.getAttribute("displayName");
if (StringUtils.isNotBlank(displayName)) {
return displayName;
}
if (StringUtils.isNotBlank(displayName)) {
return user.getUserId();
}
return user.getDn();
}
use of io.jans.as.common.model.common.User in project jans by JanssenProject.
the class Authenticator method authenticateBySessionId.
public boolean authenticateBySessionId(SessionId sessionId) {
if (sessionId == null) {
return false;
}
String sessionIdentifier = sessionId.getId();
logger.trace("authenticateBySessionId, sessionId = '{}', session = '{}', state= '{}'", sessionIdentifier, sessionId, sessionId.getState());
// IMPORTANT : authenticate by session id only if state of session is authenticated!
if (SessionIdState.AUTHENTICATED == sessionId.getState()) {
final User user = authenticationService.getUserOrRemoveSession(sessionId);
if (user != null) {
try {
authenticationService.quietLogin(user.getUserId());
authenticationService.configureEventUser(sessionId);
} catch (Exception e) {
logger.trace(e.getMessage(), e);
}
return true;
}
}
return false;
}
use of io.jans.as.common.model.common.User in project jans by JanssenProject.
the class Authenticator method userAuthenticationInteractive.
private String userAuthenticationInteractive(HttpServletRequest servletRequest) {
SessionId sessionId = getSessionId(servletRequest);
Map<String, String> sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId);
if (sessionIdAttributes == null) {
logger.debug("Unable to get session attributes. SessionId: {}", (sessionId != null ? sessionId.getId() : null));
return Constants.RESULT_EXPIRED;
}
// Set current state into identity to allow use in login form and
// authentication scripts
identity.setSessionId(sessionId);
initCustomAuthenticatorVariables(sessionIdAttributes);
boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
if (useExternalAuthenticator && !StringHelper.isEmpty(this.authAcr)) {
initCustomAuthenticatorVariables(sessionIdAttributes);
if ((this.authStep == null) || StringHelper.isEmpty(this.authAcr)) {
logger.error("Failed to determine authentication mode");
return Constants.RESULT_EXPIRED;
}
CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, this.authAcr);
if (customScriptConfiguration == null) {
logger.error("Failed to get CustomScriptConfiguration for acr: '{}', auth_step: '{}'", this.authAcr, this.authStep);
return Constants.RESULT_FAILURE;
}
// Check if all previous steps had passed
boolean passedPreviousSteps = isPassedPreviousAuthSteps(sessionIdAttributes, this.authStep);
if (!passedPreviousSteps) {
logger.error("There are authentication steps not marked as passed. acr: '{}', auth_step: '{}'", this.authAcr, this.authStep);
return Constants.RESULT_FAILURE;
}
// Restore identity working parameters from session
setIdentityWorkingParameters(sessionIdAttributes);
boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, externalContext.getRequestParameterValuesMap(), this.authStep);
if (logger.isDebugEnabled()) {
String userId = credentials.getUsername();
if (StringHelper.isEmpty(userId)) {
User user = identity.getUser();
if (user != null) {
userId = user.getUserId();
}
logger.debug("Authentication result for user '{}'. auth_step: '{}', result: '{}', credentials: '{}'", userId, this.authStep, result, System.identityHashCode(credentials));
}
}
int overridenNextStep = -1;
logger.trace("################## acr: {}, step: {}", authAcr, authStep);
int apiVersion = externalAuthenticationService.executeExternalGetApiVersion(customScriptConfiguration);
if (apiVersion > 1) {
logger.trace("According to API version script supports steps overriding");
overridenNextStep = externalAuthenticationService.getNextStep(customScriptConfiguration, externalContext.getRequestParameterValuesMap(), this.authStep);
logger.debug("Get next step from script: '{}'", overridenNextStep);
}
if (!result && (overridenNextStep == -1)) {
// Force session lastUsedAt update if authentication attempt is failed
sessionIdService.updateSessionId(sessionId);
return Constants.RESULT_AUTHENTICATION_FAILED;
}
boolean overrideCurrentStep = false;
if (overridenNextStep > -1) {
overrideCurrentStep = true;
// Reset to specified step
sessionId = sessionIdService.resetToStep(sessionId, overridenNextStep);
if (sessionId == null) {
return Constants.RESULT_AUTHENTICATION_FAILED;
}
this.authStep = overridenNextStep;
logger.info("Authentication reset to step : '{}'", this.authStep);
}
// Update parameters map to allow access it from count
// authentication steps method
updateExtraParameters(customScriptConfiguration, this.authStep + 1, sessionIdAttributes);
// Determine count authentication methods
int countAuthenticationSteps = externalAuthenticationService.executeExternalGetCountAuthenticationSteps(customScriptConfiguration);
sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId);
// Prepare for next step
if ((this.authStep < countAuthenticationSteps) || overrideCurrentStep) {
int nextStep;
if (overrideCurrentStep) {
nextStep = overridenNextStep;
} else {
nextStep = this.authStep + 1;
}
String redirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, nextStep);
if (redirectTo == null) {
return Constants.RESULT_FAILURE;
} else if (StringHelper.isEmpty(redirectTo)) {
redirectTo = "/login.xhtml";
}
// Store/Update extra parameters in session attributes map
updateExtraParameters(customScriptConfiguration, nextStep, sessionIdAttributes);
if (!overrideCurrentStep) {
// Update auth_step
sessionIdAttributes.put(AUTH_STEP, Integer.toString(nextStep));
// Mark step as passed
markAuthStepAsPassed(sessionIdAttributes, this.authStep);
}
if (sessionId != null) {
boolean updateResult = updateSession(sessionId, sessionIdAttributes);
if (!updateResult) {
return Constants.RESULT_EXPIRED;
}
}
logger.trace("Redirect to page: '{}'", redirectTo);
facesService.redirectWithExternal(redirectTo, null);
return Constants.RESULT_SUCCESS;
}
if (this.authStep == countAuthenticationSteps) {
// Store/Update extra parameters in session attributes map
updateExtraParameters(customScriptConfiguration, this.authStep + 1, sessionIdAttributes);
SessionId eventSessionId = authenticationService.configureSessionUser(sessionId, sessionIdAttributes);
authenticationService.quietLogin(credentials.getUsername());
// Redirect to authorization workflow
logger.debug("Sending event to trigger user redirection: '{}'", credentials.getUsername());
authenticationService.onSuccessfulLogin(eventSessionId);
logger.info(AUTHENTICATION_SUCCESS_FOR_USER, credentials.getUsername());
return Constants.RESULT_SUCCESS;
}
} else {
if (StringHelper.isNotEmpty(credentials.getUsername())) {
boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword());
if (authenticated) {
SessionId eventSessionId = authenticationService.configureSessionUser(sessionId, sessionIdAttributes);
// Redirect to authorization workflow
logger.debug("Sending event to trigger user redirection: '{}'", credentials.getUsername());
authenticationService.onSuccessfulLogin(eventSessionId);
} else {
// Force session lastUsedAt update if authentication attempt is failed
sessionIdService.updateSessionId(sessionId);
}
logger.info(AUTHENTICATION_SUCCESS_FOR_USER, credentials.getUsername());
return Constants.RESULT_SUCCESS;
}
}
return Constants.RESULT_FAILURE;
}
Aggregations