use of org.springframework.security.core.AuthenticationException in project OpenClinica by OpenClinica.
the class OpenClinicaUsernamePasswordAuthenticationFilter method attemptAuthentication.
//~ Methods ========================================================================================================
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// Place the last username attempted into HttpSession for views
HttpSession session = request.getSession(false);
if (session != null || getAllowSessionCreation()) {
request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextEscapeUtils.escapeEntities(username));
}
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
Authentication authentication = null;
UserAccountBean userAccountBean = null;
ResourceBundleProvider.updateLocale(new Locale("en_US"));
try {
EntityBean eb = getUserAccountDao().findByUserName(username);
userAccountBean = eb.getId() != 0 ? (UserAccountBean) eb : null;
authentication = this.getAuthenticationManager().authenticate(authRequest);
auditUserLogin(username, LoginStatus.SUCCESSFUL_LOGIN, userAccountBean);
resetLockCounter(username, LoginStatus.SUCCESSFUL_LOGIN, userAccountBean);
} catch (LockedException le) {
auditUserLogin(username, LoginStatus.FAILED_LOGIN_LOCKED, userAccountBean);
throw le;
} catch (BadCredentialsException au) {
auditUserLogin(username, LoginStatus.FAILED_LOGIN, userAccountBean);
lockAccount(username, LoginStatus.FAILED_LOGIN, userAccountBean);
throw au;
} catch (AuthenticationException ae) {
throw ae;
}
return authentication;
}
use of org.springframework.security.core.AuthenticationException in project libresonic by Libresonic.
the class RESTRequestParameterProcessingFilter method authenticate.
private RESTController.ErrorCode authenticate(String username, String password, String salt, String token, Authentication previousAuth) {
// Previously authenticated and username not overridden?
if (username == null && previousAuth != null) {
return null;
}
if (salt != null && token != null) {
User user = securityService.getUserByName(username);
if (user == null) {
return RESTController.ErrorCode.NOT_AUTHENTICATED;
}
String expectedToken = DigestUtils.md5Hex(user.getPassword() + salt);
if (!expectedToken.equals(token)) {
return RESTController.ErrorCode.NOT_AUTHENTICATED;
}
password = user.getPassword();
}
if (password != null) {
try {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
Authentication authResult = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(authResult);
return null;
} catch (AuthenticationException x) {
return RESTController.ErrorCode.NOT_AUTHENTICATED;
}
}
return RESTController.ErrorCode.MISSING_PARAMETER;
}
use of org.springframework.security.core.AuthenticationException in project cas by apereo.
the class LdapAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
try {
final String username = authentication.getPrincipal().toString();
final Object credentials = authentication.getCredentials();
final String password = credentials == null ? null : credentials.toString();
LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
final AuthenticationRequest request = new AuthenticationRequest(username, new org.ldaptive.Credential(password), ReturnAttributes.ALL.value());
final Authenticator authenticator = LdapUtils.newLdaptiveAuthenticator(adminPagesSecurityProperties.getLdap());
LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
final AuthenticationResponse response = authenticator.authenticate(request);
LOGGER.debug("LDAP response: [{}]", response);
if (response.getResult()) {
final LdapEntry entry = response.getLdapEntry();
final CommonProfile profile = new CommonProfile();
profile.setId(username);
entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
LOGGER.debug("Collected user profile [{}]", profile);
this.authorizationGenerator.generate(Pac4jUtils.getPac4jJ2EContext(), profile);
LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
final Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.addAll(profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
final RequireAnyRoleAuthorizer authorizer = new RequireAnyRoleAuthorizer(adminPagesSecurityProperties.getAdminRoles());
LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
final J2EContext context = Pac4jUtils.getPac4jJ2EContext();
if (authorizer.isAllAuthorized(context, CollectionUtils.wrap(profile))) {
return new UsernamePasswordAuthenticationToken(username, password, authorities);
}
LOGGER.warn("User [{}] is not authorized to access the requested resource allowed to roles [{}]", username, authorizer.getElements());
} else {
LOGGER.warn("LDAP authentication response produced no results for [{}]", username);
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new InsufficientAuthenticationException("Unexpected LDAP error", e);
}
throw new BadCredentialsException("Could not authenticate provided credentials");
}
use of org.springframework.security.core.AuthenticationException in project CzechIdMng by bcvsolutions.
the class JwtIdmAuthenticationFilter method authorize.
@Override
public boolean authorize(String token, HttpServletRequest request, HttpServletResponse response) {
IdmJwtAuthenticationDto claims = null;
try {
Optional<Jwt> jwt = HttpFilterUtils.parseToken(token);
if (!jwt.isPresent()) {
return false;
}
HttpFilterUtils.verifyToken(jwt.get(), jwtTokenMapper.getVerifier());
claims = jwtTokenMapper.getClaims(jwt.get());
ctx.setToken(claims);
Authentication auth = authenticationManager.authenticate(jwtTokenMapper.fromDto(claims));
LOG.debug("User [{}] successfully logged in.", auth.getName());
return auth.isAuthenticated();
} catch (ResultCodeException ex) {
LOG.warn("Invalid token, reason: [{}]", ex.getMessage());
ctx.setCodeEx(ex);
// only expired or authorities changed
ctx.setToken(claims);
} catch (AuthenticationException ex) {
LOG.warn("Invalid authentication, reason: [{}]", ex.getMessage());
ctx.setAuthEx(ex);
} catch (InvalidSignatureException | IOException | IllegalArgumentException ex) {
// client sent some rubbish, just log and ignore
LOG.warn("Invalid IdM auth token received.", ex);
}
return false;
}
use of org.springframework.security.core.AuthenticationException in project CzechIdMng by bcvsolutions.
the class OAuthAuthenticationManagerTest method testIdentityNotExists.
/**
* Non-existent identities cannot possess auth. tokens.
*/
@Test
public void testIdentityNotExists() {
IdmJwtAuthentication authentication = getAuthentication(USER_NAME, DateTime.now().plusHours(1), DateTime.now());
when(identityService.getByUsername(USER_NAME)).thenReturn(null);
try {
authManager.authenticate(authentication);
Assert.fail("Cannot authenticate unknown identity.");
} catch (AuthenticationException e) {
verify(identityService).getByUsername(USER_NAME);
}
}
Aggregations