use of org.wso2.carbon.user.core.model.UserMgtContext in project identity-inbound-auth-oauth by wso2-extensions.
the class PasswordGrantHandler method validateUserCredentials.
private AuthenticatedUser validateUserCredentials(OAuth2AccessTokenReqDTO tokenReq, ServiceProvider serviceProvider) throws IdentityOAuth2Exception {
boolean isPublishPasswordGrantLoginEnabled = Boolean.parseBoolean(IdentityUtil.getProperty(PUBLISH_PASSWORD_GRANT_LOGIN));
try {
// Get the user store preference order supplier.
UserStorePreferenceOrderSupplier<List<String>> userStorePreferenceOrderSupplier = FrameworkUtils.getUserStorePreferenceOrderSupplier(null, serviceProvider);
UserMgtContext userMgtContext = new UserMgtContext();
userMgtContext.setUserStorePreferenceOrderSupplier(userStorePreferenceOrderSupplier);
if (userStorePreferenceOrderSupplier != null) {
UserCoreUtil.setUserMgtContextInThreadLocal(userMgtContext);
if (log.isDebugEnabled()) {
log.debug("UserMgtContext had been set as the thread local.");
}
}
String username = tokenReq.getResourceOwnerUsername();
if (!IdentityUtil.isEmailUsernameValidationDisabled()) {
FrameworkUtils.validateUsername(username);
username = FrameworkUtils.preprocessUsername(username, serviceProvider);
}
String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
String userTenantDomain = MultitenantUtils.getTenantDomain(username);
ResolvedUserResult resolvedUserResult = FrameworkUtils.processMultiAttributeLoginIdentification(tenantAwareUserName, userTenantDomain);
String userId = null;
if (resolvedUserResult != null && ResolvedUserResult.UserResolvedStatus.SUCCESS.equals(resolvedUserResult.getResolvedStatus())) {
tenantAwareUserName = resolvedUserResult.getUser().getUsername();
userId = resolvedUserResult.getUser().getUserID();
tokenReq.setResourceOwnerUsername(tenantAwareUserName + "@" + userTenantDomain);
}
AbstractUserStoreManager userStoreManager = getUserStoreManager(userTenantDomain);
AuthenticationResult authenticationResult;
if (userId != null) {
authenticationResult = userStoreManager.authenticateWithID(userId, tokenReq.getResourceOwnerPassword());
} else {
authenticationResult = userStoreManager.authenticateWithID(UserCoreClaimConstants.USERNAME_CLAIM_URI, tenantAwareUserName, tokenReq.getResourceOwnerPassword(), UserCoreConstants.DEFAULT_PROFILE);
}
boolean authenticated = AuthenticationResult.AuthenticationStatus.SUCCESS == authenticationResult.getAuthenticationStatus() && authenticationResult.getAuthenticatedUser().isPresent();
if (log.isDebugEnabled()) {
log.debug("user " + tokenReq.getResourceOwnerUsername() + " authenticated: " + authenticated);
}
if (authenticated) {
AuthenticatedUser authenticatedUser = new AuthenticatedUser(authenticationResult.getAuthenticatedUser().get());
if (isPublishPasswordGrantLoginEnabled) {
publishAuthenticationData(tokenReq, true, serviceProvider, authenticatedUser);
}
return authenticatedUser;
} else {
if (isPublishPasswordGrantLoginEnabled) {
publishAuthenticationData(tokenReq, false, serviceProvider);
}
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(MultitenantUtils.getTenantDomain(tokenReq.getResourceOwnerUsername()))) {
throw new IdentityOAuth2Exception("Authentication failed for " + tenantAwareUserName);
}
username = tokenReq.getResourceOwnerUsername();
if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
// For tenant qualified urls, no need to send fully qualified username in response.
username = tenantAwareUserName;
}
throw new IdentityOAuth2Exception("Authentication failed for " + username);
}
} catch (UserStoreClientException e) {
if (isPublishPasswordGrantLoginEnabled) {
publishAuthenticationData(tokenReq, false, serviceProvider);
}
String message = e.getMessage();
if (StringUtils.isNotBlank(e.getErrorCode())) {
message = e.getErrorCode() + " " + e.getMessage();
}
throw new IdentityOAuth2Exception(message, e);
} catch (UserStoreException e) {
if (isPublishPasswordGrantLoginEnabled) {
publishAuthenticationData(tokenReq, false, serviceProvider);
}
String message = e.getMessage();
// Sometimes client exceptions are wrapped in the super class.
// Therefore, checking for possible client exception.
Throwable rootCause = ExceptionUtils.getRootCause(e);
if (rootCause instanceof UserStoreClientException) {
message = rootCause.getMessage();
String errorCode = ((UserStoreClientException) rootCause).getErrorCode();
if (StringUtils.isNotBlank(errorCode)) {
message = errorCode + " " + message;
}
}
if (e.getCause() instanceof IdentityException) {
IdentityException identityException = (IdentityException) (e.getCause());
// Set error code to message if available.
if (StringUtils.isNotBlank(identityException.getErrorCode())) {
message = identityException.getErrorCode() + " " + e.getMessage();
}
}
throw new IdentityOAuth2Exception(message, e);
} catch (AuthenticationFailedException e) {
String message = "Authentication failed for the user: " + tokenReq.getResourceOwnerUsername();
if (log.isDebugEnabled()) {
log.debug(message, e);
}
throw new IdentityOAuth2Exception(message);
} finally {
UserCoreUtil.removeUserMgtContextInThreadLocal();
if (log.isDebugEnabled()) {
log.debug("UserMgtContext had been remove from the thread local.");
}
}
}
use of org.wso2.carbon.user.core.model.UserMgtContext in project carbon-identity-framework by wso2.
the class DefaultAuthenticationRequestHandler method handle.
/**
* Executes the authentication flow
*
* @param request
* @param response
* @throws FrameworkException
*/
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws FrameworkException {
if (log.isDebugEnabled()) {
log.debug("In authentication flow");
}
if (context.isReturning()) {
// if "Deny" or "Cancel" pressed on the login page.
if (request.getParameter(FrameworkConstants.RequestParams.DENY) != null) {
handleDenyFromLoginPage(request, response, context);
return;
}
// handle remember-me option from the login page
handleRememberMeOptionFromLoginPage(request, context);
}
int currentStep = context.getCurrentStep();
// if this is the start of the authentication flow
if (currentStep == 0) {
handleSequenceStart(request, response, context);
}
SequenceConfig seqConfig = context.getSequenceConfig();
List<AuthenticatorConfig> reqPathAuthenticators = seqConfig.getReqPathAuthenticators();
boolean addOrUpdateNonceCookie = false;
try {
UserStorePreferenceOrderSupplier<List<String>> userStorePreferenceOrderSupplier = FrameworkUtils.getUserStorePreferenceOrderSupplier(context, null);
if (userStorePreferenceOrderSupplier != null) {
// Add the user store preference supplier to the container UserMgtContext.
UserMgtContext userMgtContext = new UserMgtContext();
userMgtContext.setUserStorePreferenceOrderSupplier(userStorePreferenceOrderSupplier);
UserCoreUtil.setUserMgtContextInThreadLocal(userMgtContext);
}
// the flow
if (reqPathAuthenticators != null && !reqPathAuthenticators.isEmpty() && currentStep == 0) {
// call request path sequence handler
FrameworkUtils.getRequestPathBasedSequenceHandler().handle(request, response, context);
}
// if no request path authenticators or handler returned cannot handle
if (!context.getSequenceConfig().isCompleted() || (reqPathAuthenticators == null || reqPathAuthenticators.isEmpty())) {
// To keep track of whether particular request goes through the step based sequence handler.
context.setProperty(FrameworkConstants.STEP_BASED_SEQUENCE_HANDLER_TRIGGERED, true);
// Add or Validate session nonce cookie.
if (isNonceCookieEnabled()) {
String nonceCookieName = getNonceCookieName(context);
if (context.isReturning()) {
if (validateNonceCookie(request, context)) {
addOrUpdateNonceCookie = true;
} else {
throw new FrameworkException(NONCE_ERROR_CODE, "Session nonce cookie value is not " + "matching " + "for session with sessionDataKey: " + request.getParameter("sessionDataKey"));
}
} else if (context.getProperty(nonceCookieName) == null) {
addOrUpdateNonceCookie = true;
}
}
// call step based sequence handler
FrameworkUtils.getStepBasedSequenceHandler().handle(request, response, context);
}
} catch (FrameworkException e) {
// Remove nonce cookie after authentication failure.
removeNonceCookie(request, response, context);
throw e;
} finally {
UserCoreUtil.removeUserMgtContextInThreadLocal();
}
// handle post authentication
try {
handlePostAuthentication(request, response, context);
} catch (FrameworkException e) {
// Remove nonce cookie after post authentication failure.
removeNonceCookie(request, response, context);
throw e;
}
// if flow completed, send response back
if (canConcludeFlow(context)) {
// Remove nonce cookie after authentication completion.
if (addOrUpdateNonceCookie) {
removeNonceCookie(request, response, context);
}
concludeFlow(request, response, context);
} else if (addOrUpdateNonceCookie) {
// Update nonce cookie value.
addNonceCookie(request, response, context);
}
}
Aggregations