use of org.gluu.model.custom.script.conf.CustomScriptConfiguration in project oxAuth by GluuFederation.
the class AuthorizeAction method checkPermissionGranted.
public void checkPermissionGranted() throws IOException {
if ((clientId == null) || clientId.isEmpty()) {
log.debug("Permission denied. client_id should be not empty.");
permissionDenied();
return;
}
Client client = null;
try {
client = clientService.getClient(clientId);
} catch (EntryPersistenceException ex) {
log.debug("Permission denied. Failed to find client by inum '{}' in LDAP.", clientId, ex);
permissionDenied();
return;
}
if (client == null) {
log.debug("Permission denied. Failed to find client_id '{}' in LDAP.", clientId);
permissionDenied();
return;
}
// Fix the list of scopes in the authorization page. oxAuth #739
Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
allowedScope = org.gluu.oxauth.model.util.StringUtils.implode(grantedScopes, " ");
SessionId session = getSession();
List<Prompt> prompts = Prompt.fromString(prompt, " ");
try {
redirectUri = authorizeRestWebServiceValidator.validateRedirectUri(client, redirectUri, state, session != null ? session.getSessionAttributes().get(SESSION_USER_CODE) : null, (HttpServletRequest) externalContext.getRequest());
} catch (WebApplicationException e) {
log.error(e.getMessage(), e);
permissionDenied();
return;
}
try {
session = sessionIdService.assertAuthenticatedSessionCorrespondsToNewRequest(session, acrValues);
} catch (AcrChangedException e) {
log.debug("There is already existing session which has another acr then {}, session: {}", acrValues, session.getId());
if (e.isForceReAuthentication()) {
session = handleAcrChange(session, prompts);
} else {
log.error("ACR is changed, please provide a supported and enabled acr value");
permissionDenied();
return;
}
}
if (session == null || StringUtils.isBlank(session.getUserDn()) || SessionIdState.AUTHENTICATED != session.getState()) {
Map<String, String> parameterMap = externalContext.getRequestParameterMap();
Map<String, String> requestParameterMap = requestParameterService.getAllowedParameters(parameterMap);
String redirectTo = "/login.xhtml";
boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
if (useExternalAuthenticator) {
List<String> acrValuesList = sessionIdService.acrValuesList(this.acrValues);
if (acrValuesList.isEmpty()) {
acrValuesList = Arrays.asList(defaultAuthenticationMode.getName());
}
CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.determineCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, acrValuesList);
if (customScriptConfiguration == null) {
log.error("Failed to get CustomScriptConfiguration. auth_step: {}, acr_values: {}", 1, this.acrValues);
permissionDenied();
return;
}
String acr = customScriptConfiguration.getName();
requestParameterMap.put(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, acr);
requestParameterMap.put("auth_step", Integer.toString(1));
String tmpRedirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, 1);
if (StringHelper.isNotEmpty(tmpRedirectTo)) {
log.trace("Redirect to person authentication login page: {}", tmpRedirectTo);
redirectTo = tmpRedirectTo;
}
}
// Store Remote IP
requestParameterMap.put(Constants.REMOTE_IP, getRemoteIp());
// User Code used in Device Authz flow
if (session != null && session.getSessionAttributes().containsKey(SESSION_USER_CODE)) {
String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
requestParameterMap.put(SESSION_USER_CODE, userCode);
}
// Create unauthenticated session
SessionId unauthenticatedSession = sessionIdService.generateUnauthenticatedSessionId(null, new Date(), SessionIdState.UNAUTHENTICATED, requestParameterMap, false);
unauthenticatedSession.setSessionAttributes(requestParameterMap);
unauthenticatedSession.addPermission(clientId, false);
// Copy ACR script parameters
if (appConfiguration.getKeepAuthenticatorAttributesOnAcrChange()) {
authenticationService.copyAuthenticatorExternalAttributes(session, unauthenticatedSession);
}
// #1030, fix for flow 4 - transfer previous session permissions to new session
if (session != null && session.getPermissionGrantedMap() != null && session.getPermissionGrantedMap().getPermissionGranted() != null) {
for (Map.Entry<String, Boolean> entity : session.getPermissionGrantedMap().getPermissionGranted().entrySet()) {
unauthenticatedSession.addPermission(entity.getKey(), entity.getValue());
}
// #1030, remove previous session
sessionIdService.remove(session);
}
// always persist is prompt is not none
boolean persisted = sessionIdService.persistSessionId(unauthenticatedSession, !prompts.contains(Prompt.NONE));
if (persisted && log.isTraceEnabled()) {
log.trace("Session '{}' persisted to LDAP", unauthenticatedSession.getId());
}
this.sessionId = unauthenticatedSession.getId();
cookieService.createSessionIdCookie(unauthenticatedSession, false);
cookieService.creatRpOriginIdCookie(redirectUri);
identity.setSessionId(unauthenticatedSession);
Map<String, Object> loginParameters = new HashMap<String, Object>();
if (requestParameterMap.containsKey(AuthorizeRequestParam.LOGIN_HINT)) {
loginParameters.put(AuthorizeRequestParam.LOGIN_HINT, requestParameterMap.get(AuthorizeRequestParam.LOGIN_HINT));
}
boolean enableRedirect = StringHelper.toBoolean(System.getProperty("gluu.enable-redirect", "false"), false);
if (!enableRedirect && redirectTo.toLowerCase().endsWith("xhtml")) {
if (redirectTo.toLowerCase().endsWith("postlogin.xhtml")) {
authenticator.authenticateWithOutcome();
} else {
authenticator.prepareAuthenticationForStep(unauthenticatedSession);
facesService.renderView(redirectTo);
}
} else {
facesService.redirectWithExternal(redirectTo, loginParameters);
}
return;
}
String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
if (StringUtils.isBlank(userCode) && StringUtils.isBlank(redirectionUriService.validateRedirectionUri(clientId, redirectUri))) {
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseStatus(HttpServletResponse.SC_BAD_REQUEST);
externalContext.setResponseContentType(MediaType.APPLICATION_JSON);
externalContext.getResponseOutputWriter().write(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state, ""));
facesContext.responseComplete();
}
if (log.isTraceEnabled()) {
log.trace("checkPermissionGranted, userDn = " + session.getUserDn());
}
if (prompts.contains(Prompt.SELECT_ACCOUNT)) {
Map requestParameterMap = requestParameterService.getAllowedParameters(externalContext.getRequestParameterMap());
facesService.redirect("/selectAccount.xhtml", requestParameterMap);
return;
}
if (prompts.contains(Prompt.NONE) && prompts.size() > 1) {
invalidRequest();
return;
}
ExternalPostAuthnContext postAuthnContext = new ExternalPostAuthnContext(client, session, (HttpServletRequest) externalContext.getRequest(), (HttpServletResponse) externalContext.getResponse());
final boolean forceAuthorization = externalPostAuthnService.externalForceAuthorization(client, postAuthnContext);
final boolean hasConsentPrompt = prompts.contains(Prompt.CONSENT);
if (!hasConsentPrompt && !forceAuthorization) {
if (appConfiguration.getTrustedClientEnabled() && client.getTrustedClient()) {
// if trusted client = true, then skip authorization page and grant access directly
permissionGranted(session);
return;
} else if (ServerUtil.isTrue(appConfiguration.getSkipAuthorizationForOpenIdScopeAndPairwiseId()) && SubjectType.PAIRWISE.toString().equals(client.getSubjectType()) && hasOnlyOpenidScope()) {
// If a client has only openid scope and pairwise id, person should not have to authorize. oxAuth-743
permissionGranted(session);
return;
}
final User user = sessionIdService.getUser(session);
ClientAuthorization clientAuthorization = clientAuthorizationsService.find(user.getAttribute("inum"), client.getClientId());
if (clientAuthorization != null && clientAuthorization.getScopes() != null && Arrays.asList(clientAuthorization.getScopes()).containsAll(org.gluu.oxauth.model.util.StringUtils.spaceSeparatedToList(scope))) {
permissionGranted(session);
return;
}
}
if (externalConsentGatheringService.isEnabled()) {
if (consentGatherer.isConsentGathered()) {
log.trace("Consent-gathered flow passed successfully");
permissionGranted(session);
return;
}
log.trace("Starting external consent-gathering flow");
boolean result = consentGatherer.configure(session.getUserDn(), clientId, state);
if (!result) {
log.error("Failed to initialize external consent-gathering flow.");
permissionDenied();
return;
}
}
}
use of org.gluu.model.custom.script.conf.CustomScriptConfiguration in project oxAuth by GluuFederation.
the class ConsentGathererService method configure.
public boolean configure(String userDn, String clientId, String state) {
final HttpServletRequest httpRequest = (HttpServletRequest) externalContext.getRequest();
final HttpServletResponse httpResponse = (HttpServletResponse) externalContext.getResponse();
final SessionId session = sessionService.getConsentSession(httpRequest, httpResponse, userDn, true);
CustomScriptConfiguration script = determineConsentScript(clientId);
if (script == null) {
log.error("Failed to determine consent-gathering script");
return false;
}
sessionService.configure(session, script.getName(), clientId, state);
this.context = new ConsentGatheringContext(script.getConfigurationAttributes(), httpRequest, httpResponse, session, pageAttributes, sessionService, userService, facesService, appConfiguration);
log.debug("Configuring consent-gathering script '{}'", script.getName());
int step = sessionService.getStep(session);
String redirectTo = external.getPageForStep(script, step, context);
if (StringHelper.isEmpty(redirectTo)) {
log.error("Failed to determine page for consent-gathering script");
return false;
}
context.persist();
log.trace("Redirecting to page: '{}'", redirectTo);
facesService.redirectWithExternal(redirectTo, null);
return true;
}
use of org.gluu.model.custom.script.conf.CustomScriptConfiguration in project oxAuth by GluuFederation.
the class LogoutAction method processExternalAuthenticatorLogOut.
private ExternalLogoutResult processExternalAuthenticatorLogOut(SessionId sessionId) {
if ((sessionId != null) && sessionId.getSessionAttributes().containsKey(EXTERNAL_LOGOUT)) {
log.debug("Detected callback from external system. Resuming logout.");
return ExternalLogoutResult.SUCCESS;
}
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
if (authorizationGrant == null) {
Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
}
}
if ((authorizationGrant == null) && (sessionId == null)) {
return ExternalLogoutResult.FAILURE;
}
String acrValues;
if (authorizationGrant == null) {
acrValues = sessionIdService.getAcr(sessionId);
} else {
acrValues = authorizationGrant.getAcrValues();
}
boolean isExternalAuthenticatorLogoutPresent = StringHelper.isNotEmpty(acrValues);
if (isExternalAuthenticatorLogoutPresent) {
log.debug("Attemptinmg to execute logout method of '{}' external authenticator.", acrValues);
CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfigurationByName(acrValues);
if (customScriptConfiguration == null) {
log.error("Failed to get ExternalAuthenticatorConfiguration. acr_values: {}", acrValues);
return ExternalLogoutResult.FAILURE;
} else {
boolean scriptExternalLogoutResult = externalAuthenticationService.executeExternalLogout(customScriptConfiguration, null);
ExternalLogoutResult externalLogoutResult = scriptExternalLogoutResult ? ExternalLogoutResult.SUCCESS : ExternalLogoutResult.FAILURE;
log.debug("Logout result is '{}' for session '{}', userDn: '{}'", externalLogoutResult, sessionId.getId(), sessionId.getUserDn());
int apiVersion = externalAuthenticationService.executeExternalGetApiVersion(customScriptConfiguration);
if (apiVersion < 3) {
// Not support redirect to external system at logout
return externalLogoutResult;
}
log.trace("According to API version script supports logout redirects");
String logoutExternalUrl = externalAuthenticationService.getLogoutExternalUrl(customScriptConfiguration, null);
log.debug("External logout result is '{}' for user '{}'", logoutExternalUrl, sessionId.getUserDn());
if (StringHelper.isEmpty(logoutExternalUrl)) {
return externalLogoutResult;
}
// Store in session parameters needed to call end_session
try {
storeLogoutParametersInSession(sessionId);
} catch (IOException ex) {
log.debug("Failed to persist logout parameters in session", ex);
return ExternalLogoutResult.FAILURE;
}
// Redirect to external URL
facesService.redirectToExternalURL(logoutExternalUrl);
return ExternalLogoutResult.REDIRECT;
}
} else {
return ExternalLogoutResult.SUCCESS;
}
}
use of org.gluu.model.custom.script.conf.CustomScriptConfiguration in project oxAuth by GluuFederation.
the class ConsentGathererService method authorize.
public boolean authorize() {
try {
final HttpServletRequest httpRequest = (HttpServletRequest) externalContext.getRequest();
final HttpServletResponse httpResponse = (HttpServletResponse) externalContext.getResponse();
final SessionId session = sessionService.getConsentSession(httpRequest, httpResponse, null, false);
if (session == null) {
log.error("Failed to restore claim-gathering session state");
errorPage("consent.gather.invalid.session");
return false;
}
CustomScriptConfiguration script = getScript(session);
if (script == null) {
log.error("Failed to find script '{}' in session:", sessionService.getScriptName(session));
errorPage("consent.gather.failed");
return false;
}
int step = sessionService.getStep(session);
if (!sessionService.isPassedPreviousSteps(session, step)) {
log.error("There are consent-gathering steps not marked as passed. scriptName: '{}', step: '{}'", script.getName(), step);
errorPage("consent.gather.invalid.step");
return false;
}
this.context = new ConsentGatheringContext(script.getConfigurationAttributes(), httpRequest, httpResponse, session, pageAttributes, sessionService, userService, facesService, appConfiguration);
boolean authorizeResult = external.authorize(script, step, context);
log.debug("Consent-gathering result for script '{}', step: '{}', gatheredResult: '{}'", script.getName(), step, authorizeResult);
int overridenNextStep = external.getNextStep(script, step, context);
if (!authorizeResult && overridenNextStep == -1) {
SessionId connectSession = sessionService.getConnectSession(httpRequest);
authorizeService.permissionDenied(connectSession);
return false;
}
if (overridenNextStep != -1) {
sessionService.resetToStep(session, overridenNextStep, step);
step = overridenNextStep;
}
int stepsCount = external.getStepsCount(script, context);
if (step < stepsCount || overridenNextStep != -1) {
int nextStep;
if (overridenNextStep != -1) {
nextStep = overridenNextStep;
} else {
nextStep = step + 1;
sessionService.markStep(session, step, true);
}
sessionService.setStep(nextStep, session);
String redirectTo = external.getPageForStep(script, nextStep, context);
context.persist();
log.trace("Redirecting to page: '{}'", redirectTo);
facesService.redirectWithExternal(redirectTo, null);
return true;
}
if (step == stepsCount) {
context.persist();
onSuccess(httpRequest, session, context);
return true;
}
} catch (Exception e) {
log.error("Exception during gather() method call.", e);
}
log.error("Failed to perform gather() method successfully.");
errorPage("consent.gather.failed");
return false;
}
use of org.gluu.model.custom.script.conf.CustomScriptConfiguration in project oxAuth by GluuFederation.
the class Authenticator method prepareAuthenticationForStep.
public String prepareAuthenticationForStep(SessionId sessionId) {
Map<String, String> sessionIdAttributes = sessionIdService.getSessionAttributes(sessionId);
if (sessionIdAttributes == null) {
logger.debug("Unable to get attributes from session");
return Constants.RESULT_EXPIRED;
}
// Set current state into identity to allow use in login form and
// authentication scripts
identity.setSessionId(sessionId);
if (!externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE)) {
return Constants.RESULT_SUCCESS;
}
initCustomAuthenticatorVariables(sessionIdAttributes);
if (StringHelper.isEmpty(this.authAcr)) {
return Constants.RESULT_SUCCESS;
}
if ((this.authStep == null) || (this.authStep < 1)) {
return Constants.RESULT_NO_PERMISSIONS;
}
CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, this.authAcr);
if (customScriptConfiguration == null) {
logger.error("Failed to get CustomScriptConfiguration. auth_step: '{}', acr: '{}'", this.authStep, this.authAcr);
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);
String currentauthAcr = customScriptConfiguration.getName();
customScriptConfiguration = externalAuthenticationService.determineExternalAuthenticatorForWorkflow(AuthenticationScriptUsageType.INTERACTIVE, customScriptConfiguration);
if (customScriptConfiguration == null) {
return Constants.RESULT_FAILURE;
} else {
String determinedauthAcr = customScriptConfiguration.getName();
if (!StringHelper.equalsIgnoreCase(currentauthAcr, determinedauthAcr)) {
// Redirect user to alternative login workflow
String redirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, this.authStep);
if (StringHelper.isEmpty(redirectTo)) {
redirectTo = "/login.xhtml";
}
CustomScriptConfiguration determinedCustomScriptConfiguration = externalAuthenticationService.getCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, determinedauthAcr);
if (determinedCustomScriptConfiguration == null) {
logger.error("Failed to get determined CustomScriptConfiguration. auth_step: '{}', acr: '{}'", this.authStep, this.authAcr);
return Constants.RESULT_FAILURE;
}
logger.debug("Redirect to page: '{}'. Force to use acr: '{}'", redirectTo, determinedauthAcr);
determinedauthAcr = determinedCustomScriptConfiguration.getName();
String determinedAuthLevel = Integer.toString(determinedCustomScriptConfiguration.getLevel());
sessionIdAttributes.put("acr", determinedauthAcr);
sessionIdAttributes.put("auth_level", determinedAuthLevel);
sessionIdAttributes.put("auth_step", Integer.toString(1));
// Remove old session parameters from session
if (!appConfiguration.getKeepAuthenticatorAttributesOnAcrChange()) {
authenticationService.clearExternalScriptExtraParameters(sessionIdAttributes);
}
if (sessionId != null) {
boolean updateResult = updateSession(sessionId, sessionIdAttributes);
if (!updateResult) {
return Constants.RESULT_EXPIRED;
}
}
facesService.redirectWithExternal(redirectTo, null);
return Constants.RESULT_SUCCESS;
}
}
Boolean result = externalAuthenticationService.executeExternalPrepareForStep(customScriptConfiguration, externalContext.getRequestParameterValuesMap(), this.authStep);
if ((result != null) && result) {
// Store/Update extra parameters in session attributes map
updateExtraParameters(customScriptConfiguration, this.authStep, sessionIdAttributes);
if (sessionId != null) {
boolean updateResult = updateSession(sessionId, sessionIdAttributes);
if (!updateResult) {
return Constants.RESULT_FAILURE;
}
}
return Constants.RESULT_SUCCESS;
} else {
return Constants.RESULT_FAILURE;
}
}
Aggregations