Java Code Examples for org.apache.shiro.authc.UsernamePasswordToken#getUsername()

The following examples show how to use org.apache.shiro.authc.UsernamePasswordToken#getUsername() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MockRealm.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  UsernamePasswordToken upToken = (UsernamePasswordToken) token;

  String password = new String(upToken.getPassword());
  String userId = upToken.getUsername();

  // username == password
  try {
    if (userId.endsWith(password) && userManager.getUser(userId) != null) {
      return new SimpleAuthenticationInfo(new SimplePrincipalCollection(token.getPrincipal(),
          this.getName()), userId);
    }
    else {
      throw new IncorrectCredentialsException("User [" + userId + "] bad credentials.");
    }
  }
  catch (UserNotFoundException e) {
    throw new UnknownAccountException("User [" + userId + "] not found.");
  }
}
 
Example 2
Source File: JdbcAuthenticationRealm.java    From base-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 用户登录的身份验证方法
 * 
 */
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());
}
 
Example 3
Source File: MyCustomRealm.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
  throws AuthenticationException {

    UsernamePasswordToken uToken = (UsernamePasswordToken) token;

    if(uToken.getUsername() == null
      || uToken.getUsername().isEmpty()
      || !credentials.containsKey(uToken.getUsername())
      ) {
        throw new UnknownAccountException("username not found!");
    }


    return new SimpleAuthenticationInfo(
      uToken.getUsername(), credentials.get(uToken.getUsername()),
      getName());
}
 
Example 4
Source File: OrientDbRealm.java    From spring-boot-shiro-orientdb with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
        final AuthenticationToken token)
        throws AuthenticationException {
    final UsernamePasswordToken credentials = (UsernamePasswordToken) token;
    final String email = credentials.getUsername();
    if (email == null) {
        throw new UnknownAccountException("Email not provided");
    }
    final User user = userRepository.findByEmailAndActive(email, true);
    if (user == null) {
        throw new UnknownAccountException("Account does not exist");
    }
    return new SimpleAuthenticationInfo(email, user.getPassword().toCharArray(),
            ByteSource.Util.bytes(email), getName());
}
 
Example 5
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
/**
 * Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for
 * the specified username.  This method binds to the LDAP server using the provided username
 * and password - which if successful, indicates that the password is correct.
 * <p/>
 * This method can be overridden by subclasses to query the LDAP server in a more complex way.
 *
 * @param token              the authentication token provided by the user.
 * @param ldapContextFactory the factory used to build connections to the LDAP server.
 * @return an {@link AuthenticationInfo} instance containing information retrieved from LDAP.
 * @throws NamingException if any LDAP errors occur during the search.
 */
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
        LdapContextFactory ldapContextFactory) throws NamingException {
  UsernamePasswordToken upToken = (UsernamePasswordToken) token;

  // Binds using the username and password provided by the user.
  LdapContext ctx = null;
  try {
    String userPrincipalName = upToken.getUsername();
    if (!isValidPrincipalName(userPrincipalName)) {
      return null;
    }
    if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
      userPrincipalName = upToken.getUsername() + this.principalSuffix;
    }
    ctx = ldapContextFactory.getLdapContext(
        userPrincipalName, upToken.getPassword());
  } finally {
    LdapUtils.closeContext(ctx);
  }

  return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
 
Example 6
Source File: DbRealm.java    From dpCms with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 7
Source File: AuthenticatingRealmImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) {
  UsernamePasswordToken upToken = (UsernamePasswordToken) token;

  CUser user;
  try {
    user = configuration.readUser(upToken.getUsername());
  }
  catch (UserNotFoundException e) {
    throw new UnknownAccountException("User '" + upToken.getUsername() + "' cannot be retrieved.", e);
  }

  if (user.getPassword() == null) {
    throw new CredentialsException("User '" + upToken.getUsername() + "' has no password, cannot authenticate.");
  }

  if (user.isActive()) {
    // 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() + "'.");
  }
}
 
Example 8
Source File: MockRealmB.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example 9
Source File: AdminAuthorizingRealm.java    From dts-shop with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

	UsernamePasswordToken upToken = (UsernamePasswordToken) token;
	String username = upToken.getUsername();
	String password = new String(upToken.getPassword());

	if (StringUtils.isEmpty(username)) {
		throw new AccountException("用户名不能为空");
	}
	if (StringUtils.isEmpty(password)) {
		throw new AccountException("密码不能为空");
	}

	List<DtsAdmin> adminList = adminService.findAdmin(username);
	Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
	if (adminList.size() == 0) {
		logger.error("找不到用户(" + username + ")的帐号信息");
		throw new UnknownAccountException("找不到用户(" + username + ")的帐号信息");
	}
	DtsAdmin admin = adminList.get(0);

	BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
	if (!encoder.matches(password, admin.getPassword())) {
		logger.error("找不到用户(" + username + ")的帐号信息");
		throw new UnknownAccountException("找不到用户(" + username + ")的帐号信息");
	}

	return new SimpleAuthenticationInfo(admin, password, getName());
}
 
Example 10
Source File: MockRealmA.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
    throws AuthenticationException
{
  // only allow jcoder/jcoder

  UsernamePasswordToken userpass = (UsernamePasswordToken) token;
  if ("jcoder".equals(userpass.getUsername()) && "jcoder".equals(new String(userpass.getPassword()))) {
    return new SimpleAuthenticationInfo(userpass.getUsername(), new String(userpass.getPassword()), this.getName());
  }

  return null;
}
 
Example 11
Source File: HibernateRealm.java    From niubi-job with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    String username = upToken.getUsername();
    User param = new User();
    param.setUserName(username);
    return baseDao.getUnique(User.class, param);
}
 
Example 12
Source File: NexusKeycloakClient.java    From nexus3-keycloak-plugin with Apache License 2.0 5 votes vote down vote up
public boolean authenticate(UsernamePasswordToken token) {
    String principal = token.getUsername();
    String credentials = new String(token.getPassword());
    AccessTokenResponse accessTokenResponse = this.keycloakAdminClient.obtainAccessToken(principal, credentials);

    return accessTokenResponse != null && StringUtils.hasText(accessTokenResponse.getToken());
}
 
Example 13
Source File: ExtendedPropertiesRealm.java    From tapestry-security with Apache License 2.0 5 votes vote down vote up
/**
 * Eliminates the error generating NullPointerException,
 * when trying to register for non-existent account.
 *
 * @see org.apache.shiro.realm.SimpleAccountRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
{

	UsernamePasswordToken upToken = (UsernamePasswordToken) token;
	if (!accountExists(upToken.getUsername()))
	{
		throw new UnknownAccountException("Unknown account " + upToken.getUsername());
	}

	return super.doGetAuthenticationInfo(token);
}
 
Example 14
Source File: CustomDomainADRealm.java    From opensoc-streaming with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthenticationInfo queryForAuthenticationInfo(
		AuthenticationToken token, LdapContextFactory ldapContextFactory)
		throws NamingException {

	UsernamePasswordToken upToken = (UsernamePasswordToken)token;
	String userName = upToken.getUsername();
	upToken.setUsername( userName + "@" + customDomain );
	
	return super.queryForAuthenticationInfo(token, ldapContextFactory);
}
 
Example 15
Source File: MyBatisRealm.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
@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.");
    }

    SqlSession sqlSession = null;
    Connection conn = null;
    SimpleAuthenticationInfo info = null;
    try {
    	if(sqlSessionManager == null) {
    		sqlSessionManager = GlobalSqlSession.get(dataSourceName);
    	}
    	
        conn = (sqlSession = sqlSessionManager.openSession()).getConnection();
        String password = null;
        String salt = null;
        switch (saltStyle) {
        case NO_SALT:
            password = getPasswordForUser(conn, username)[0];
            break;
        case CRYPT:
            // TODO: separate password and hash from getPasswordForUser[0]
            throw new ConfigurationException("Not implemented yet");
            //break;
        case COLUMN:
            String[] queryResults = getPasswordForUser(conn, username);
            password = queryResults[0];
            salt = queryResults[1];
            break;
        case EXTERNAL:
            password = getPasswordForUser(conn, username)[0];
            salt = getSaltForUser(username);
        }

        if (password == null) {
            throw new UnknownAccountException("No account found for user [" + username + ']');
        }

        info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
        
        if (salt != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(salt));
        }

    } catch (SQLException e) {
        final String message = "There was a SQL error while authenticating user [" + username + ']';
    	LOGGER.error(message, e);

        // Rethrow any SQL errors as an authentication exception
        throw new AuthenticationException(message, e);
    } finally {
        if(sqlSession != null) {
            sqlSession.close();
        }
    }

    return info;
}
 
Example 16
Source File: ShiroAuthRealm.java    From belling-admin with Apache License 2.0 4 votes vote down vote up
/**
 * 认证回调函数,登录时调用.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
	UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
	return new SimpleAuthenticationInfo(token.getUsername(), new String(token.getPassword()), getName());
}
 
Example 17
Source File: AccountRealm.java    From Roothub with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	// 1. 把 AuthenticationToken 转换为 UsernamePasswordToken 
	UsernamePasswordToken upToken = (UsernamePasswordToken) token;
	
	// 2. 从 UsernamePasswordToken 中来获取 userName
	String userName = upToken.getUsername();
			
	logger.debug("用户:{} 正在登录...", userName);
	
	// 3.从数据库中查询 username 对应的用户记录
	// AdminUser adminUser = adminUserService.getByName(username);
	QueryWrapper<User> queryWrapper = new QueryWrapper<>();
	queryWrapper.eq("user_name", userName);
	UserDTO userDTO = this.userService.getOne(queryWrapper);
	
	// 4.如果用户不存在,则抛出未知用户的异常
	// if(adminUser == null) throw new UnknownAccountException("用户不存在!");
	if (userDTO == null) throw new UserException(UserErrorCodeEnum.NOT_FOUND);
	
	// 5.根据用户的情况, 来构建 AuthenticationInfo 对象并返回,通常使用的实现类为: SimpleAuthenticationInfo
	
	/**
	 * 5.1 principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象. 
	 * 可以通过 SecurityUtils.getSubject().getPrincipal() 拿到 principal,如果有多个,则随机返回其中的一个
	 * 也可以通过 PrincipalCollection.getPrimaryPrincipal() 拿到 principal,如果有多个,则随机返回其中的一个
	 * 也可以通过 PrincipalCollection.asSet() 拿到所有的 principal,返回的是 set 集合
	 */
	// Object principal = username;
	// AdminUser principal = new AdminUser();
	// principal.setAdminUserId(adminUser.getAdminUserId());
	// principal.setUsername(username);
	// principal.setAvatar(adminUser.getAvatar());
	
	// 5.2 credentials: 密码
	// Object credentials = adminUser.getPassword();
	Object credentials = userDTO.getPassword();
	
	// 5.3 realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
	String realmName = getName();
	
	// 5.4 盐值加密
	ByteSource credentialsSalt = ByteSource.Util.bytes(userName);
	
	return new SimpleAuthenticationInfo(userDTO, credentials, credentialsSalt, realmName);
}