Java 类org.apache.shiro.authc.AuthenticationInfo 实例源码

项目:spring-boot-shiro    文件:RetryLimitHashedCredentialsMatcher.java   
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws ExcessiveAttemptsException {
    String username = (String)token.getPrincipal();
    AtomicInteger retryCount = passwordRetryCache.get(username);

    if(retryCount == null) {
        retryCount = new AtomicInteger(0);
        passwordRetryCache.put(username, retryCount);
    }
    if(retryCount.incrementAndGet() > retryMax) {
        throw new ExcessiveAttemptsException("您已连续错误达" + retryMax + "次!请10分钟后再试");
    }

    boolean matches = super.doCredentialsMatch(token, info);
    if(matches) {
        passwordRetryCache.remove(username);
    }else {
        throw new IncorrectCredentialsException("密码错误,已错误" + retryCount.get() + "次,最多错误" + retryMax + "次");
    }
    return true;
}
项目:rabbitframework    文件:DefaultLdapRealm.java   
/**
 * This implementation opens an LDAP connection using the token's
 * {@link #getLdapPrincipal(org.apache.shiro.authc.AuthenticationToken) discovered principal} and provided
 * {@link AuthenticationToken#getCredentials() credentials}.  If the connection opens successfully, the
 * authentication attempt is immediately considered successful and a new
 * {@link AuthenticationInfo} instance is
 * {@link #createAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, Object, Object, javax.naming.ldap.LdapContext) created}
 * and returned.  If the connection cannot be opened, either because LDAP authentication failed or some other
 * JNDI problem, an {@link NamingException} will be thrown.
 *
 * @param token              the submitted authentication token that triggered the authentication attempt.
 * @param ldapContextFactory factory used to retrieve LDAP connections.
 * @return an {@link AuthenticationInfo} instance representing the authenticated user's information.
 * @throws NamingException if any LDAP errors occur.
 */
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
                                                        LdapContextFactory ldapContextFactory)
        throws NamingException {

    Object principal = token.getPrincipal();
    Object credentials = token.getCredentials();

    log.debug("Authenticating user '{}' through LDAP", principal);

    principal = getLdapPrincipal(token);

    LdapContext ctx = null;
    try {
        ctx = ldapContextFactory.getLdapContext(principal, credentials);
        //context was opened successfully, which means their credentials were valid.  Return the AuthenticationInfo:
        return createAuthenticationInfo(token, principal, credentials, ctx);
    } finally {
        LdapUtils.closeContext(ctx);
    }
}
项目:kettle_support_kettle8.0    文件:Authorizing2Realm.java   
/**
 * 认证回调函数,登录时调用.
 */
@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());
}
项目:springboot-shiro-cas-mybatis    文件:ShiroRealm.java   
@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //UsernamePasswordToken对象用来存放提交的登录信息
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;

        log.info("验证当前Subject时获取到token为:" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); 
//        return new SimpleAuthenticationInfo("hsjhsj","8e24137dee97c9bbddb9a0cd6e043be4" , getName());
        return new SimpleAuthenticationInfo("hsjhsj","" , getName());
        //查出是否有此用户
//        TbUser user=null;
//        if(user!=null){
            // 若存在,将此用户存放到登录认证info中,无需自己做密码对比,Shiro会为我们进行密码对比校验
//            return new SimpleAuthenticationInfo(user.getUsername(), , getName());
//        }
//        return null;
    }
项目:eagle-oj-api    文件:Realm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
    String token = (String) auth.getCredentials();
    Cache<String, String> authCache = CacheController.getAuthCache();
    if (! authCache.containsKey(token)) {
        // get user info from database
        int uid = JWTUtil.getUid(token);
        UserEntity userEntity = userService.getUserByUid(uid);
        authCache.put(token, String.valueOf(userEntity.getPassword()));
    }

    String secret = authCache.get(token);
    if (!JWTUtil.decode(token, secret)) {
        throw new AuthenticationException("Token invalid");
    }

    return new SimpleAuthenticationInfo(token, token, "jwt_realm");
}
项目:xproject    文件:AdminUserRealm.java   
/**
 * 用户认证-验证用户是否登录、用户名密码是否匹配
 */
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    logger.info(">>> 【用户认证】token = {}", token);
    String userName = (String)token.getPrincipal();
    AdminUser user = getPrincipalService().getPrincipalObject(userName);
       if(user == null) {
           throw new UnknownAccountException("Unknown account: " + userName);//没找到帐号
       }
       if(AdminUserStatusEnum.ADMIN_USER_STATUS_DISABLED.getStatusCode().equals(user.getStatus())) {
           throw new LockedAccountException("Account[" + userName + "] has been locked!"); //帐号锁定
       }
       //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
       SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
               user.getUserName(), //用户名
               user.getPassword(), //密码
               ByteSource.Util.bytes(user.getPasswordSalt()),//salt
               getName()  //realm name
       );
       return authenticationInfo;
}
项目:xproject    文件:RetryLimitHashedCredentialsMatcher.java   
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    String userName = (String)token.getPrincipal();
    final String key = REDIS_KEY_PREFIX + userName;
    long maxRetry = redisTemplate.opsForValue().increment(key, 1);
    if(maxRetry == 1){ //首次输入密码
        redisTemplate.expire(key, passwordRetryWaitMinutes, TimeUnit.MINUTES);
    }
    if(maxRetry >= passwordRetryLimit){
        throw new ExcessiveAttemptsException(passwordRetryLimit + "");
    }
    boolean matches = super.doCredentialsMatch(token, info);
       if(matches) {
        redisTemplate.delete(key);
       }
       return matches;
}
项目:centraldogma    文件:SearchFirstActiveDirectoryRealm.java   
/**
 * Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for the
 * specified username.
 */
@Override
protected AuthenticationInfo queryForAuthenticationInfo(
        AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {

    final UsernamePasswordToken upToken = ensureUsernamePasswordToken(token);
    final String userDn = findUserDn(ldapContextFactory, upToken.getUsername());

    LdapContext ctx = null;
    try {
        // Binds using the username and password provided by the user.
        ctx = ldapContextFactory.getLdapContext(userDn, upToken.getPassword());
    } finally {
        LdapUtils.closeContext(ctx);
    }
    return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
项目:bibliometrics    文件:BibliometricsRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    // identify account to log to
    UsernamePasswordToken userPassToken = (UsernamePasswordToken) token;
    final String username = userPassToken.getUsername();
    if (username == null) {
        return null;
    }
    // read password hash and salt from db
    final User user = UserDAO.getUser(username);
    if (user == null) {
        return null;
    }
    // return salted credentials
    SaltedAuthenticationInfo info = new SaltedAuthInfo(username, user.getPassword(), user.getSalt());
    return info;
}
项目:xmall    文件:MyRealm.java   
/**
 * 先执行登录验证
 * @param token
 * @return
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    //获取用户名密码
    String username = token.getPrincipal().toString();
    TbUser tbUser = userService.getUserByUsername(username);
    if (tbUser != null){
        //得到用户账号和密码存放到authenticationInfo中用于Controller层的权限判断 第三个参数随意不能为null
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(tbUser.getUsername(),tbUser.getPassword(),
                tbUser.getUsername()) ;
        return authenticationInfo ;
    }else{
        return null ;
    }
}
项目:JAVA-    文件:Realm.java   
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("enable", 1);
    params.put("account", token.getUsername());
    Parameter parameter = new Parameter("sysUserService", "queryList").setMap(params);
    logger.info("{} execute sysUserService.queryList start...", parameter.getNo());
    List<?> list = provider.execute(parameter).getList();
    logger.info("{} execute sysUserService.queryList end.", parameter.getNo());
    if (list.size() == 1) {
        SysUser user = (SysUser) list.get(0);
        StringBuilder sb = new StringBuilder(100);
        for (int i = 0; i < token.getPassword().length; i++) {
            sb.append(token.getPassword()[i]);
        }
        if (user.getPassword().equals(sb.toString())) {
            WebUtil.saveCurrentUser(user.getId());
            saveSession(user.getAccount(), token.getHost());
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(),
                    user.getUserName());
            return authcInfo;
        }
        logger.warn("USER [{}] PASSWORD IS WRONG: {}", token.getUsername(), sb.toString());
        return null;
    } else {
        logger.warn("No user: {}", token.getUsername());
        return null;
    }
}
项目:rure    文件:CustomRealm.java   
@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // token是用户输入的用户名和密码
        // 第一步从token中取出用户名
        String userCode = (String) token.getPrincipal();

        // 如果查询不到返回null
        //数据库中用户账号是zhangsansan
//        if(!userCode.equals("zhangsansan")){//
//            return null;
//        }

        // 模拟从数据库查询到密码
        String password = "111111";

        //将activeUser设置simpleAuthenticationInfo
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                userCode, password, this.getName());

        return simpleAuthenticationInfo;
    }
项目:myblog    文件:MyRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    String username = (String) token.getPrincipal();// 根据刚刚传过来的token获取用户名
    Blogger blogger = bloggerService.findByUsername(username);// 只是根据用户名查询出,不涉及密码
    if (blogger != null) {
        System.out.println("验证信息:" + blogger);
        // 把获取到的用户存到session中
        SecurityUtils.getSubject().getSession().setAttribute("blogger", blogger);
        // 把从数据库中查询出来的博主信息放到AuthenticationInfo中,即把正确的用户名,密码,交给shiro,再和前台输入的校验。
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(blogger.getUsername(),
                blogger.getPassword(), "MyRealm");
        return authenticationInfo;
    } else {
        return null;
    }

}
项目:DWSurvey    文件:ShiroDbRealm.java   
/**
     * 认证回调函数,登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
//      User user = accountManager.findUserByLoginName(token.getUsername());

        //根据loginToken 看能不查到当前token token有效期就1分钟

        String tokenPassword=new String(token.getPassword());

        User user = accountManager.findUserByLoginNameOrEmail(token.getUsername());

        //user.getStandardLock()==1 
        if (user != null &&  user.getStatus().intValue()!=0 && !user.getLoginName().endsWith("@chacuo.net")) {
             return new SimpleAuthenticationInfo(user.getLoginName(), user.getShaPassword() , getName());
        } else {
            return null;
        }
    }
项目:stateless-shiro    文件:BearerTokenAuthenticatingRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
    BearerToken token = (BearerToken)arg0;
    // assert the bearerToken, and if valid, look up the account data and return
       //an AuthenticationInfo instance representing that account.
    String email = (String)token.getPrincipal();
    String credentials = (String)token.getCredentials();

    Preconditions.checkNotNull(email, "Email can't be null");
    Preconditions.checkNotNull(token, "Token can't be null");

    DBAuthenticationToken dbToken = tokenRepository.getAuthenticationToken(credentials) ;
    if (tokenIsInvalid(token, dbToken)) {
        LOGGER.info("Rejecting token " + credentials + " for user " + email);
        return null;
    }

    return new BearerAuthenticationInfo(this, dbToken);
}
项目:cjs_ssms    文件:UUserRealm.java   
/**
 * 登录认证,在权限认证前执行
 *
 * @param token
 * @return AuthenticationInfo
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  String username = token.getPrincipal().toString();
  UUser user = userMService.findUserByUserName(username);
  if (null == user) {
    return null;
  } else {
    /**
     * info中principal选择方案:1.username, 2.User, 3.UserWithRoleAndPermission
     * 各有优劣,这里选择使用username
     *
     * EAO isssue: 新建对象WholeUser,有属性roles,permissions,登录时产生此对象作为principals,则authorization时无需再和sql交互
     * 1.优势: 减少sql交互,
     * 2.劣势:缓存大,对变更的用户信息反馈不及时
     * 适用: 变化不大信息量少,但权限校验频繁的用户类型.
     *
     * SimpleAuthorizationInfo: param: principal检查源码最后被强转为Collection不知何意??
     */
    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), "UserRealm");
    return info;
  }
}
项目:cjs_ssms    文件:UserRealm.java   
/**
 * 登录认证,在权限认证前执行
 *
 * @param token
 * @return AuthenticationInfo
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  String userName = token.getPrincipal().toString();
  UUser user = userFService.findUserByUsername(userName);
  if (null == user) {
    return null;
  } else {
    /**
     * info中principal选择方案:1.username, 2.User, 3.UserWithRoleAndPermission
     * 各有优劣,这里选择使用username
     *
     * EAO isssue: 新建对象WholeUser,有属性roles,permissions,登录时产生此对象作为principals,则authorization时无需再和sql交互
     * 1.优势: 减少sql交互,
     * 2.劣势:缓存大,对变更的用户信息反馈不及时
     * 适用: 变化不大信息量少,但权限校验频繁的用户类型.
     *
     * SimpleAuthorizationInfo: param: principal检查源码最后被强转为Collection不知何意??
     */
    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), "UserRealm");
    return info;
  }
}
项目:rabbitframework    文件:PasswordMatcher.java   
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        PasswordService service = ensurePasswordService();

        Object submittedPassword = getSubmittedPassword(token);
        Object storedCredentials = getStoredPassword(info);
        assertStoredCredentialsType(storedCredentials);

        if (storedCredentials instanceof Hash) {
            Hash hashedPassword = (Hash)storedCredentials;
            HashingPasswordService hashingService = assertHashingPasswordService(service);
            return hashingService.passwordsMatch(submittedPassword, hashedPassword);
        }
        //otherwise they are a String (asserted in the 'assertStoredCredentialsType' method call above):
        String formatted = (String)storedCredentials;
        return passwordService.passwordsMatch(submittedPassword, formatted);
    }
项目:shiro-demo    文件:OnlyOneAuthenticatorStrategy.java   
/**
 * 在每个Realm之后调用
 */
@Override
public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t) throws AuthenticationException {
    AuthenticationInfo authenticationInfo = null;
    if(singleRealmInfo == null){//当前没有通过验证
        authenticationInfo = aggregateInfo;//保存之前所合并的
    }else{//通过验证
        if(aggregateInfo== null){//之前没有合并过
            authenticationInfo = singleRealmInfo;//初始化
        }else{
            authenticationInfo = merge(singleRealmInfo, aggregateInfo);//合并
            if(authenticationInfo.getPrincipals().getRealmNames().size() > 1){
                System.out.println(authenticationInfo.getPrincipals().getRealmNames());
                   throw new AuthenticationException("[" + token.getClass() + "] " +
                           "这个认证令牌无法通过realm的验证,请确认您提供的令牌只允许通过1个realm验证");
            }
        }
    }
    return authenticationInfo;
}
项目:windows-file-change    文件:NutDaoRealm.java   
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
      UsernamePasswordToken upToken = (UsernamePasswordToken) token;

     /* if (Strings.isBlank(upToken.getCaptcha()))
          throw new AuthenticationException("验证码不能为空");
      String _captcha = Strings.sBlank(SecurityUtils.getSubject().getSession(true).getAttribute(Toolkit.captcha_attr));
      if (!upToken.getCaptcha().equalsIgnoreCase(_captcha))
          throw new AuthenticationException("验证码错误");*/

      User user = dao().fetch(User.class, Cnd.where("name", "=", upToken.getUsername()));
      if (user == null)
          return null;
      if (user.isLocked()) 
          throw new LockedAccountException("Account [" + upToken.getUsername() + "] is locked.");
      ByteSource salt = ByteSource.Util.bytes(user.getSalt());
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
info.setCredentialsSalt(salt);
return info;
  }
项目:dms-webapp    文件:MemberRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    String phoneNumber = (String)token.getPrincipal();
       if(StringUtils.trimToNull(phoneNumber) == null){
           throw new IncorrectCredentialsException();//账号或密码错误
       }
    CdMember query = new CdMember();
    query.setPhoneNumber(phoneNumber);
       CdMember member = memberService.findMember(query);
       if(member == null) {
           throw new UnknownAccountException();//没找到帐号
       }
       SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
               phoneNumber, //用户名
               member.getPassword(), //密码
               ByteSource.Util.bytes(AppConstants.PC_PASSWORD_SALT),//salt=phoneNumber
               getName()  //realm name
       );
       return authenticationInfo;
}
项目:dms-webapp    文件:UserRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    String username = (String)token.getPrincipal();

    SysUsers user = userService.findByUsername(username);

    if(user == null) {
        throw new UnknownAccountException();//没找到帐号
    }

    if(Boolean.TRUE.equals(user.getLocked())) {
        throw new LockedAccountException(); //帐号锁定
    }

    //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
            username, //用户名
            user.getPassword(), //密码
            ByteSource.Util.bytes(user.getSalt()),//salt=salt
            getName()  //realm name
    );
    return authenticationInfo;
}
项目:shiro-oltu    文件:OAuthAuthorizeRealm.java   
/**
 * create authentication info, by default, this create
 * SimpleAuthenticationInfo with principals using access token as primary
 * principal and a map contains attributes {@link OAuth#OAUTH_ACCESS_TOKEN}
 * and {@link OAuth#OAUTH_EXPIRES_IN} and {@link OAuth#OAUTH_REFRESH_TOKEN}
 * and {@link OAuthConstants#OAUTH_TOKEN_TIME} and
 * {@link OAuthConstants#OAUTH_SCOPES}, the credentials set to byte array of
 * access token. if sub-class override requestAttributes and returned
 * attributes contains key {@link OAuthConstants#OAUTH_PRINCIPAL}, then the
 * value will be used as primary principal.
 * 
 * @param clientToken
 *          the client token
 * @param oAuthResponse
 *          OAuth access token response
 * @return authentication info
 */
protected AuthenticationInfo buildAuthenticationInfo(OAuthClientToken clientToken,
    OAuthAccessTokenResponse oAuthResponse) {
  String accessToken = oAuthResponse.getAccessToken();
  Date tokenTime = new Date();
  Map<String, Object> attributes = requestAttributes(oAuthResponse);
  if (attributes == null)
    attributes = new HashMap<String, Object>();
  else
    attributes = new HashMap<String, Object>(attributes);
  List<Object> principals = new ArrayList<Object>();
  if (attributes.containsKey(OAuthConstants.OAUTH_PRINCIPAL))
    principals.add(attributes.get(OAuthConstants.OAUTH_PRINCIPAL));
  else
    principals.add(accessToken);
  attributes.put(OAuth.OAUTH_ACCESS_TOKEN, accessToken);
  attributes.put(OAuth.OAUTH_EXPIRES_IN, oAuthResponse.getExpiresIn());
  attributes.put(OAuth.OAUTH_REFRESH_TOKEN, oAuthResponse.getRefreshToken());
  attributes.put(OAuthConstants.OAUTH_TOKEN_TIME, tokenTime);
  attributes.put(OAuthConstants.OAUTH_SCOPES, clientToken.getScopes());
  principals.add(attributes);
  PrincipalCollection collection = new SimplePrincipalCollection(principals, getName());
  return new SimpleAuthenticationInfo(collection, accessToken);
}
项目:dms-webapp    文件:MultiLoginAuthenticator.java   
@Override
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
        throws AuthenticationException {
    assertRealmsConfigured();
    //根据不同类型的token找对应的的Realm
       String realmKey = "";
       if(authenticationToken instanceof MemberUserToken) {
           realmKey = ((MemberUserToken)authenticationToken).getRealmKey();
       } else if(authenticationToken instanceof SysUserToken) {
        realmKey = ((SysUserToken)authenticationToken).getRealmKey();
       }
       if(StringUtils.isEmpty(realmKey)) {
        // 抛异常还是支持multiple Realms
        // return doMultiRealmAuthentication(realms, authenticationToken);
        throw new AuthenticationException("不支持token:" + authenticationToken.getClass().getName());
       } else {
           Realm realm = lookupRealm(realmKey);
           return doSingleRealmAuthentication(realm, authenticationToken);
       }
}
项目:simbest-cores    文件:MutilModularRealmAuthenticator.java   
@Override
protected AuthenticationInfo doMultiRealmAuthentication(
        Collection<Realm> realms, AuthenticationToken token) {
    SSORealm ssoRealm = null;
    SNSRealm snsRealm = null;
    JDBCRealm jdbcRealm = null;

    for (Realm realm : realms) {
        if (realm instanceof SSORealm) {
            ssoRealm = (SSORealm) realm;
        } else if (realm instanceof SNSRealm) {
            snsRealm = (SNSRealm) realm;
        } else {
            jdbcRealm = (JDBCRealm) realm;
        }
    }

       //核心思想,判断token类型,选择realm
    if(token instanceof SNSAuthenticationToken)
        return doSingleRealmAuthentication(snsRealm, token);
    else if(token instanceof SSOAuthenticationToken)
        return doSingleRealmAuthentication(ssoRealm, token);
    else
        return doSingleRealmAuthentication(jdbcRealm, token);
}
项目:simbest-cores    文件:AbstractShrioRealm.java   
protected AuthenticationInfo createPasswordAuthenticationInfo(SysUser u){
    if (u != null) {
        byte[] salt = Encodes.decodeHex(u.getSalt());
        List<Integer> roleIds = Lists.newArrayList();
        for (SysRole role : u.getRoleList()) {
            roleIds.add(role.getId());
        }
        Object principal = new ShiroUser(u.getLoginName(), u.getUsername(),u.getUniqueCode(),
                u.getUserCode(), u.getId(), u.getSysOrg().getId(),
                u.getSysOrg().getOrgName(), roleIds,
                u.getHeadimgurl(), u.getAccesstoken(),
                u.getOpenid(), u.getUnionid(), u.getPhone(), u.getOwnerOrgId());
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(principal,u.getPassword(),ByteSource.Util.bytes(salt), getName());
        return authenticationInfo;
    } else {
        return null;
    }
}
项目:simbest-cores    文件:AbstractShrioRealm.java   
protected AuthenticationInfo createAuthenticationInfo(SysUser u){
    if (u != null) {
        List<Integer> roleIds = Lists.newArrayList();
        for (SysRole role : u.getRoleList()) {
            roleIds.add(role.getId());
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                new ShiroUser(u.getLoginName(), u.getUsername(),u.getUniqueCode(),
                        u.getUserCode(), u.getId(), u.getSysOrg()
                                .getId(), u.getSysOrg().getOrgName(),
                        roleIds, u.getHeadimgurl(), u.getAccesstoken(),
                        u.getOpenid(), u.getUnionid(), u.getPhone(), u.getOwnerOrgId()),
                u.getPassword(), getName());
        return authenticationInfo;
    } else {
        return null;
    }
}
项目:dpCms    文件:DbRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
        final AuthenticationToken token)
        throws AuthenticationException {
    final UsernamePasswordToken credentials = (UsernamePasswordToken) token;
    final String userName = credentials.getUsername();
    if (userName == null) {
        throw new UnknownAccountException("userName not provided");
    }
    Account account = accountRepository.findByLoginName(userName);
    if (account == null) {
        throw new UnknownAccountException("Account does not exist");
    }
    return new SimpleAuthenticationInfo(userName, account.getPassword().toCharArray(),
            ByteSource.Util.bytes(userName), getName());
}
项目:emodb    文件:ApiKeyRealm.java   
/**
 * Gets the AuthenticationInfo that matches a token.  This method is only called if the info is not already
 * cached by the realm, so this method does not need to perform any further caching.
 */
@SuppressWarnings("unchecked")
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
        throws AuthenticationException {
    String id;

    if (AnonymousToken.isAnonymous(token)) {
        // Only continue if an anonymous identity has been set
        if (_anonymousId != null) {
            id = _anonymousId;
        } else {
            return null;
        }
    } else {
        id = ((ApiKeyAuthenticationToken) token).getPrincipal();
    }

    return getUncachedAuthenticationInfoForKey(id);
}
项目:java-platform    文件:DatabaseRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (token instanceof UsernamePasswordToken) {
        String username = ((UsernamePasswordToken) token).getUsername();
        char[] password = ((UsernamePasswordToken) token).getPassword();

        if (Strings.isNullOrEmpty(username) || password == null) {
            return null;
        }

        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UnknownAccountException();
        }

        return new SimpleAuthenticationInfo(new Principal(user.getId(), username), user.getPassword(), new SimpleByteSource(user.getUsername()),
                getName());
    }
    return null;
}
项目:octopus-jsr375    文件:AppAuthentication.java   
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) {

    if (token instanceof UsernamePasswordToken) {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        AuthenticationInfoBuilder authenticationInfoBuilder = new AuthenticationInfoBuilder();
        authenticationInfoBuilder.principalId(principalId++).name(token.getPrincipal().toString());
        authenticationInfoBuilder.password(usernamePasswordToken.getPassword());

        authenticationInfoBuilder.externalPasswordCheck();

        return authenticationInfoBuilder.build();
    }
    return null;
}
项目:shiro-oltu    文件:OAuthAuthorizeRealm.java   
/**
 * authenticate through OAuth token URI
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
    throws AuthenticationException {
  OAuthClientToken clientToken = (OAuthClientToken) token;
  OAuthClient client = new OAuthClient(new CloseableHttpClient4());
  try {
    OAuthClientRequest oAuthRequest = OAuthClientRequest.tokenLocation(tokenURI)
        .setClientId(clientId).setClientSecret(clientSecret)
        .setGrantType(clientToken.getGrantType()).setCode(clientToken.getAuthCode())
        .setRefreshToken(clientToken.getRefreshToken()).setRedirectURI("client")
        .buildBodyMessage();
    return buildAuthenticationInfo(clientToken, client.accessToken(oAuthRequest));
  } catch (OAuthSystemException | OAuthProblemException ex) {
    throw new AuthenticationException(ex.getMessage(), ex);
  } finally {
    client.shutdown();
  }
}
项目:SSM    文件:MyRealm.java   
/**
 * 首先执行这个登录验证
 * @param token
 * @return
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
        throws AuthenticationException {
    //获取用户账号
    String username = token.getPrincipal().toString() ;
    T_user user = t_userService.findUserByUsername(username) ;
    if (user != null){
        //将查询到的用户账号和密码存放到 authenticationInfo用于后面的权限判断。第三个参数随便放一个就行了。
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),
                "a") ;
        return authenticationInfo ;
    }else{
        return  null ;
    }
}
项目:VideoMeeting    文件:ShiroService.java   
@Override
protected void assertCredentialsMatch(AuthenticationToken token,
        AuthenticationInfo info) throws AuthenticationException {
    // 如果验证出错,super会抛出异常
    super.assertCredentialsMatch(token, info);
    // 验证通过,走下面,删除旧的subject,不删好像也没事
    // 删除其他设备上的这个用户的session
    // 人多了效率有点危险
    String username = (String) token.getPrincipal();
    if (token == null || username == null)
        return;
    if (SecurityUtils.getSubject() != null) {
        SecurityUtils.getSubject().logout();
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            if (username.equals(session.getAttribute("username"))) {
                session.stop();
            }
        }
    }
}
项目:VideoMeeting    文件:RetryLimitHashedCredentialsMatcher.java   
@Override
public boolean doCredentialsMatch(AuthenticationToken token,
        AuthenticationInfo info) {
    String username = (String) token.getPrincipal();
    // retry count + 1
    if (passwordRetryCache != null) {
        AtomicInteger retryCount = passwordRetryCache.get(username);
        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        if (retryCount.incrementAndGet() > 5) {
            // if retry count > 5 throw
            throw new ExcessiveAttemptsException();
        }
    }
    boolean matches = super.doCredentialsMatch(token, info);
    if (matches && passwordRetryCache != null) {
        // clear retry count
        passwordRetryCache.remove(username);
    }
    return matches;
}
项目:rabbitframework    文件:DefaultSubjectContext.java   
public boolean resolveAuthenticated() {
    Boolean authc = getTypedValue(AUTHENTICATED, Boolean.class);
    if (authc == null) {
        //see if there is an AuthenticationInfo object.  If so, the very presence of one indicates a successful
        //authentication attempt:
        AuthenticationInfo info = getAuthenticationInfo();
        authc = info != null;
    }
    if (!authc) {
        //fall back to a session check:
        Session session = resolveSession();
        if (session != null) {
            Boolean sessionAuthc = (Boolean) session.getAttribute(AUTHENTICATED_SESSION_KEY);
            authc = sessionAuthc != null && sessionAuthc;
        }
    }

    return authc;
}
项目:SilentGo    文件:RetryLimitHashedCredentialsMatcher.java   
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    String username = (String) token.getPrincipal();
    //retry count + 1
    AtomicInteger retryCount = (AtomicInteger) SilentGo.me().getConfig().getCacheManager().get("passwordRetryCache", username);
    if (retryCount == null) {
        retryCount = new AtomicInteger(0);
        SilentGo.me().getConfig().getCacheManager().set("passwordRetryCache", username, retryCount);
    }
    if (retryCount.incrementAndGet() > 5) {
        //if retry count > 5 throw
        throw new ExcessiveAttemptsException();
    }

    boolean matches = super.doCredentialsMatch(token, info);
    if (matches) {
        //clear retry count
        SilentGo.me().getConfig().getCacheManager().evict("passwordRetryCache", username);
    }
    return matches;
}
项目:BLOG-Microservice    文件:ShiroConfiguration.java   
/**
     * 凭证匹配器
     * (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
     *  所以我们需要修改下doGetAuthenticationInfo中的代码;
     * )
     * @return
     */
    @Bean
    public SimpleCredentialsMatcher /*HashedCredentialsMatcher*/ hashedCredentialsMatcher(){

        //1:
//        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//        hashedCredentialsMatcher.setHashAlgorithmName("md5");//MD5算法;
//        hashedCredentialsMatcher.setHashIterations(2);//散列的次数
//        return hashedCredentialsMatcher;

//2:或:
        SimpleCredentialsMatcher simpleCredentialsMatcher=  new SimpleCredentialsMatcher(){
            @Override
            public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
//
//                UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//                //将用户在页面输入的原始密码加密   param : 1.用户页面填写的密码, 加密的盐
//                //String pwd = Encrypt.md5(upToken.getPassword().toString(), upToken.getUsername());
//                String pwd = md5(new String(upToken.getPassword()), upToken.getUsername());
//                //3取出数据库加密的密码
//                Object dbPwd = info.getCredentials();  //从AuthRealm doGetAuthenticationInfo传入的密码,数据库查询的密码.
//
//                return  this.equals(pwd,dbPwd);
                return true;
            }
        };

        return simpleCredentialsMatcher;
    }
项目:BLOG-Microservice    文件:MyShiroRealm.java   
@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.err.println("MyShiroRealm.doGetAuthenticationInfo()");
       String username = (String) token.getPrincipal();
        System.err.println(username);

        User user = userService.findUserByUsername(username);

        if (user==null){
            return null;
        }

        System.err.println(salt);

        //1:
//        SimpleAuthenticationInfo authenticationInfo =
//                new SimpleAuthenticationInfo(
//                        user, //用户对象
//                        user.getPassword(), //密码
//                        ByteSource.Util.bytes(username+salt),//salt=username+salt
//                        getName()  //realm name
//                );

        //2:或:
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                username, //用户名
                user.getPassword(), //密码""
                getName()  //realm name
        );

        return authenticationInfo;
    }
项目:oauth2-shiro    文件:OAuth2CredentialsMatcher.java   
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    LOG.debug("Do credentials match, token: {}, info: {}", token, info);

    if (token instanceof OAuth2Token) {
        LOG.debug("Call [resources] CredentialsMatcher: {}", resourcesCredentialsMatcher);
        return resourcesCredentialsMatcher.doCredentialsMatch(token, info);
    } else {
        LOG.debug("Call [authz] CredentialsMatcher: {}", authzCredentialsMatcher);
        return authzCredentialsMatcher.doCredentialsMatch(token, info);
    }

}