use of org.springframework.security.core.AuthenticationException in project pentaho-platform by pentaho.
the class SpringSecurityLoginModule method getAuthentication.
/**
* {@inheritDoc}
*
* Creates a {@code UsernamePasswordAuthenticationToken} from the given {@code principal} and {@code credentials}
* and passes to Spring Security {@code AuthenticationManager}.
*/
@Override
protected Authentication getAuthentication(final Principal principal, final Credentials credentials) throws RepositoryException {
// only handles SimpleCredential instances; DefaultLoginModule behaves the same way (albeit indirectly)
if (!(credentials instanceof SimpleCredentials)) {
// $NON-NLS-1$
logger.debug("credentials not instance of SimpleCredentials; returning null");
return null;
}
SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(simpleCredentials.getUserID(), String.valueOf(simpleCredentials.getPassword()));
boolean authenticated = false;
try {
org.springframework.security.core.Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getName().equals(simpleCredentials.getUserID())) {
// see if there's already an active Authentication for this user.
authenticated = true;
} else {
// delegate to Spring Security
getAuthenticationManager().authenticate(token);
authenticated = true;
}
} catch (AuthenticationException e) {
// $NON-NLS-1$
logger.debug("authentication exception", e);
}
final boolean authenticateResult = authenticated;
return new Authentication() {
public boolean canHandle(Credentials credentials) {
// this is decided earlier in getAuthentication
return true;
}
public boolean authenticate(Credentials credentials) throws RepositoryException {
return authenticateResult;
}
};
}
use of org.springframework.security.core.AuthenticationException in project pentaho-platform by pentaho.
the class UserRoleDaoService method updatePassword.
public void updatePassword(User user, String administratorPassword) throws SecurityException {
final IPentahoSession pentahoSession = PentahoSessionHolder.getSession();
AuthenticationProvider authenticator = PentahoSystem.get(AuthenticationProvider.class, pentahoSession);
if (authenticator == null) {
throw new SecurityException("Authentication Provider not found, can not re-authenticate logged-in user");
}
try {
Authentication authentication = authenticator.authenticate(new UsernamePasswordAuthenticationToken(pentahoSession.getName(), administratorPassword));
if (authentication.isAuthenticated()) {
updatePassword(user);
} else {
throw new SecurityException("Logged-in user re-authentication failed");
}
} catch (AuthenticationException e) {
throw new SecurityException("Logged-in user re-authentication failed", e);
}
}
use of org.springframework.security.core.AuthenticationException in project ORCID-Source by ORCID.
the class OauthLoginController method authenticateAndAuthorize.
@RequestMapping(value = { "/oauth/custom/signin.json", "/oauth/custom/login.json" }, method = RequestMethod.POST)
@ResponseBody
public OauthAuthorizeForm authenticateAndAuthorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
// Clean form errors
form.setErrors(new ArrayList<String>());
RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
boolean willBeRedirected = false;
if (form.getApproved()) {
// Validate name and password
validateUserNameAndPassword(form);
if (form.getErrors().isEmpty()) {
try {
// Authenticate user
copy2FAFields(form, request);
Authentication auth = authenticateUser(request, form.getUserName().getValue(), form.getPassword().getValue());
profileEntityManager.updateLastLoginDetails(auth.getName(), OrcidRequestUtil.getIpAddress(request));
// Create authorization params
SimpleSessionStatus status = new SimpleSessionStatus();
Map<String, Object> model = new HashMap<String, Object>();
Map<String, String> params = new HashMap<String, String>();
Map<String, String> approvalParams = new HashMap<String, String>();
fillOauthParams(requestInfoForm, params, approvalParams, form.getPersistentTokenEnabled(), form.isEmailAccessAllowed());
// Authorize
try {
authorizationEndpoint.authorize(model, params, status, auth);
} catch (RedirectMismatchException rUriError) {
String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
// Set the client id
redirectUri = redirectUri.replace("{0}", requestInfoForm.getClientId());
// Set the response type if needed
if (!PojoUtil.isEmpty(requestInfoForm.getResponseType()))
redirectUri += "&response_type=" + requestInfoForm.getResponseType();
// Set the redirect uri
if (!PojoUtil.isEmpty(requestInfoForm.getRedirectUrl()))
redirectUri += "&redirect_uri=" + requestInfoForm.getRedirectUrl();
// Set the scope param
if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()))
redirectUri += "&scope=" + requestInfoForm.getScopesAsString();
// Copy the state param if present
if (!PojoUtil.isEmpty(requestInfoForm.getStateParam()))
redirectUri += "&state=" + requestInfoForm.getStateParam();
form.setRedirectUrl(redirectUri);
LOGGER.info("OauthLoginController being sent to client browser: " + form.getRedirectUrl());
return form;
}
// Approve
RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
form.setRedirectUrl(view.getUrl());
willBeRedirected = true;
} catch (AuthenticationException ae) {
if (ae.getCause() instanceof DisabledException) {
// Handle this message in angular to allow AJAX action
form.getErrors().add("orcid.frontend.security.orcid_deactivated");
} else if (ae.getCause() instanceof UnclaimedProfileExistsException) {
String email = PojoUtil.isEmpty(form.getUserName()) ? null : form.getUserName().getValue();
String resendEmailUrl = createResendClaimUrl(email, request);
String errorMessage = getMessage("orcid.frontend.security.unclaimed_exists_1");
errorMessage += "<a href=\"" + resendEmailUrl + "\">";
errorMessage += getMessage("orcid.frontend.security.unclaimed_exists_2");
errorMessage += "</a>" + getMessage("orcid.frontend.security.unclaimed_exists_3");
form.getErrors().add(errorMessage);
} else if (ae instanceof VerificationCodeFor2FARequiredException) {
form.setVerificationCodeRequired(true);
} else if (ae instanceof Bad2FAVerificationCodeException) {
form.getErrors().add(getMessage("orcid.frontend.security.2fa.bad_verification_code"));
} else if (ae instanceof Bad2FARecoveryCodeException) {
form.getErrors().add(getMessage("orcid.frontend.security.2fa.bad_recovery_code"));
} else {
form.getErrors().add(getMessage("orcid.frontend.security.bad_credentials"));
}
}
}
} else {
form.setRedirectUrl(buildDenyRedirectUri(requestInfoForm.getRedirectUrl(), requestInfoForm.getStateParam()));
willBeRedirected = true;
}
// not be redirected yet
if (willBeRedirected) {
if (new HttpSessionRequestCache().getRequest(request, response) != null)
new HttpSessionRequestCache().removeRequest(request, response);
LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + requestInfoForm.getRedirectUrl());
}
return form;
}
use of org.springframework.security.core.AuthenticationException in project ORCID-Source by ORCID.
the class ClaimController method automaticallyLogin.
private void automaticallyLogin(HttpServletRequest request, String password, String orcid) {
UsernamePasswordAuthenticationToken token = null;
try {
token = new UsernamePasswordAuthenticationToken(orcid, password);
token.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (AuthenticationException e) {
// this should never happen
SecurityContextHolder.getContext().setAuthentication(null);
LOGGER.warn("User " + orcid + " should have been logged-in, but we unable to due to a problem", e, (token != null ? token.getPrincipal() : "empty principle"));
}
}
use of org.springframework.security.core.AuthenticationException in project ORCID-Source by ORCID.
the class ShibbolethController method post2FAVerificationCode.
@RequestMapping(value = { "/2FA/submitCode.json" }, method = RequestMethod.POST)
@ResponseBody
public TwoFactorAuthenticationCodes post2FAVerificationCode(@RequestBody TwoFactorAuthenticationCodes codes, HttpServletRequest request, HttpServletResponse response, @RequestHeader Map<String, String> headers) {
checkEnabled();
String shibIdentityProvider = headers.get(InstitutionalSignInManager.SHIB_IDENTITY_PROVIDER_HEADER);
RemoteUser remoteUser = institutionalSignInManager.retrieveRemoteUser(headers);
if (remoteUser == null) {
LOGGER.info("Failed federated log in for {}", shibIdentityProvider);
identityProviderManager.incrementFailedCount(shibIdentityProvider);
codes.setRedirectUrl(orcidUrlManager.getBaseUrl() + "/shibboleth/signin");
return codes;
}
UserconnectionEntity userConnectionEntity = userConnectionManager.findByProviderIdAndProviderUserIdAndIdType(remoteUser.getUserId(), shibIdentityProvider, remoteUser.getIdType());
if (userConnectionEntity != null) {
LOGGER.info("Found existing user connection: {}", userConnectionEntity);
HeaderCheckResult checkHeadersResult = institutionalSignInManager.checkHeaders(parseOriginalHeaders(userConnectionEntity.getHeadersJson()), headers);
if (!checkHeadersResult.isSuccess()) {
codes.setRedirectUrl(orcidUrlManager.getBaseUrl() + "/shibboleth/signin");
return codes;
}
validate2FACodes(userConnectionEntity.getOrcid(), codes);
if (!codes.getErrors().isEmpty()) {
return codes;
}
try {
notifyUser(shibIdentityProvider, userConnectionEntity);
processAuthentication(remoteUser, userConnectionEntity);
} catch (AuthenticationException e) {
// this should never happen
SecurityContextHolder.getContext().setAuthentication(null);
LOGGER.warn("User {0} should have been logged-in via Shibboleth, but was unable to due to a problem", remoteUser, e);
}
codes.setRedirectUrl(calculateRedirectUrl(request, response));
return codes;
} else {
codes.setRedirectUrl(orcidUrlManager.getBaseUrl() + "/shibboleth/signin");
return codes;
}
}
Aggregations