@ValidateParams({ @ValidateParam(value = "user.name", minLen = 4, maxLen = 12), @ValidateParam(value = "user.password", minLen = 6, maxLen = 20), @ValidateParam(value = "captcha", defaultValue = "@@@@", maxLen = 4, minLen = 4), @ValidateParam(value = "rememberMe", type = Boolean.class) }) @RequestMethod(Method.POST) public void signin() { User user = getModel(User.class, "user"); Sys_Common_Variable captcha = ComVarService.service.getComVarByName(Key.CAPTCHA); if (captcha != null && captcha.getToBoolean(Sys_Common_Variable.S_VALUE) && !validateCaptcha(getPara("captcha"))) { renderJson(new Message(captcha.getStr(Sys_Common_Variable.S_ERROR))); return; } Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(user.getStr(User.S_NAME), user.getStr(User.S_PASSWORD)); token.setRememberMe(getParaToBoolean("rememberMe")); subject.login(token); if (subject.isAuthenticated()) { subject.getSession().setAttribute(Lc4eCaptchaRender.captcha_code, Const.DEFAULT_NONE); } else { renderJson(new Message("Login failed")); } } renderJson(new Message(true, "Login Success")); }
/** * 验证当前登录的Subject * * @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { // 获取基于用户名和密码的令牌 // 实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的 // 两个token的引用都是一样的 UsernamePasswordToken token = (UsernamePasswordToken) authcToken; System.out.println( "验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); User user = userService.getByUsername(token.getUsername()); if (user == null) { throw new UnknownAccountException(); // 没找到帐号 } if (UserUtil.STATUS_LOCK == user.getStatus()) { throw new LockedAccountException(); // 帐号锁定 } // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配 AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( user.getAccount(), // 用户名 user.getPassword(), // 密码 ByteSource.Util.bytes(user.getCredentialsSalt()), // salt=username+salt getName() // realm name ); // AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getAccount(), // user.getPassword().toCharArray(), getName()); this.setSession(WebConstant.SESSION_CURRRENT_USER, user); return authenticationInfo; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { if (!(authenticationToken instanceof UsernamePasswordToken)) { throw new UnsupportedTokenException( "Token of type " + authenticationToken.getClass().getName() + " is not supported. A " + UsernamePasswordToken.class.getName() + " is required."); } UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String password = new String(token.getPassword()); try { crowdClientHolder.getAuthenticationManager().authenticate(token.getUsername(), password); return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName()); } catch (RemoteException e) { throw new AuthenticationException(DEFAULT_MESSAGE, e); } catch (com.atlassian.crowd.exception.InactiveAccountException e) { throw new AuthenticationException(DEFAULT_MESSAGE, e); } catch (com.atlassian.crowd.exception.ExpiredCredentialException e) { throw new AuthenticationException(DEFAULT_MESSAGE, e); } catch (com.atlassian.crowd.exception.InvalidAuthenticationException e) { throw new AuthenticationException(DEFAULT_MESSAGE, e); } catch (com.atlassian.crowd.exception.InvalidAuthorizationTokenException e) { throw new AuthenticationException(DEFAULT_MESSAGE, e); } catch (com.atlassian.crowd.exception.ApplicationAccessDeniedException e) { throw new AuthenticationException(DEFAULT_MESSAGE, e); } }
/** 认证回调函数, 登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { logger.info("authentication: 认证回调函数"); UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; return new SimpleAuthenticationInfo(usernamePasswordToken.getUsername(), "world", getName()); }
@RequestMapping("/login") public ModelAndView login( HttpServletRequest request, HttpServletResponse response, @RequestParam String userName, @RequestParam String password, Boolean isRemeberMe) throws Exception { UsernamePasswordToken token = new UsernamePasswordToken(userName, password); Subject subject = SecurityUtils.getSubject(); subject.login(token); if (null != isRemeberMe && isRemeberMe) token.setRememberMe(true); if (subject.isAuthenticated()) { AuthenticationInfo info = new SimpleAuthenticationInfo(userName, password, userName); Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = new User(); user.setUserName(userName); user.setPassword(password); Env env = new Env(); env.setUser(user); session.setAttribute("env", env); GlobalConfigHolder.setEnv(env); ModelAndView view = createLayoutView("admin/index", request, response); return view; } else return createSingleView("login/login", request, response); }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { if (accountDAO == null) { accountDAO = new AccountDAO(); } UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); if (username == null) { throw new AccountException("Null usernames are not allowed by this realm."); } byte[] password = null; try { password = accountDAO.getPasswordForUser(username); if (password == null) { throw new UnknownAccountException("No account found for user [" + username + "]"); } } catch (SQLException e) { throw new AuthenticationException( "An error occured while authenticating user [" + username + "]", e); } return new SimpleAuthenticationInfo(username, password, getName()); }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { /** WHEN USER LOGS IN !!! */ logger.info("doGetAuthorizationInfo(token)..."); UsernamePasswordToken upToken = (UsernamePasswordToken) token; String login = upToken.getUsername(); logger.info("doGetAuthorizationInfo(token) : login = "******"doGetAuthorizationInfo(token) : password = "******"OK")) { // Authentication OK User user = new User(UserType.TELOSYS_USER, login); // Constructor that takes in a single 'primary' principal of the account and // its corresponding credentials, associated with the specified realm. // // This is a convenience constructor and will construct a PrincipalCollection // based on the principal and realmName argument. // Parameters:principal the 'primary' principal associated with the specified // realm.credentials // the credentials that verify the given principal.realmName the realm from where the // principal and credentials were acquired. return new SimpleAuthenticationInfo(user, password, REALM_NAME); } else { // Authentication INVALID throw new AuthenticationException("Invalid user/password"); } }
@Override @Transactional public User createUser(User user) throws UserExistsException, DatabaseException { if (userRepository.findByEmailAddress(user.getEmailAddress()) != null) { throw new UserExistsException(); } if (user.isNew()) { String hash = new Sha512Hash(user.getPassword(), getSalt(), HASH_ITERATIONS).toBase64(); user.setDbPassword(hash); user.setActive(true); } try { userRepository.save(user); } catch (Exception e) { throw new DatabaseException(e); } Subject currentUserSubject = SecurityUtils.getSubject(); if (!currentUserSubject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(user.getEmailAddress(), user.getPassword()); token.setRememberMe(false); try { currentUserSubject.login(token); } catch (AuthenticationException ae) { throw new LoginException(); } } return currentUser = user; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername().trim(); String password = ""; if (upToken.getPassword() != null) { password = new String(upToken.getPassword()); } User user = null; try { user = userService.login(username, password); } catch (UserNotExistsException e) { throw new UnknownAccountException(e.getMessage(), e); } catch (UserPasswordNotMatchException e) { throw new AuthenticationException(e.getMessage(), e); } catch (UserPasswordRetryLimitExceedException e) { throw new ExcessiveAttemptsException(e.getMessage(), e); } catch (UserBlockedException e) { throw new LockedAccountException(e.getMessage(), e); } catch (Exception e) { log.error("login error", e); throw new AuthenticationException(new UserException("user.unknown.error", null)); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), password.toCharArray(), getName()); return info; }
/** * 根据角色id获取角色菜单关系测试方法. * * @throws Exception 普通异常. */ @Test public final void testQueryRoleMenuItemMap() throws Exception { Subject currentUser = ShiroHelper.getSubject(this.request, this.response); UsernamePasswordToken token = new UsernamePasswordToken("user1", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); token.setRememberMe(true); try { currentUser.login(token); UserPo uPo = new UserPo(); uPo.setUserId(Long.valueOf("1")); uPo.setLoginName("user1"); uPo.setPassword("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-01-12 23:30:20"); uPo.setCreateTime(date); uPo.setCreatorId(Long.valueOf("1")); uPo.setIsDelete(false); uPo.setIsLockUp(false); uPo.setVersion(Long.valueOf("0")); currentUser.getSession().setAttribute("user", uPo); } catch (Exception se) { se.printStackTrace(); } request.setParameter("roleMenuItemMap", "{\"roleId\":\"2\"}"); String resultMessage = executeAction("/SuperW/queryRoleMenuItemMap.action"); boolean rs = -1 != resultMessage.indexOf( "{\"userToken\":true,\"serviceResult\":true," + "\"resultInfo\":\"查询角色菜单关系列表成功\""); assertTrue("返回服務信息錯誤失敗", rs); }
/** 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AccountException { Subject currentUser = SecurityUtils.getSubject(); currentUser.getSession(); System.out.println("============" + this.getAuthenticationCacheName()); System.out.println("============" + this.getAuthorizationCacheName()); UsernamePasswordToken token = (UsernamePasswordToken) authcToken; ShiroUser user = null; try { user = shiroUserService.findUserByLoginName(token.getUsername()); } catch (Exception e) { e.printStackTrace(); } if (user != null) { if (!user.isEnabled()) { throw new DisabledAccountException(); } byte[] salt = EncodeUtils.hexDecode(user.getSalt()); return new SimpleAuthenticationInfo( user, user.getPassword(), ByteSource.Util.bytes(salt), getName()); } else { return null; } }
/** * 获取认证信息,会通过realmDao或取用户的id和密码【此2项是必须的】,以及用户状态【非必须,当获取为NULL时不会中断认证】 * * @param authcToken * @return * @throws AuthenticationException */ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; Map<String, Object> info = realmService.getUserUniqueIdentityAndPassword(token.getUsername()); boolean flag = info == null || info.isEmpty() || info.get(identity_in_map_key) == null || info.get(password_in_map_key) == null; if (!flag) { Object status = info.get(user_status_in_map_key); if (status != null) { String userStatus = status.toString(); if (user_status_forbidden.equals(userStatus)) { // 禁用账号 throw new AccountForbiddenException("AccountForbiddenException"); } if (user_status_locked.equals(userStatus)) { // 账号锁定 throw new AccountLockedException("AccountLockedException"); } } return new SimpleAuthenticationInfo( info.get(identity_in_map_key), info.get(password_in_map_key), getName()); } else { throw new UnknownAccountException("UnknownAccountException"); // 没找到帐号; } }
/** 用户登陆 */ @RequestMapping( path = "/login", produces = {"application/json;charset=UTF-8"}) public JsonResult login(String loginName, String password, Boolean rememberMe) { JsonResult result = new JsonResult(); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(loginName, password); if (rememberMe != null && rememberMe) { token.setRememberMe(true); } try { subject.login(token); } catch (AuthenticationException e) { subject.logout(); log.info("登录失败"); result.setResult(false); return result; } if (subject.isAuthenticated()) { result.setResult(true); } else { result.setResult(false); } return result; }
private boolean authenticateViaUrl(final UsernamePasswordToken usernamePasswordToken) { final HttpClient client = getHttpClient(null); try { final String url = kenaiRealmConfiguration.getConfiguration().getBaseUrl() + "api/login/authenticate.json"; final List<NameValuePair> nameValuePairs = Lists.newArrayListWithCapacity(2); nameValuePairs.add(new BasicNameValuePair("username", usernamePasswordToken.getUsername())); nameValuePairs.add( new BasicNameValuePair("password", new String(usernamePasswordToken.getPassword()))); final HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8)); final HttpResponse response = client.execute(post); try { logger.debug( "Kenai Realm user \"{}\" validated against URL={} as {}", usernamePasswordToken.getUsername(), url, response.getStatusLine()); final boolean success = response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 299; return success; } finally { HttpClientUtils.closeQuietly(response); } } catch (IOException e) { logger.info("Kenai Realm was unable to perform authentication", e); return false; } }
/** * 认证缓存key,登录时调用,默认使用token值,使用缓存时才调用此方法 {@link * org.apache.shiro.realm.AuthenticatingRealm#getAuthenticationCacheKey(org.apache.shiro.authc.AuthenticationToken)} * * @param token token * @return key */ protected Object getAuthenticationCacheKey(AuthenticationToken token) { UsernamePasswordToken simpleToken = (UsernamePasswordToken) token; Object id = realmService.getUniqueIdentity(simpleToken.getUsername().toLowerCase()); if (id != null) { return "DRC_" + id; } return null; }
@RequestMapping(value = "/auth", method = POST) public void authenticate(@RequestBody final UsernamePasswordToken credentials) { log.info( "Authenticating {} with password {}", credentials.getUsername(), credentials.getPassword()); final Subject subject = SecurityUtils.getSubject(); subject.login(credentials); // set attribute that will allow session querying subject.getSession().setAttribute("email", credentials.getUsername()); }
/** 登录认证 */ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; CmsUser user = cmsUserMng.findByUsername(token.getUsername()); if (user != null) { UnifiedUser unifiedUser = unifiedUserMng.findById(user.getId()); return new SimpleAuthenticationInfo(user.getUsername(), unifiedUser.getPassword(), getName()); } else { return null; } }
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; Useraccount user = userAccountService.getUserAccount(token.getUsername()); if (user != null) { ByteSource salt = ByteSource.Util.bytes(user.getSalt()); return new SimpleAuthenticationInfo(user, user.getPassword(), salt, getName()); } else { return null; } }
/** * login * * @param userName login userName * @param password login password * @throws InvalidateLoginUserException userName or password invalidate */ public static void login(String userName, String password) throws InvalidateLoginUserException { try { Subject subject = getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(); token.setUsername(userName); token.setPassword(password.toCharArray()); subject.login(token); } catch (Exception e) { throw new InvalidateLoginUserException("userName or password error.", e); } }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authToken; if (StringUtils.isBlank(token.getUsername())) { throw new AccountException("Empty usernames are not allowed by this realm."); } String loginPayload = createLoginPayload(token.getUsername(), token.getPassword()); User user = authenticateUser(loginPayload); LOG.debug("{} successfully login via ZeppelinHub", user.login); return new SimpleAuthenticationInfo(user.login, token.getPassword(), name); }
/** 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; SecurityUser<Long> user = userHessianService.findUserByAccount(token.getUsername(), UserStaEnum.ENABLE); if (user != null) { token.setUsername(user.getLoginName()); return new SimpleAuthenticationInfo(user, user.getPassWord(), getName()); } else { return null; } }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; User user = userDAO.getUserByUsername(upToken.getUsername()); if (user == null) { throw new AuthenticationException("Login name [" + upToken.getUsername() + "] not found!"); } return new SimpleAuthenticationInfo(user, user.getPassword(), getName()); }
@Override protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) throws AuthenticationException { final UsernamePasswordToken upToken = (UsernamePasswordToken) token; // if the user can authenticate we are good to go if (authenticateViaUrl(upToken)) { return buildAuthenticationInfo(upToken); } else { throw new AccountException( "User \"" + upToken.getUsername() + "\" cannot be authenticated via Kenai Realm."); } }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // only allow jcool/jcool UsernamePasswordToken userpass = (UsernamePasswordToken) token; if ("jcool".equals(userpass.getUsername()) && "jcool".equals(new String(userpass.getPassword()))) { return new SimpleAuthenticationInfo( userpass.getUsername(), new String(userpass.getPassword()), this.getName()); } return null; }
public void login(String username, String password) { UsernamePasswordToken token; token = new UsernamePasswordToken(username, password); // ”Remember Me” built-in, just do this: token.setRememberMe(true); // With most of Shiro, you'll always want to make sure you're working with the currently // executing user, // referred to as the subject Subject currentUser = SecurityUtils.getSubject(); // Authenticate currentUser.login(token); }
/** 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; User user = accountService.findUserByLoginName(token.getUsername()); if (user != null) { byte[] salt = Encodes.decodeHex(user.getSalt()); return new SimpleAuthenticationInfo( new ShiroUser(user.getId(), user.getLoginName(), user.getName()), user.getPassword(), ByteSource.Util.bytes(salt), getName()); } else { return null; } }
private HttpClient getHttpClient(final UsernamePasswordToken usernamePasswordToken) { // risky, but we must blindly assume it is final DefaultHttpClient client = (DefaultHttpClient) hc4Provider.createHttpClient(); if (usernamePasswordToken != null) { final List<String> authorisationPreference = new ArrayList<String>(2); authorisationPreference.add(AuthPolicy.DIGEST); authorisationPreference.add(AuthPolicy.BASIC); final Credentials credentials = new UsernamePasswordCredentials( usernamePasswordToken.getUsername(), String.valueOf(usernamePasswordToken.getPassword())); client.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authorisationPreference); } return client; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; User user = userService.findByUserName(token.getUsername()); Session session = SecurityUtils.getSubject().getSession(); if (user == null) { throw new AuthorizationException("用户不存在"); } SimpleAuthenticationInfo info = null; if (user.getUsername().equals(token.getUsername())) { info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName()); session.setAttribute("user", user); } return info; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); // Null username is invalid. // if (username == null) { throw new AccountException("Null usernames are not allowed by this realm."); } // Lookup user. // UtenteService us = ServiceFactory.createUtenteService(); Utente utente = us.retrieveByUsername(username); if (utente == null) throw new UnknownAccountException("No account found for user [" + username + "]"); // Extract digested password informations. // String digest = utente.getDigest(); String salt = utente.getSalt(); Integer iterations = utente.getIterations(); // Create authentication info. // String realm = getName(); SaltedWithIterationAuthenticationInfo info = new SaltedWithIterationAuthenticationInfo(username, digest, realm); // Set up digest info. // info.setIterations(iterations); info.setSalt(salt); // Set up user details as a secondary principal. // info.addPrincipal(utente, realm); // Always clean up cached authorization after a login. // clearCachedAuthorizationInfo(info.getPrincipals()); return info; }
/* * 用户验证。 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken) */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { logger.debug(String.format("token:[%s]", token.getClass())); UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String username = usernamePasswordToken.getUsername(), pwd = new SimpleHash( "md5", new String(usernamePasswordToken.getPassword()), ByteSource.Util.bytes(username), 2) .toHex(); // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配。 return new SimpleAuthenticationInfo( username, pwd, ByteSource.Util.bytes(username), this.getName()); }