use of org.springframework.security.core.AuthenticationException in project gocd by gocd.
the class AbstractBasicAuthenticationFilter method doFilterInternal.
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
try {
if (isPreviouslyAuthenticated(request)) {
LOGGER.debug("Request is already authenticated.");
filterChain.doFilter(request, response);
return;
}
final UsernamePassword credential = BasicAuthHeaderExtractor.extractBasicAuthenticationCredentials(request.getHeader("Authorization"));
if (credential != null) {
LOGGER.debug("[Basic Authentication] Authorization header found for user '{}'", credential.getUsername());
}
if (securityService.isSecurityEnabled()) {
LOGGER.debug("Security is enabled.");
filterWhenSecurityEnabled(request, response, filterChain, credential);
} else {
LOGGER.debug("Security is disabled.");
filterWhenSecurityDisabled(request, response, filterChain, credential);
}
} catch (AuthenticationException e) {
onAuthenticationFailure(request, response, e.getMessage());
}
}
use of org.springframework.security.core.AuthenticationException in project gocd by gocd.
the class AccessTokenAuthenticationFilter method filterWhenSecurityEnabled.
private void filterWhenSecurityEnabled(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, AccessTokenCredential accessTokenCredential) throws IOException, ServletException {
if (accessTokenCredential == null) {
LOGGER.debug("Bearer auth credentials are not provided in request.");
filterChain.doFilter(request, response);
} else {
accessTokenService.updateLastUsedCacheWith(accessTokenCredential.getAccessToken());
ACCESS_TOKEN_LOGGER.debug("[Bearer Token Authentication] Authenticating bearer token for: " + "GoCD User: '{}'. " + "GoCD API endpoint: '{}', " + "API Client: '{}', " + "Is Admin Scoped Token: '{}', " + "Current Time: '{}'.", accessTokenCredential.getAccessToken().getUsername(), request.getRequestURI(), request.getHeader("User-Agent"), securityService.isUserAdmin(new Username(accessTokenCredential.getAccessToken().getUsername())), new Timestamp(System.currentTimeMillis()));
try {
String authConfigId = accessTokenCredential.getAccessToken().getAuthConfigId();
SecurityAuthConfig authConfig = securityAuthConfigService.findProfile(authConfigId);
if (authConfig == null) {
String errorMessage = String.format("Can not find authorization configuration \"%s\" to which the requested personal access token belongs. Authorization Configuration \"%s\" might have been renamed or deleted. Please revoke the existing token and create a new one for the same.", authConfigId, authConfigId);
onAuthenticationFailure(request, response, errorMessage);
return;
}
final AuthenticationToken<AccessTokenCredential> authenticationToken = authenticationProvider.authenticateUser(accessTokenCredential, authConfig);
if (authenticationToken == null) {
onAuthenticationFailure(request, response, BAD_CREDENTIALS_MSG);
} else {
SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
filterChain.doFilter(request, response);
}
} catch (AuthenticationException e) {
LOGGER.debug("Failed to authenticate user.", e);
onAuthenticationFailure(request, response, e.getMessage());
}
}
}
use of org.springframework.security.core.AuthenticationException in project cas by apereo.
the class EndpointLdapAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
try {
val username = authentication.getPrincipal().toString();
val credentials = authentication.getCredentials();
val password = Optional.ofNullable(credentials).map(Object::toString).orElse(null);
if (StringUtils.isBlank(password)) {
throw new IllegalArgumentException("Password cannot be blank");
}
LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
val request = new AuthenticationRequest(username, new Credential(password), ReturnAttributes.ALL.value());
LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
val response = this.authenticator.authenticate(request);
LOGGER.debug("LDAP response: [{}]", response);
if (response.isSuccess()) {
val roles = securityProperties.getUser().getRoles();
if (roles.isEmpty()) {
LOGGER.info("No user security roles are defined to enable authorization. User [{}] is considered authorized", username);
return generateAuthenticationToken(authentication, new ArrayList<>(0));
}
val entry = response.getLdapEntry();
val profile = new CommonProfile();
profile.setId(username);
entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
LOGGER.debug("Collected user profile [{}]", profile);
val context = new JEEContext(HttpRequestUtils.getHttpServletRequestFromRequestAttributes(), HttpRequestUtils.getHttpServletResponseFromRequestAttributes());
val authZGen = buildAuthorizationGenerator();
authZGen.generate(context, JEESessionStore.INSTANCE, profile);
LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
val authorities = profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toCollection(ArrayList::new));
LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
val authorizer = new RequireAnyRoleAuthorizer(roles);
LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
if (authorizer.isAllAuthorized(context, JEESessionStore.INSTANCE, CollectionUtils.wrap(profile))) {
return generateAuthenticationToken(authentication, 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) {
LoggingUtils.error(LOGGER, 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 AuthenticationExceptionContextTest method testDisabledOrNotFound.
@Test
public void testDisabledOrNotFound() {
AuthenticationException e = new IdmAuthenticationException("test");
AuthenticationExceptionContext ctx = new AuthenticationExceptionContext();
ctx.setAuthEx(e);
Assert.assertFalse(ctx.isAuthoritiesChanged());
Assert.assertTrue(ctx.isDisabledOrNotExists());
Assert.assertFalse(ctx.isExpired());
}
use of org.springframework.security.core.AuthenticationException in project ArachneCentralAPI by OHDSI.
the class BaseAuthenticationController method login.
@ApiOperation("Login with specified credentials.")
@RequestMapping(value = "/api/v1/auth/login", method = RequestMethod.POST)
public JsonResult<CommonAuthenticationResponse> login(@Valid @RequestBody CommonAuthenticationRequest authenticationRequest) throws AuthenticationException {
JsonResult<CommonAuthenticationResponse> jsonResult;
String username = authenticationRequest.getUsername();
try {
checkIfUserBlocked(username);
checkIfUserHasTenant(username);
String authToken = authenticationService.authenticateAndGetAuthToken(authenticationRequest);
CommonAuthenticationResponse authenticationResponse = new CommonAuthenticationResponse(authToken);
jsonResult = new JsonResult<>(JsonResult.ErrorCode.NO_ERROR, authenticationResponse);
loginAttemptService.loginSucceeded(username);
} catch (Exception ex) {
jsonResult = getJsonResultForUnsuccessfulLogin(username, ex);
}
// Return the token
return jsonResult;
}
Aggregations