use of org.springframework.security.authentication.AuthenticationServiceException in project spring-security by spring-projects.
the class DigestAuthenticationFilter method doFilter.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Digest ")) {
chain.doFilter(request, response);
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Digest Authorization header received from user agent: " + header);
}
DigestData digestAuth = new DigestData(header);
try {
digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(), this.authenticationEntryPoint.getRealmName());
} catch (BadCredentialsException e) {
fail(request, response, e);
return;
}
// Lookup password for presented username
// NB: DAO-provided password MUST be clear text - not encoded/salted
// (unless this instance's passwordAlreadyEncoded property is 'false')
boolean cacheWasUsed = true;
UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername());
String serverDigestMd5;
try {
if (user == null) {
cacheWasUsed = false;
user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
if (user == null) {
throw new AuthenticationServiceException("AuthenticationDao returned null, which is an interface contract violation");
}
this.userCache.putUserInCache(user);
}
serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
// If digest is incorrect, try refreshing from backend and recomputing
if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
if (logger.isDebugEnabled()) {
logger.debug("Digest comparison failure; trying to refresh user from DAO in case password had changed");
}
user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
this.userCache.putUserInCache(user);
serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
}
} catch (UsernameNotFoundException notFound) {
fail(request, response, new BadCredentialsException(this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound", new Object[] { digestAuth.getUsername() }, "Username {0} not found")));
return;
}
// If digest is still incorrect, definitely reject authentication attempt
if (!serverDigestMd5.equals(digestAuth.getResponse())) {
if (logger.isDebugEnabled()) {
logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '" + digestAuth.getResponse() + "'; is AuthenticationDao returning clear text passwords?");
}
fail(request, response, new BadCredentialsException(this.messages.getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response")));
return;
}
// but the request was otherwise appearing to be valid
if (digestAuth.isNonceExpired()) {
fail(request, response, new NonceExpiredException(this.messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out")));
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '" + digestAuth.getResponse() + "'");
}
Authentication authentication = createSuccessfulAuthentication(request, user);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
chain.doFilter(request, response);
}
use of org.springframework.security.authentication.AuthenticationServiceException 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.authentication.AuthenticationServiceException in project opennms by OpenNMS.
the class RadiusAuthenticationProvider method retrieveUser.
/* (non-Javadoc)
* @see org.springframework.security.providers.dao.AbstractUserDetailsAuthenticationProvider#retrieveUser(java.lang.String, org.springframework.security.providers.UsernamePasswordAuthenticationToken)
*/
/** {@inheritDoc} */
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken token) throws AuthenticationException {
if (!StringUtils.hasLength(username)) {
LOG.info("Authentication attempted with empty username");
throw new BadCredentialsException(messages.getMessage("RadiusAuthenticationProvider.emptyUsername", "Username cannot be empty"));
}
String password = (String) token.getCredentials();
if (!StringUtils.hasLength(password)) {
LOG.info("Authentication attempted with empty password");
throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
}
InetAddress serverIP = null;
serverIP = InetAddressUtils.addr(server);
if (serverIP == null) {
LOG.error("Could not resolve radius server address {}", server);
throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.unknownServer", "Could not resolve radius server address"));
}
AttributeFactory.loadAttributeDictionary("net.jradius.dictionary.AttributeDictionaryImpl");
AttributeList attributeList = new AttributeList();
attributeList.add(new Attr_UserName(username));
attributeList.add(new Attr_UserPassword(password));
RadiusPacket reply;
try {
RadiusClient radiusClient = new RadiusClient(serverIP, secret, port, port + 1, timeout);
AccessRequest request = new AccessRequest(radiusClient, attributeList);
LOG.debug("Sending AccessRequest message to {}:{} using {} protocol with timeout = {}, retries = {}, attributes:\n{}", InetAddressUtils.str(serverIP), port, (authTypeClass == null ? "PAP" : authTypeClass.getAuthName()), timeout, retries, attributeList.toString());
reply = radiusClient.authenticate(request, authTypeClass, retries);
} catch (RadiusException e) {
LOG.error("Error connecting to radius server {} : {}", server, e);
throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError", new Object[] { e }, "Error connecting to radius server: " + e));
} catch (IOException e) {
LOG.error("Error connecting to radius server {} : {}", server, e);
throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError", new Object[] { e }, "Error connecting to radius server: " + e));
}
if (reply == null) {
LOG.error("Timed out connecting to radius server {}", server);
throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusTimeout", "Timed out connecting to radius server"));
}
if (!(reply instanceof AccessAccept)) {
LOG.info("Received a reply other than AccessAccept from radius server {} for user {} :\n{}", server, username, reply.toString());
throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
}
LOG.debug("Received AccessAccept message from {}:{} for user {} with attributes:\n{}", InetAddressUtils.str(serverIP), port, username, reply.getAttributes().toString());
String roles = null;
if (!StringUtils.hasLength(rolesAttribute)) {
LOG.debug("rolesAttribute not set, using default roles ({}) for user {}", defaultRoles, username);
roles = new String(defaultRoles);
} else {
Iterator<RadiusAttribute> attributes = reply.getAttributes().getAttributeList().iterator();
while (attributes.hasNext()) {
RadiusAttribute attribute = attributes.next();
if (rolesAttribute.equals(attribute.getAttributeName())) {
roles = new String(attribute.getValue().getBytes());
break;
}
}
if (roles == null) {
LOG.info("Radius attribute {} not found, using default roles ({}) for user {}", rolesAttribute, defaultRoles, username);
roles = new String(defaultRoles);
}
}
String[] rolesArray = roles.replaceAll("\\s*", "").split(",");
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(rolesArray.length);
for (String role : rolesArray) {
authorities.add(new SimpleGrantedAuthority(role));
}
StringBuffer readRoles = new StringBuffer();
for (GrantedAuthority authority : authorities) {
readRoles.append(authority.toString() + ", ");
}
if (readRoles.length() > 0) {
readRoles.delete(readRoles.length() - 2, readRoles.length());
}
LOG.debug("Parsed roles {} for user {}", readRoles, username);
return new User(username, password, true, true, true, true, authorities);
}
use of org.springframework.security.authentication.AuthenticationServiceException in project midpoint by Evolveum.
the class AuthenticationEvaluatorImpl method getCredentialsPolicy.
private CredentialPolicyType getCredentialsPolicy(MidPointPrincipal principal, T authnCtx) {
SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
CredentialPolicyType credentialsPolicy = null;
try {
credentialsPolicy = getEffectiveCredentialPolicy(securityPolicy, authnCtx);
} catch (SchemaException e) {
// TODO how to properly hanlde the error????
throw new AuthenticationServiceException("Bad config");
}
return credentialsPolicy;
}
use of org.springframework.security.authentication.AuthenticationServiceException in project midpoint by Evolveum.
the class AuthenticationEvaluatorImpl method decryptAndMatch.
// protected boolean matchDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, String decryptedValue,
// String enteredPassword){
// return enteredPassword.equals(decryptedValue);
// }
//
protected boolean decryptAndMatch(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, String enteredPassword) {
ProtectedStringType entered = new ProtectedStringType();
entered.setClearValue(enteredPassword);
try {
return protector.compare(entered, protectedString);
} catch (SchemaException | EncryptionException e) {
recordAuthenticationFailure(principal, connEnv, "error decrypting password: " + e.getMessage());
throw new AuthenticationServiceException("web.security.provider.unavailable", e);
}
}
Aggregations