@Override protected UserDetails retrieveUser( String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { return MySQLSecurityRealm.this.authenticate( username, authentication.getCredentials().toString()); }
/** * @param authentication null if we are just retrieving the said user, instead of trying to * authenticate. */ private UserDetails retrieveUser( String username, UsernamePasswordAuthenticationToken authentication, String domainName) throws AuthenticationException { // when we use custom socket factory below, every LDAP operations result // in a classloading via context classloader, so we need it to resolve. ClassLoader ccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { String password = NO_AUTHENTICATION; if (authentication != null) password = (String) authentication.getCredentials(); return retrieveUser(username, password, domainName, obtainLDAPServers(domainName)); } finally { Thread.currentThread().setContextClassLoader(ccl); } }
/** 具体验证用户登陆的方法 */ protected void additionalAuthenticationChecks( UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { this.isVailedSystemAdmin = this.isSystemAdmin(userDetails); SecurityMessageInfo smi = new SecurityMessageInfo(); // add by zhangpengf for sso in 2009-12-15 begin if ("SP_SSO".equals(authentication.getCredentials().toString().trim())) { String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName(); if ("NONE_PROVIDED".equals(username)) { String msg = messages.getMessage("system.security.ssoExpired", "未找到该用户,请检查是否输入正确!"); smi.setMessage(msg); UserContext.setLoginMessage("loginerror", smi); throw new BadCredentialsException(msg, userDetails); } else if (!username.trim().toLowerCase().equals(userDetails.getUsername().toLowerCase())) { String msg = messages.getMessage("system.security.ssoExpired", "未找到该用户,请检查是否输入正确!"); smi.setMessage(msg); UserContext.setLoginMessage("loginerror", smi); throw new BadCredentialsException(msg, userDetails); } } else { if (userDetails.isSpecialUser() || !Boolean.valueOf(this.isLdap).booleanValue()) { Object salt = null; if (this.saltSource != null) { salt = this.saltSource.getSalt(userDetails); } if (!passwordEncoder.isPasswordValid( userDetails.getPassword(), authentication.getCredentials().toString(), salt)) { String msg = messages.getMessage( "system.security.dbExpired", "验证错误,请检查您输入的用户名密码是您在本系统中设定的用户名以及密码!"); smi.setMessage(msg); UserContext.setLoginMessage("loginerror", smi); throw new BadCredentialsException(msg, userDetails); } } else if (Boolean.valueOf(this.isLdap).booleanValue()) { try { boolean isAuth = false; System.out.println( "The User Check Type Is : " + this.messages.getMessage("system.security.authtype", "ldap")); if ("ldap" .equalsIgnoreCase(this.messages.getMessage("system.security.authtype", "ldap"))) { isAuth = ldap.IsAuthenticatedByLdap( authentication.getName().toLowerCase(), authentication.getCredentials().toString()); } else if ("notes" .equalsIgnoreCase(this.messages.getMessage("system.security.authtype", "ldap"))) { isAuth = ldap.IsAuthenticated( authentication.getName().toLowerCase(), authentication.getCredentials().toString()); } if (!isAuth) { if (isVailedSystemAdmin) { Object salt = null; if (this.saltSource != null) { salt = this.saltSource.getSalt(userDetails); } if (!passwordEncoder.isPasswordValid( userDetails.getPassword(), authentication.getCredentials().toString(), salt)) { String msg = messages.getMessage( "system.security.dbExpired", "验证错误,请检查您输入的用户名密码是您在本系统中设定的用户名以及密码!"); smi.setMessage(msg); UserContext.setLoginMessage("loginerror", smi); throw new BadCredentialsException(msg, userDetails); } } else { String msg = messages.getMessage( "system.security.ldapExpired", "Ldap验证错误,请检查您输入的用户名密码是您的Notes用户名以及密码!"); smi.setMessage(msg); UserContext.setLoginMessage("loginerror", smi); throw new BadCredentialsException(msg, userDetails); } } } catch (Exception e) { String msg = messages.getMessage("system.security.unknowExpired", "登陆验证发生错误,请联系管理员!"); smi.setMessage(msg); UserContext.setLoginMessage("loginerror", smi); throw new BadCredentialsException(msg, userDetails); } } } // add by zhangpengf for sso in 2009-12-15 end }
public String create() { LOGGER.info("Inside create"); try { Role employeeRole = new Role(); employeeRole.setName(RoleNames.ROLE_EMPLOYEE.name()); List<Role> roles = this.roleService.findByExample(employeeRole); Set<Role> userRoles = new HashSet<Role>(); userRoles.addAll(roles); user.setRoles(userRoles); // user.setAge(ageCalculator(user)); user.setPassword(encrypt(user.getPassword())); System.out.println("dobCheckbox" + dobCheckbox); // if(dobCheckbox.equals("true")){ // user.setCheckDOBYR(true); // }else{ // user.setCheckDOBYR(false); // } this.userManagement.registerUser(user); user = employerAccountService.findByUserName(user, user.getEmail()); try { String msg = "Your Account has been created"; msgingService.sendEmail( "*****@*****.**", new String[] {user.getEmail()}, "Registration to MyOwnBriefcase", msg); } catch (MessagingException e) { e.printStackTrace(); } if (this.upload != null && upload.length() > 0) { this.userManagement.updateUserPicture(user, this.upload.getAbsolutePath(), uploadFileName); } // log newUser in automatically UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken( user, "user.getPassword()", new GrantedAuthority[] {new GrantedAuthorityImpl(RoleNames.ROLE_EMPLOYEE.name())}); System.out.println("Setting auth details"); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(auth); System.out.println("auth" + auth.getClass()); getSession().put("ACEGI_SECURITY_CONTEXT", context); /* * SwitchUserProcessingFilter filter = new * SwitchUserProcessingFilter(); filter.setUserDetailsService(new * MockAuthenticationDaoUserJackLord()); */ System.out.println("Done"); } catch (Exception e) { e.printStackTrace(); return "error"; } return Action.SUCCESS; }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("Can only process HttpServletRequest"); } if (!(response instanceof HttpServletResponse)) { throw new ServletException("Can only process HttpServletResponse"); } HttpServletRequest httpRequest = (HttpServletRequest) request; String header = httpRequest.getHeader("Authorization"); if (logger.isDebugEnabled()) { logger.debug("Authorization header received from user agent: " + header); } if ((header != null) && header.startsWith("Digest ")) { String section212response = header.substring(7); String[] headerEntries = StringSplitUtils.splitIgnoringQuotes(section212response, ','); Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); String username = (String) headerMap.get("username"); String realm = (String) headerMap.get("realm"); String nonce = (String) headerMap.get("nonce"); String uri = (String) headerMap.get("uri"); String responseDigest = (String) headerMap.get("response"); String qop = (String) headerMap.get("qop"); // RFC 2617 extension String nc = (String) headerMap.get("nc"); // RFC 2617 extension String cnonce = (String) headerMap.get("cnonce"); // RFC 2617 extension // Check all required parameters were supplied (ie RFC 2069) if ((username == null) || (realm == null) || (nonce == null) || (uri == null) || (response == null)) { if (logger.isDebugEnabled()) { logger.debug( "extracted username: '******'; realm: '" + username + "'; nonce: '" + username + "'; uri: '" + username + "'; response: '" + username + "'"); } fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.missingMandatory", new Object[] {section212response}, "Missing mandatory digest value; received header {0}"))); return; } // Check all required parameters for an "auth" qop were supplied (ie RFC 2617) if ("auth".equals(qop)) { if ((nc == null) || (cnonce == null)) { if (logger.isDebugEnabled()) { logger.debug("extracted nc: '" + nc + "'; cnonce: '" + cnonce + "'"); } fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.missingAuth", new Object[] {section212response}, "Missing mandatory digest value; received header {0}"))); return; } } // Check realm name equals what we expected if (!this.getAuthenticationEntryPoint().getRealmName().equals(realm)) { fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.incorrectRealm", new Object[] {realm, this.getAuthenticationEntryPoint().getRealmName()}, "Response realm name '{0}' does not match system realm name of '{1}'"))); return; } // Check nonce was a Base64 encoded (as sent by DigestProcessingFilterEntryPoint) if (!Base64.isArrayByteBase64(nonce.getBytes())) { fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.nonceEncoding", new Object[] {nonce}, "Nonce is not encoded in Base64; received nonce {0}"))); return; } // Decode nonce from Base64 // format of nonce is: // base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key)) String nonceAsPlainText = new String(Base64.decodeBase64(nonce.getBytes())); String[] nonceTokens = StringUtils.delimitedListToStringArray(nonceAsPlainText, ":"); if (nonceTokens.length != 2) { fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.nonceNotTwoTokens", new Object[] {nonceAsPlainText}, "Nonce should have yielded two tokens but was {0}"))); return; } // Extract expiry time from nonce long nonceExpiryTime; try { nonceExpiryTime = new Long(nonceTokens[0]).longValue(); } catch (NumberFormatException nfe) { fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.nonceNotNumeric", new Object[] {nonceAsPlainText}, "Nonce token should have yielded a numeric first token, but was {0}"))); return; } // Check signature of nonce matches this expiry time String expectedNonceSignature = DigestUtils.md5Hex(nonceExpiryTime + ":" + this.getAuthenticationEntryPoint().getKey()); if (!expectedNonceSignature.equals(nonceTokens[1])) { fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.nonceCompromised", new Object[] {nonceAsPlainText}, "Nonce token compromised {0}"))); 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 loadedFromDao = false; UserDetails user = userCache.getUserFromCache(username); if (user == null) { loadedFromDao = true; try { user = userDetailsService.loadUserByUsername(username); } catch (UsernameNotFoundException notFound) { fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.usernameNotFound", new Object[] {username}, "Username {0} not found"))); return; } if (user == null) { throw new AuthenticationServiceException( "AuthenticationDao returned null, which is an interface contract violation"); } userCache.putUserInCache(user); } // Compute the expected response-digest (will be in hex form) String serverDigestMd5; // Don't catch IllegalArgumentException (already checked validity) serverDigestMd5 = generateDigest( passwordAlreadyEncoded, username, realm, user.getPassword(), ((HttpServletRequest) request).getMethod(), uri, qop, nonce, nc, cnonce); // If digest is incorrect, try refreshing from backend and recomputing if (!serverDigestMd5.equals(responseDigest) && !loadedFromDao) { if (logger.isDebugEnabled()) { logger.debug( "Digest comparison failure; trying to refresh user from DAO in case password had changed"); } try { user = userDetailsService.loadUserByUsername(username); } catch (UsernameNotFoundException notFound) { // Would very rarely happen, as user existed earlier fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.usernameNotFound", new Object[] {username}, "Username {0} not found"))); } userCache.putUserInCache(user); // Don't catch IllegalArgumentException (already checked validity) serverDigestMd5 = generateDigest( passwordAlreadyEncoded, username, realm, user.getPassword(), ((HttpServletRequest) request).getMethod(), uri, qop, nonce, nc, cnonce); } // If digest is still incorrect, definitely reject authentication attempt if (!serverDigestMd5.equals(responseDigest)) { if (logger.isDebugEnabled()) { logger.debug( "Expected response: '" + serverDigestMd5 + "' but received: '" + responseDigest + "'; is AuthenticationDao returning clear text passwords?"); } fail( request, response, new BadCredentialsException( messages.getMessage( "DigestProcessingFilter.incorrectResponse", "Incorrect response"))); return; } // To get this far, the digest must have been valid // Check the nonce has not expired // We do this last so we can direct the user agent its nonce is stale // but the request was otherwise appearing to be valid if (nonceExpiryTime < System.currentTimeMillis()) { fail( request, response, new NonceExpiredException( messages.getMessage( "DigestProcessingFilter.nonceExpired", "Nonce has expired/timed out"))); return; } if (logger.isDebugEnabled()) { logger.debug( "Authentication success for user: '******' with response: '" + responseDigest + "'"); } // START SIPXECS CUSTOM CODE: XX-8253 // commented original code // UsernamePasswordAuthenticationToken authRequest = new // UsernamePasswordAuthenticationToken(user, // user.getPassword()); // creates digest token to be handled by // org.sipfoundry.sipxconfig.security.DaoAuthenticationProvider UsernamePasswordAuthenticationToken authRequest = new DigestUsernamePasswordAuthenticationToken(user, user.getPassword()); // END SIPXECS CUSTOM CODE: XX-8253 authRequest.setDetails( authenticationDetailsSource.buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext().setAuthentication(authRequest); } chain.doFilter(request, response); }