use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class OAuth2AuthenticationProcessingFilter method doFilter.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final boolean debug = logger.isDebugEnabled();
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
try {
Authentication authentication = tokenExtractor.extract(request);
if (authentication == null) {
if (stateless && isAuthenticated()) {
if (debug) {
logger.debug("Clearing security context.");
}
SecurityContextHolder.clearContext();
}
if (debug) {
logger.debug("No token in request, will continue chain.");
}
} else {
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
if (authentication instanceof AbstractAuthenticationToken) {
AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
}
Authentication authResult = authenticationManager.authenticate(authentication);
if (debug) {
logger.debug("Authentication success: " + authResult);
}
eventPublisher.publishAuthenticationSuccess(authResult);
SecurityContextHolder.getContext().setAuthentication(authResult);
}
} catch (OAuth2Exception failed) {
SecurityContextHolder.clearContext();
if (debug) {
logger.debug("Authentication request failed: " + failed);
}
eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed), new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(failed.getMessage(), failed));
return;
}
chain.doFilter(request, response);
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project midpoint by Evolveum.
the class SecurityEnforcerImpl method decide.
/**
* Spring security method. It is practically applicable only for simple cases.
*/
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if (object instanceof MethodInvocation) {
MethodInvocation methodInvocation = (MethodInvocation) object;
// TODO
} else if (object instanceof FilterInvocation) {
FilterInvocation filterInvocation = (FilterInvocation) object;
// TODO
} else {
SecurityUtil.logSecurityDeny(object, ": Unknown type of secure object");
throw new IllegalArgumentException("Unknown type of secure object");
}
Object principalObject = authentication.getPrincipal();
if (!(principalObject instanceof MidPointPrincipal)) {
if (authentication.getPrincipal() instanceof String && "anonymousUser".equals(principalObject)) {
SecurityUtil.logSecurityDeny(object, ": Not logged in");
throw new InsufficientAuthenticationException("Not logged in.");
}
throw new IllegalArgumentException("Expected that spring security principal will be of type " + MidPointPrincipal.class.getName() + " but it was " + principalObject.getClass());
}
Collection<String> configActions = SecurityUtil.getActions(configAttributes);
for (String configAction : configActions) {
boolean isAuthorized;
try {
isAuthorized = isAuthorized(configAction, null, null, null, null, null);
} catch (SchemaException e) {
throw new SystemException(e.getMessage(), e);
}
if (isAuthorized) {
return;
}
}
SecurityUtil.logSecurityDeny(object, ": Not authorized", null, configActions);
// Better message is logged.
throw new AccessDeniedException("Not authorized");
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project midpoint by Evolveum.
the class MidPointGuiAuthorizationEvaluator method decide.
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if (!(object instanceof FilterInvocation)) {
return;
}
FilterInvocation filterInvocation = (FilterInvocation) object;
Collection<ConfigAttribute> guiConfigAttr = new ArrayList<>();
for (PageUrlMapping urlMapping : PageUrlMapping.values()) {
addSecurityConfig(filterInvocation, guiConfigAttr, urlMapping.getUrl(), urlMapping.getAction());
}
Map<String, DisplayableValue<String>[]> actions = DescriptorLoader.getActions();
for (Map.Entry<String, DisplayableValue<String>[]> entry : actions.entrySet()) {
addSecurityConfig(filterInvocation, guiConfigAttr, entry.getKey(), entry.getValue());
}
if (configAttributes == null || guiConfigAttr.isEmpty()) {
return;
}
Collection<ConfigAttribute> configAttributesToUse = guiConfigAttr;
if (guiConfigAttr.isEmpty()) {
configAttributesToUse = configAttributes;
}
try {
securityEnforcer.decide(authentication, object, configAttributesToUse);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("DECIDE: authentication={}, object={}, configAttributesToUse={}: OK", authentication, object, configAttributesToUse);
}
} catch (AccessDeniedException | InsufficientAuthenticationException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("DECIDE: authentication={}, object={}, configAttributesToUse={}: {}", authentication, object, configAttributesToUse, e);
}
throw e;
}
}
use of org.springframework.security.authentication.InsufficientAuthenticationException 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");
}
Aggregations