use of org.springframework.security.authentication.DisabledException 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.authentication.DisabledException in project syncope by apache.
the class AuthDataAccessor method authenticate.
@Transactional
public Pair<String, Set<SyncopeGrantedAuthority>> authenticate(final JWTAuthentication authentication) {
String username;
Set<SyncopeGrantedAuthority> authorities;
if (adminUser.equals(authentication.getClaims().getSubject())) {
AccessToken accessToken = accessTokenDAO.find(authentication.getClaims().getTokenId());
if (accessToken == null) {
throw new AuthenticationCredentialsNotFoundException("Could not find an Access Token for JWT " + authentication.getClaims().getTokenId());
}
username = adminUser;
authorities = getAdminAuthorities();
} else {
JWTSSOProvider jwtSSOProvider = getJWTSSOProvider(authentication.getClaims().getIssuer());
Pair<User, Set<SyncopeGrantedAuthority>> resolved = jwtSSOProvider.resolve(authentication.getClaims());
if (resolved == null || resolved.getLeft() == null) {
throw new AuthenticationCredentialsNotFoundException("Could not find User " + authentication.getClaims().getSubject() + " for JWT " + authentication.getClaims().getTokenId());
}
User user = resolved.getLeft();
username = user.getUsername();
authorities = resolved.getRight() == null ? Collections.emptySet() : resolved.getRight();
LOG.debug("JWT {} issued by {} resolved to User {} with authorities {}", authentication.getClaims().getTokenId(), authentication.getClaims().getIssuer(), username, authorities);
if (BooleanUtils.isTrue(user.isSuspended())) {
throw new DisabledException("User " + username + " is suspended");
}
Optional<? extends CPlainAttr> authStatuses = confDAO.find("authentication.statuses");
if (authStatuses.isPresent() && !authStatuses.get().getValuesAsStrings().contains(user.getStatus())) {
throw new DisabledException("User " + username + " not allowed to authenticate");
}
if (BooleanUtils.isTrue(user.isMustChangePassword())) {
LOG.debug("User {} must change password, resetting authorities", username);
authorities = Collections.singleton(new SyncopeGrantedAuthority(StandardEntitlement.MUST_CHANGE_PASSWORD));
}
}
return Pair.of(username, authorities);
}
use of org.springframework.security.authentication.DisabledException in project syncope by apache.
the class AuthDataAccessor method authenticate.
/**
* Attempts to authenticate the given credentials against internal storage and pass-through resources (if
* configured): the first succeeding causes global success.
*
* @param authentication given credentials
* @return {@code null} if no matching user was found, authentication result otherwise
*/
@Transactional(noRollbackFor = DisabledException.class)
public Pair<User, Boolean> authenticate(final Authentication authentication) {
User user = null;
Optional<? extends CPlainAttr> authAttrs = confDAO.find("authentication.attributes");
List<String> authAttrValues = authAttrs.isPresent() ? authAttrs.get().getValuesAsStrings() : Collections.singletonList("username");
for (int i = 0; user == null && i < authAttrValues.size(); i++) {
if ("username".equals(authAttrValues.get(i))) {
user = userDAO.findByUsername(authentication.getName());
} else {
AttributeCond attrCond = new AttributeCond(AttributeCond.Type.EQ);
attrCond.setSchema(authAttrValues.get(i));
attrCond.setExpression(authentication.getName());
List<User> users = searchDAO.search(SearchCond.getLeafCond(attrCond), AnyTypeKind.USER);
if (users.size() == 1) {
user = users.get(0);
} else {
LOG.warn("Value {} provided for {} does not uniquely identify a user", authentication.getName(), authAttrValues.get(i));
}
}
}
Boolean authenticated = null;
if (user != null) {
authenticated = false;
if (user.isSuspended() != null && user.isSuspended()) {
throw new DisabledException("User " + user.getUsername() + " is suspended");
}
Optional<? extends CPlainAttr> authStatuses = confDAO.find("authentication.statuses");
if (authStatuses.isPresent() && !authStatuses.get().getValuesAsStrings().contains(user.getStatus())) {
throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
}
boolean userModified = false;
authenticated = AuthDataAccessor.this.authenticate(user, authentication.getCredentials().toString());
if (authenticated) {
if (confDAO.find("log.lastlogindate", true)) {
user.setLastLoginDate(new Date());
userModified = true;
}
if (user.getFailedLogins() != 0) {
user.setFailedLogins(0);
userModified = true;
}
} else {
user.setFailedLogins(user.getFailedLogins() + 1);
userModified = true;
}
if (userModified) {
userDAO.save(user);
}
}
return ImmutablePair.of(user, authenticated);
}
use of org.springframework.security.authentication.DisabledException in project irida by phac-nml.
the class CredentialsExpiredAuthenticationFailureHandlerTest method testOnAuthenticationFailureWithOtherException.
@Test
public void testOnAuthenticationFailureWithOtherException() throws IOException, ServletException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
AuthenticationException exception = new DisabledException("disabled");
handler.onAuthenticationFailure(request, response, exception);
verifyZeroInteractions(userService);
verifyZeroInteractions(resetService);
}
use of org.springframework.security.authentication.DisabledException in project ma-core-public by infiniteautomation.
the class LoginController method initForm.
@RequestMapping(method = RequestMethod.GET)
public String initForm(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("login") LoginForm loginForm, BindingResult result) {
BindException errors = new BindException(result);
HttpSession session = request.getSession(false);
if (session != null) {
AuthenticationException ex = (AuthenticationException) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
if (ex != null) {
if (ex instanceof DisabledException) {
errors.reject("login.validation.accountDisabled", ex.getMessage());
} else {
errors.reject("login.validation.invalidLogin", ex.getMessage());
}
}
String username = (String) session.getAttribute("username");
if (username != null && !username.isEmpty()) {
loginForm.setUsername(username);
}
}
return "/WEB-INF/jsp/login.jsp";
}
Aggregations