use of org.springframework.security.core.AuthenticationException in project spring-security by spring-projects.
the class RememberMeAuthenticationFilter method doFilter.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (SecurityContextHolder.getContext().getAuthentication() == null) {
Authentication rememberMeAuth = rememberMeServices.autoLogin(request, response);
if (rememberMeAuth != null) {
// Attempt authenticaton via AuthenticationManager
try {
rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);
// Store to SecurityContextHolder
SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);
onSuccessfulAuthentication(request, response, rememberMeAuth);
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder populated with remember-me token: '" + SecurityContextHolder.getContext().getAuthentication() + "'");
}
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(SecurityContextHolder.getContext().getAuthentication(), this.getClass()));
}
if (successHandler != null) {
successHandler.onAuthenticationSuccess(request, response, rememberMeAuth);
return;
}
} catch (AuthenticationException authenticationException) {
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder not populated with remember-me token, as " + "AuthenticationManager rejected Authentication returned by RememberMeServices: '" + rememberMeAuth + "'; invalidating remember-me token", authenticationException);
}
rememberMeServices.loginFail(request, response);
onUnsuccessfulAuthentication(request, response, authenticationException);
}
}
chain.doFilter(request, response);
} else {
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder not populated with remember-me token, as it already contained: '" + SecurityContextHolder.getContext().getAuthentication() + "'");
}
chain.doFilter(request, response);
}
}
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 nifi by apache.
the class AccessResource method createAccessTokenFromTicket.
/**
* Creates a token for accessing the REST API via Kerberos ticket exchange / SPNEGO negotiation.
*
* @param httpServletRequest the servlet request
* @return A JWT (string)
*/
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@Path("/kerberos")
@ApiOperation(value = "Creates a token for accessing the REST API via Kerberos ticket exchange / SPNEGO negotiation", notes = "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, " + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header " + "in the format 'Authorization: Bearer <token>'.", response = String.class)
@ApiResponses(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "NiFi was unable to complete the request because it did not contain a valid Kerberos " + "ticket in the Authorization header. Retry this request after initializing a ticket with kinit and " + "ensuring your browser is configured to support SPNEGO."), @ApiResponse(code = 409, message = "Unable to create access token because NiFi is not in the appropriate state. (i.e. may not be configured to support Kerberos login."), @ApiResponse(code = 500, message = "Unable to create access token because an unexpected error occurred.") })
public Response createAccessTokenFromTicket(@Context HttpServletRequest httpServletRequest) {
// only support access tokens when communicating over HTTPS
if (!httpServletRequest.isSecure()) {
throw new IllegalStateException("Access tokens are only issued over HTTPS.");
}
// If Kerberos Service Principal and keytab location not configured, throws exception
if (!properties.isKerberosSpnegoSupportEnabled() || kerberosService == null) {
throw new IllegalStateException("Kerberos ticket login not supported by this NiFi.");
}
String authorizationHeaderValue = httpServletRequest.getHeader(KerberosService.AUTHORIZATION_HEADER_NAME);
if (!kerberosService.isValidKerberosHeader(authorizationHeaderValue)) {
final Response response = generateNotAuthorizedResponse().header(KerberosService.AUTHENTICATION_CHALLENGE_HEADER_NAME, KerberosService.AUTHORIZATION_NEGOTIATE).build();
return response;
} else {
try {
// attempt to authenticate
Authentication authentication = kerberosService.validateKerberosTicket(httpServletRequest);
if (authentication == null) {
throw new IllegalArgumentException("Request is not HTTPS or Kerberos ticket missing or malformed");
}
final String expirationFromProperties = properties.getKerberosAuthenticationExpiration();
long expiration = FormatUtils.getTimeDuration(expirationFromProperties, TimeUnit.MILLISECONDS);
final String identity = authentication.getName();
expiration = validateTokenExpiration(expiration, identity);
// create the authentication token
final LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken(identity, expiration, "KerberosService");
// generate JWT for response
final String token = jwtService.generateSignedToken(loginAuthenticationToken);
// build the response
final URI uri = URI.create(generateResourceUri("access", "kerberos"));
return generateCreatedResponse(uri, token).build();
} catch (final AuthenticationException e) {
throw new AccessDeniedException(e.getMessage(), e);
}
}
}
use of org.springframework.security.core.AuthenticationException in project nifi by apache.
the class NiFiAuthenticationFilter method authenticate.
private void authenticate(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
String dnChain = null;
try {
final Authentication authenticationRequest = attemptAuthentication(request);
if (authenticationRequest != null) {
// log the request attempt - response details will be logged later
log.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", authenticationRequest.toString(), request.getMethod(), request.getRequestURL().toString(), request.getRemoteAddr()));
// attempt to authorize the user
final Authentication authenticated = authenticationManager.authenticate(authenticationRequest);
successfulAuthorization(request, response, authenticated);
}
// continue
chain.doFilter(request, response);
} catch (final AuthenticationException ae) {
// invalid authentication - always error out
unsuccessfulAuthorization(request, response, ae);
}
}
Aggregations