/** * 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { UsernamePassword2Token token = (UsernamePassword2Token) authcToken; String username = token.getUsername(); if (username == null || null == username) { throw new AccountException( "Null usernames are not allowed by this realm."); } User entity = new User(); entity.setEmail(username); entity.setStatus(Constant.STATUS_ENABLED); entity = (User) service.iUserService.select(entity); if (null == entity) { throw new UnknownAccountException("No account found for user [" + username + "]"); } byte[] key = Encode.decodeHex(entity.getRandom()); return new SimpleAuthenticationInfo(new Shiro(entity.getId(), entity.getEmail(), entity.getName()), entity.getPassword(), ByteSource.Util.bytes(key), getName()); }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { if(!(token instanceof UsernamePasswordToken)) { throw new IllegalStateException("Token has to be instance of UsernamePasswordToken class"); } UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token; if (usernamePasswordToken.getUsername() == null) { throw new AccountException("Null usernames are not allowed by this realm."); } AppUser user = service.getAppUser(usernamePasswordToken.getUsername()); if(user == null) { throw new AuthenticationException("Could not find user"); } if(getCredentialsMatcher().doCredentialsMatch(usernamePasswordToken, user.getAsAuthenticationInfo())) { return user.getAsAuthenticationInfo(); } throw new AuthenticationException("Failed to authenticate!"); }
@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."); } User user = userService.findActiveUser(username); if(user == null) user = userService.findActiveUserByEmail(username); if(user == null || !user.isEnabled() || !user.getRealm().equals(AGATE_REALM)) throw new UnknownAccountException("No account found for user [" + username + "]"); username = user.getName(); UserCredentials userCredentials = userService.findUserCredentials(username); if(userCredentials == null) throw new UnknownAccountException("No account found for user [" + username + "]"); SimpleAuthenticationInfo authInfo = new SimpleAuthenticationInfo(username, userCredentials.getPassword(), getName()); authInfo.setCredentialsSalt(new SimpleByteSource(salt)); return authInfo; }
/** * 用户登录的身份验证方法 * */ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String username = usernamePasswordToken.getUsername(); if (username == null) { throw new AccountException("用户名不能为空"); } User user = accountManager.getUserByUsername(username); if (user == null) { throw new UnknownAccountException("用户不存在"); } if (user.getState().equals(State.Disable.getValue())) { throw new DisabledAccountException("你的账户已被禁用,请联系管理员开通."); } SessionVariable model = new SessionVariable(user); return new SimpleAuthenticationInfo(model,user.getPassword(),getName()); }
@Override public Response toResponse(ShiroException exception) { Status status = Status.FORBIDDEN; // Invalid api key if (exception instanceof AccountException) { // API key missing status = Status.BAD_REQUEST; logger.warn(exception.getMessage()); } else if (exception instanceof AuthorizationException) { // Not enough permissions status = Status.UNAUTHORIZED; logger.warn(exception.getMessage()); } else { logger.error(exception.getMessage(), exception); } return Response.status(status).type(MediaType.APPLICATION_JSON) .entity(ErrorEntity.with().message(exception.getMessage()).build()).build(); }
/** * 认证回调函数, 登录时调用 */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { System.out.println("------!"); UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String username = usernamePasswordToken.getUsername(); if (username == null) { throw new AccountException("用户名不能为空"); } User user = null;//userService.getByUserName(username); if (user == null) { throw new UnknownAccountException("用户不存在"); } return new SimpleAuthenticationInfo(user,user.getPassword(),getName()); }
/** * 认证信息,主要针对用户登录, */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { ShiroToken token = (ShiroToken) authcToken; User user = null; try { user = userService.login(token.getUsername(), token.getPswd()); } catch (Exception e) { throw new AccountException(e); } return new SimpleAuthenticationInfo(user, token.getPswd(), getName()); }
@SuppressWarnings("unused") @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException { ShiroToken token = (ShiroToken) arg0; String username = token.getUsername(); // 根据username从数据库查找用户,得到密码 // 假设找到的用户如下 // User user = userService.findByUsername(username) User user = new User(); user.setName(username); user.setPassword("21232f297a57a5a743894a0e4a801fc3"); // 数据库中的密码md5加密的 if (null == user) { throw new AccountException("username is not exist"); } else if (!user.getPassword().equals(token.getPswd())) { throw new AccountException("password is not right"); } else { // 登陆成功 logger.info("{} login success.", username); } return new SimpleAuthenticationInfo(arg0, user.getPassword(), username); }
@Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { if (WebHelper.isAjax((HttpServletRequest) request)) { Result result = Result.failure(); if (e instanceof IncorrectCredentialsException) { result.message("密码错误"); } else if (e instanceof ExpiredCredentialsException) { result.message("密码已过期"); } else if (e instanceof UnknownAccountException) { result.message("该账号不存在"); } else if (e instanceof DisabledAccountException) { result.message("该账号已禁用"); } else if (e instanceof LockedAccountException) { result.message("该账号已锁定"); } else if (e instanceof AccountException) { result.message("账号错误"); } else if (e instanceof CredentialsException) { result.message("密码错误"); } try { writeObject(request, response, result); } catch (IOException ex) { throw new RuntimeException(ex); } return false; } return super.onLoginFailure(token, e, request, response); }
@Override protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) { UsernamePasswordToken upToken = (UsernamePasswordToken) token; CUser user; try { user = configuration.readUser(upToken.getUsername()); } catch (UserNotFoundException e) { throw new AccountException("User '" + upToken.getUsername() + "' cannot be retrieved.", e); } if (user.getPassword() == null) { throw new AccountException("User '" + upToken.getUsername() + "' has no password, cannot authenticate."); } if (CUser.STATUS_ACTIVE.equals(user.getStatus())) { // Check for legacy user that has unsalted password hash // Update if unsalted password hash and valid credentials were specified if (hasLegacyPassword(user) && isValidCredentials(upToken, user)) { reHashPassword(user, new String(upToken.getPassword())); } return createAuthenticationInfo(user); } else if (CUser.STATUS_DISABLED.equals(user.getStatus())) { throw new DisabledAccountException("User '" + upToken.getUsername() + "' is disabled."); } else { throw new AccountException( "User '" + upToken.getUsername() + "' is in illegal status '" + user.getStatus() + "'."); } }
@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 at) throws AuthenticationException { log.debug("getting authc info for {}", at); ClothoAccount account = store.getAccount(((UsernamePasswordToken) at).getUsername()); if (!account.isAuthenticatable()) throw new AccountException("Cannot authenticate as " + at.getPrincipal().toString()); return account; }
/** * Method description * * * @param token * * @param authToken * * @return * * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authToken) throws AuthenticationException { if (!(authToken instanceof PublicKeyToken)) { throw new UnsupportedTokenException("PublicKeyToken is required"); } PublicKeyToken token = (PublicKeyToken) authToken; AuthenticationInfo info = null; AuthenticationResult result = authenticator.authenticate( token.getUsername(), token.getPublicKey()); if ((result != null) && (AuthenticationState.SUCCESS == result.getState())) { info = createAuthenticationInfo(token, result); } else if ((result != null) && (AuthenticationState.NOT_FOUND == result.getState())) { throw new UnknownAccountException("unknown account ".concat(token .getUsername())); } else { throw new AccountException("authentication failed"); } return info; }
/** * Method description * * * @param token * * @param authToken * * @return * * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authToken) throws AuthenticationException { if (!(authToken instanceof UsernamePasswordToken)) { throw new UnsupportedTokenException( "ScmAuthenticationToken is required"); } UsernamePasswordToken token = (UsernamePasswordToken) authToken; AuthenticationInfo info = null; AuthenticationResult result = authenticator.authenticate(null, null, token.getUsername(), new String(token.getPassword())); if ((result != null) && (AuthenticationState.SUCCESS == result.getState())) { info = createAuthenticationInfo(token, result); } else if ((result != null) && (AuthenticationState.NOT_FOUND == result.getState())) { throw new UnknownAccountException("unknown account ".concat(token .getUsername())); } else { throw new AccountException("authentication failed"); } return info; }
/** * 根据认证方式(如表单)获取用户名称、密码 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); if (username == null) { log.warn("用户名不能为空"); throw new AccountException("用户名不能为空"); } User user = null; try { user = userManager.findUserByName(username); } catch(Exception ex) { log.warn("获取用户失败\n" + ex.getMessage()); } if (user == null) { log.warn("用户不存在"); throw new UnknownAccountException("用户不存在"); } if(user.getEnabled() == null || "2".equals(user.getEnabled())) { log.warn("用户被禁止使用"); throw new UnknownAccountException("用户被禁止使用"); } log.info("用户【" + username + "】登录成功"); byte[] salt = EncodeUtils.hexDecode(user.getSalt()); ShiroPrincipal subject = new ShiroPrincipal(user); return new SimpleAuthenticationInfo(subject, user.getPassword(), ByteSource.Util.bytes(salt), getName()); }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) { if (authenticationToken instanceof UsernamePasswordToken) { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken; String username = usernamePasswordToken.getUsername(); char[] password = usernamePasswordToken.getPassword(); if (username == null || username.isEmpty()) { throw new AccountException("Null and empty usernames are not allowed by this realm!"); } if (password == null || password.length == 0) { throw new AccountException("Null and empty passwords are not allowed by this realm!"); } // Lookup user Identity identity = identityService().findActivatedIdentityByUsername(username); if (identity == null) { throw new UnknownAccountException("Could not authenticate with given credentials"); } // Create Auth Info return new SimpleAuthenticationInfo( identity.userId().identifier(), identity.encryptedPassword(), ByteSource.Util.bytes("salt"), // (not sure if this salt is used at all?) getName() ); } else { return null; } }
/** * 重写父类方法,在shiro执行登录时先对比验证码,正确后在登录,否则直接登录失败 */ @Override protected boolean executeLogin(ServletRequest request,ServletResponse response) throws Exception { Session session = getSubject(request, response).getSession(); //获取登录次数 Integer number = (Integer) session.getAttribute(getLoginNumKeyAttribute()); //首次登录,将该数量记录在session中 if (number == null) { number = new Integer(1); session.setAttribute(getLoginNumKeyAttribute(), number); } //如果登录次数大于allowLoginNum,需要判断验证码是否一致 if (number > getAllowLoginNum()) { //获取当前验证码 String currentCaptcha = (String) session.getAttribute(getSessionCaptchaKeyAttribute()); //获取用户输入的验证码 String submitCaptcha = getCaptcha(request); //如果验证码不匹配,登录失败 if (StringUtils.isEmpty(submitCaptcha) || !StringUtils.equals(currentCaptcha,submitCaptcha.toLowerCase())) { return onLoginFailure(this.createToken(request, response), new AccountException("验证码不正确"), request, response); } } return super.executeLogin(request, response); }
private String extractMail(final AuthenticationToken token) { LOG.info("Checking doGetAuthenticationInfo"); checkArgument(token instanceof UsernamePasswordToken, "Expected a usernamePassword token"); final UsernamePasswordToken usernamePassword = (UsernamePasswordToken) token; final String email = usernamePassword.getUsername(); if (email == null) { throw new AccountException("Null usernames are not allowed by this realm."); } return email; }
/** * {@inheritDoc} */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); log.debug("Get authentication info for username: {}", username); // Null username is invalid if (username == null) { throw new AccountException("Null usernames are not allowed."); } // get account from repository AccountEntity account = getAccountByUsername(username); // check if user's account is expired assertCredentialsNotExpired(account); // create authentication info SimpleAuthenticationInfo info = createAuthenticationInfo(account); log.debug("Authentication info resolved: username={}", username); return info; }
/** * 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { SystemLoginToken token = (SystemLoginToken) authcToken; if (token.getUsername() == null) { throw new AccountException("提交表单未包含用户名."); } // 增加判断验证码逻辑 String captcha = token.getCaptcha(); String exitCode = (String) SecurityUtils .getSubject() .getSession() .getAttribute( com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if (null == captcha || !captcha.equalsIgnoreCase(exitCode)) { throw new ValidateCodeException("验证码错误"); } UserLoginDto user = userservice.login(token.getUsername()); if (user == null) { return null; } log.info("[用户登录]-[获取登录用户信息]-返回数据结果:" + ToStringBuilder.reflectionToString(user)); if (user != null && UserConstant.SUCCESS == user.getResult()) { // 用户没有被验证 if (!user.isvStatus()) { log.info("用户没有通过邮箱验证."); throw new UnValidationAccountException(); } if(user.isDisable()&&UserDisableReason.登录超过限制.equals(user.getDisableReason())){ throw new LockedAccountException(); } // 用户被锁定 if (user.isDisable()) { log.info("用户被禁止登录."); throw new DisabledAccountException(); } byte[] salt = Encodes.decodeHex(user.getSalt()); return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getName(), user.getRole()), user.getPassword(), ByteSource.Util.bytes(salt), getName()); } throw new UnknownAccountException(); }
/** * 认证回调函数,登录时调用. */ protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { if (null == authcToken) { throw new AccountException("登录出错!"); } UsernamePasswordCaptchaToken token = (UsernamePasswordCaptchaToken) authcToken; String name = token.getUsername(); if (StringUtils.isEmpty(name)) { throw new AccountException("用户名为空!"); } char[] password = token.getPassword(); if (password == null || password.length == 0) { throw new AccountException("密码为空!"); } // 增加判断验证码逻辑 String captcha = token.getCaptcha(); boolean useCaptcha = token.isUseCaptcha(); if (useCaptcha) { String exitCode = (String) SecurityUtils.getSubject().getSession() .getAttribute(ValidateCodeServlet.VALIDATE_CODE); if (StringUtils.isEmpty(exitCode)) { throw new CaptchaInvalidException("图形验证码已经失效,请重新刷新页面!"); } if (StringUtils.isEmpty(captcha) || !captcha.equalsIgnoreCase(exitCode)) { throw new CaptchaException("图形验证码错误!"); } } Parameter map = Parameter.newParameter(); if (EmailValidator.getInstance().isValid(name)) { map.put("email", name); } else if (StringFormatter.isLegalPhone(name)) { map.put("phone", name); } else { map.put("nick", name); } final User user = userService.queryUser(map); if (null == user) { throw new UnknownAccountException("您还没有注册,请注册使用!"); } // 审核通过 if (user.getVerifyStatus() == VerifyStatusEnum.NORMAL.getValue()) { IdentityInfo identityInfo = userService.getIdentityInfo(user .getId()); if (identityInfo != null) { user.setIdentity(true); user.setRealName(identityInfo.getRealName()); } } return new SimpleAuthenticationInfo(new ShiroUser(user, password, captcha), user.getPassword(), ByteSource.Util.bytes(UserConstants.SALT), getName()); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { String method = requestContext.getMethod(); String path = uriInfo.getPath(); String query = uriInfo.getRequestUri().getQuery(); logger.debug("New access to resource {}", path); if (path.startsWith("auth") || path.contains("api-docs")) { // Ignore the AuthenticationResource return; } Subject subject = SecurityUtils.getSubject(); String dateUTC = requestContext.getHeaderString(HttpHeaders.DATE); String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); if (authorizationHeader == null) { throw new AccountException("Hmac-SHA1 Authorization token is required"); } String[] values = authorizationHeader.split(" "); String apiKeyAndSignature[] = StringUtils.split(values[1], ":"); StringBuilder signedContent = new StringBuilder().append(method).append(" /").append(path); if (query != null) { signedContent.append("?").append(query); } if (dateUTC != null) { signedContent.append("\n").append(dateUTC); } /*- if ("POST".equals(method)) { DelegatingInputStream input = message.getContent(DelegatingInputStream.class); if (input != null) { input.cacheInput(); try { signedContent.append("\n").append(IOUtils.toString(input)); } catch (IOException e) { throw new IllegalStateException("Errors when reading POST content", e); } } }*/ String apiKey = apiKeyAndSignature[0]; String signature = apiKeyAndSignature[1]; AuthenticationToken token = new HmacAuthToken.Builder().apiKey(apiKey).message(signedContent.toString()) .signature(signature).dateUTC(dateUTC).build(); subject.login(token); // }