org.apache.shiro.authc.AuthenticationInfo Java Examples

The following examples show how to use org.apache.shiro.authc.AuthenticationInfo. 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: UsernameRealm.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/**
 * 认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

	if (!(token instanceof UsernameToken)) return null;// 只认证UsernameToken

	if(Objects.isNull(token.getPrincipal()))
		throw new AuthenticationException(this.properties.getMsgAccountPasswordEmpty());
	String account = (String) token.getPrincipal();
	Account accountEntity = this.accountProvider.loadAccount(account);
	Boolean match = Boolean.TRUE;
	if (Objects.isNull(accountEntity)) {
		match = Boolean.FALSE;
		throw new AuthenticationException(this.properties.getMsgAccountNotExist());
	}
	return new SimpleAuthenticationInfo(account,match, getName());
}
 
Example #2
Source File: SearchFirstActiveDirectoryRealm.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Nullable
private AuthenticationInfo queryForAuthenticationInfo0(
        AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {

    final UsernamePasswordToken upToken = ensureUsernamePasswordToken(token);
    final String userDn = findUserDn(ldapContextFactory, upToken.getUsername());
    if (userDn == null) {
        return null;
    }

    LdapContext ctx = null;
    try {
        // Binds using the username and password provided by the user.
        ctx = ldapContextFactory.getLdapContext(userDn, upToken.getPassword());
    } catch (AuthenticationException e) {
        // According to this page, LDAP error code 49 (invalid credentials) is the only case where
        // AuthenticationException is raised:
        // - https://docs.oracle.com/javase/tutorial/jndi/ldap/exceptions.html
        // - com.sun.jndi.ldap.LdapCtx.mapErrorCode()
        return null;
    } finally {
        LdapUtils.closeContext(ctx);
    }
    return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
 
Example #3
Source File: JpaRealm.java    From init-spring with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
{
	String username = token.getPrincipal().toString();
	User user = this.jpaRealmRepository.findUserByName(username);

	if (null == user)
	{
		log.error("没有相关用户!");
		throw new UnknownAccountException();
	}

	String principal = username;
	String hashedCredentials = user.getPasswordHash();
	ByteSource credentialsSalt = ByteSource.Util.bytes(user.getName() + new String(user.getPasswordSalt()));
	String realmName = getName();

	SimpleAuthenticationInfo authentication = new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, realmName);
	return authentication;
}
 
Example #4
Source File: PamRealmTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoGetAuthenticationInfo() {
  PamRealm realm = new PamRealm();
  realm.setService("sshd");

  String pamUser = System.getenv("PAM_USER");
  String pamPass = System.getenv("PAM_PASS");
  assumeTrue(pamUser != null);
  assumeTrue(pamPass != null);

  // mock shiro auth token
  UsernamePasswordToken authToken = mock(UsernamePasswordToken.class);
  when(authToken.getUsername()).thenReturn(pamUser);
  when(authToken.getPassword()).thenReturn(pamPass.toCharArray());
  when(authToken.getCredentials()).thenReturn(pamPass);

  AuthenticationInfo authInfo = realm.doGetAuthenticationInfo(authToken);

  assertTrue(authInfo.getCredentials() != null);
}
 
Example #5
Source File: MyShiroRealm.java    From EasyReport with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
    throws AuthenticationException {
    final String account = (String)token.getPrincipal();
    final User user = this.membershipFacade.getUser(account);

    if (user == null) {
        throw new UnknownAccountException();
    }
    if (user.getStatus() == 0) {
        throw new LockedAccountException();
    }

    // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
    return new SimpleAuthenticationInfo(
        user.getAccount(), user.getPassword(),
        ByteSource.Util.bytes(user.getCredentialsSalt()),
        getName());
}
 
Example #6
Source File: AuthRealm.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 认证(主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确)
 *
 * @param token
 * @return
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    log.info("调用认证方法");
    //获取用户的输入的账号.
    String username = (String) token.getPrincipal();
    if (username == null) {
        throw new AuthenticationException("账号名为空,登录失败!");
    }

    log.info("credentials:" + token.getCredentials());
    UserInfo userInfo = userInfoService.findByUsername(username);
    if (userInfo == null) {
        throw new AuthenticationException("不存在的账号,登录失败!");
    }

    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
            userInfo,                                               //用户
            userInfo.getPassword(),                                 //密码
            ByteSource.Util.bytes(userInfo.getCredentialsSalt()),   //加盐后的密码
            getName()                                               //指定当前 Realm 的类名
    );
    return authenticationInfo;
}
 
Example #7
Source File: DBRealm.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken authenticationToken,
                                                        LdapContextFactory ldapContextFactory) throws NamingException {
    String token = (String) authenticationToken.getCredentials();
    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);

    if (null==username  || !JwtUtil.verify(token, username)) {
        throw new AuthenticationException("token认证失败!");
    }
    UserModel userModel= userService.getUserByUserName(username);
    if(null==userModel){
        return null;
    }
    return new SimpleAuthenticationInfo(token, token, "MyRealm");
}
 
Example #8
Source File: CredentialsMatcher.java    From springboot-learn with MIT License 6 votes vote down vote up
@Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        System.out.println("=================CredentialsMatcher.doCredentialsMatch=================");
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;
        //获得用户输入的密码:(可以采用加盐(salt)的方式去检验)
        String inPassword = new String(utoken.getPassword());
        //获得数据库中的密码
        String dbPassword = (String) info.getCredentials();
        try {
//            dbPassword = PasswordUtil.decrypt(dbPassword, utoken.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        //进行密码的比对
        return this.equals(inPassword, dbPassword);
    }
 
Example #9
Source File: Realm.java    From permission with Apache License 2.0 6 votes vote down vote up
/**
	 * 认证方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {
		System.out.println("认证中......");
		UsernamePasswordToken upt = (UsernamePasswordToken)token;
		String pwd = new String(upt.getPassword());
//		// 根据用户名和密码查找用户
		User user = userService.findUserByCodeAndPwd(upt.getUsername(), pwd);
		if(user != null) {
			//返回认证信息
			//参数1:主角,就是登陆的用户
			//参数2:证书,就是凭证,对应密码
			//参数3:当前realm的名称
			return new SimpleAuthenticationInfo(user, pwd, getName());
		}
		return null;
	}
 
Example #10
Source File: AppHandoffRealm.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {		
	SessionHandoff handoff = null;
	try {
		handoff = handoffDao.validate(((AppHandoffToken) token).getToken()).orElseThrow(() -> new IncorrectCredentialsException());
		AppHandoffMetrics.incValidateTokenSuccess();
	}catch(IncorrectCredentialsException e) {
		AppHandoffMetrics.incValidateTokenFailed();
		throw e;
	}
	if(checkSameIp) {
		String tokenHost = ((AppHandoffToken) token).getHost();
		if(StringUtils.isBlank(tokenHost) || StringUtils.isBlank(handoff.getIp()) || !tokenHost.equalsIgnoreCase(handoff.getIp())) {
			if(StringUtils.isBlank(handoff.getIp()) && StringUtils.isBlank(tokenHost)) {
				logger.warn("Both IP in token and app_handoff_token DB is null for person [{}].  Should not happen!", handoff.getPersonId());
			}
			AppHandoffMetrics.incSameIPFailed();
			throw new IncorrectCredentialsException();
		}
		AppHandoffMetrics.incSameIPSuccess();
	}
	Login login = new Login();
	login.setUserId(handoff.getPersonId());
	login.setUsername(handoff.getUsername());
	return new SimpleAuthenticationInfo(principalResolver.resolvePrincipal(login), token, getName()); 
}
 
Example #11
Source File: ApiRealm.java    From flash-waimai with MIT License 6 votes vote down vote up
/**
 * 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
    String token = (String) auth.getCredentials();
    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);
    if (username == null) {
        throw new AuthenticationException("token invalid");
    }

    ShiroUser userBean =  ShiroFactroy.me().shiroUser(userService.findByAccount(username));
    if (userBean == null) {
        throw new AuthenticationException("User didn't existed!");
    }

    if (! JwtUtil.verify(token, username, userBean.getPassword())) {
        throw new AuthenticationException("Username or password error");
    }

    return new SimpleAuthenticationInfo(token, token, "my_realm");
}
 
Example #12
Source File: AuthenticatingRealmImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testCreateWithPassowrd() throws Exception {
  buildTestAuthenticationConfig(CUser.STATUS_ACTIVE);

  String clearPassword = "default-password";
  String username = "testCreateWithPassowrdEmailUserId";

  CUser user = user("testCreateWithPassowrdEmail@somewhere", "testCreateWithPassowrdEmail",
      "testCreateWithPassowrdEmail", CUser.STATUS_ACTIVE, username, null);

  Set<String> roles = new HashSet<String>();
  roles.add("role");

  configurationManager.createUser(user, clearPassword, roles);

  UsernamePasswordToken upToken = new UsernamePasswordToken("testCreateWithPassowrdEmailUserId", clearPassword);
  AuthenticationInfo ai = realm.getAuthenticationInfo(upToken);
  String password = new String((char[]) ai.getCredentials());

  assertThat(passwordService.passwordsMatch(clearPassword, password), is(true));
}
 
Example #13
Source File: GitlabAuthenticatingRealm.java    From nexus3-gitlabauth-plugin with MIT License 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (!(token instanceof UsernamePasswordToken)) {
        throw new UnsupportedTokenException(String.format("Token of type %s  is not supported. A %s is required.",
                token.getClass().getName(), UsernamePasswordToken.class.getName()));
    }

    UsernamePasswordToken t = (UsernamePasswordToken) token;
    LOGGER.info("doGetAuthenticationInfo for {}", ((UsernamePasswordToken) token).getUsername());

    GitlabPrincipal authenticatedPrincipal;
    try {
        authenticatedPrincipal = gitlabClient.authz(t.getUsername(), t.getPassword());
        LOGGER.info("Successfully authenticated {}",t.getUsername());
    } catch (GitlabAuthenticationException e) {
        LOGGER.warn("Failed authentication", e);
        return null;
    }

    return createSimpleAuthInfo(authenticatedPrincipal, t);
}
 
Example #14
Source File: PamRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
        throws AuthenticationException {
  UsernamePasswordToken userToken = (UsernamePasswordToken) token;
  UnixUser user;

  try {
    user = (new PAM(this.getService()))
        .authenticate(userToken.getUsername(), new String(userToken.getPassword()));
  } catch (PAMException e) {
    throw new AuthenticationException("Authentication failed for PAM.", e);
  }

  return new SimpleAuthenticationInfo(
      new UserPrincipal(user),
      userToken.getCredentials(),
      getName());
}
 
Example #15
Source File: ZeppelinHubRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public void onLoginSuccess(String username, String session) {
  UserSessionContainer.instance.setSession(username, session);

  /* TODO(xxx): add proper roles */
  HashSet<String> userAndRoles = new HashSet<>();
  userAndRoles.add(username);
  ServiceContext context = new ServiceContext(
      new org.apache.zeppelin.user.AuthenticationInfo(username), userAndRoles);
  try {
    // This can failed to get NotebookServer instance with very rare cases
    NotebookServer.getInstance().broadcastReloadedNoteList(null, context);
  } catch (IOException e) {
    LOG.error("Fail to broadcastReloadedNoteList", e);
  }

  ZeppelinhubUtils.userLoginRoutine(username);
}
 
Example #16
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #17
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 用户认证
 *
 * @param authenticationToken 身份认证 token
 * @return AuthenticationInfo 身份认证信息
 * @throws AuthenticationException 认证相关异常
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的,已经经过了解密
    String token = (String) authenticationToken.getCredentials();

    String username = JWTUtil.getUsername(token);

    if (StringUtils.isBlank(username))
        throw new AuthenticationException("token校验不通过");

    // 通过用户名查询用户信息
    User user = SystemUtils.getUser(username);

    if (user == null)
        throw new AuthenticationException("用户名或密码错误");
    if (!JWTUtil.verify(token, username, user.getPassword()))
        throw new AuthenticationException("token校验不通过");
    return new SimpleAuthenticationInfo(token, token, "shiro_realm");
}
 
Example #18
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #19
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #20
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #21
Source File: AbstractCredentialsSecurerSupport.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate(@NotNull CredentialsToken token, @NotNull AuthenticationInfo info)
		throws CredentialsException, RuntimeException {
	/*
	 * Password is a string that may be set to empty.
	 * See:xx.realm.GeneralAuthorizingRealm#doAuthenticationInfo
	 */
	notNullOf(info, "storedCredentials");
	notNullOf(info.getCredentials(), "storedCredentials");

	// Delegate validate.
	if (!isNull(delegate) && !token.isSolved()) {
		return delegate.validate(resolves(token), info);
	}

	// # Assertion compare request credentials & storage credentials.
	return isEqual(toBytes(signature(token)), toBytes(info.getCredentials()));
}
 
Example #22
Source File: ShiroDbRealm.java    From dubai with MIT License 6 votes vote down vote up
/**
 * 认证回调函数,登录时调用.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
       try{
           UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
           User user = userService.findUserByLoginName(token.getUsername());
           if (user != null && user.getStatusCode() == UserStatus.Active.code()) {
               byte[] salt = Encodes.decodeHex(user.getSalt());
               return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getNiceName()),
                       user.getPassword(), ByteSource.Util.bytes(salt), getName());
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return null;
}
 
Example #23
Source File: HashedCredentialsMatcher.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param info the AuthenticationInfo from which to retrieve the credentials which assumed to be in already-hashed form.
 * @return a {@link Hash Hash} instance representing the given AuthenticationInfo's stored credentials.
 */
protected Object getCredentials(AuthenticationInfo info) {
    Object credentials = info.getCredentials();

    byte[] storedBytes = toBytes(credentials);

    if (credentials instanceof String || credentials instanceof char[]) {
        //account.credentials were a char[] or String, so
        //we need to do text decoding first:
        if (isStoredCredentialsHexEncoded()) {
            storedBytes = Hex.decode(storedBytes);
        } else {
            storedBytes = Base64.decode(storedBytes);
        }
    }
    AbstractHash hash = newHashInstance();
    hash.setBytes(storedBytes);
    return hash;
}
 
Example #24
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 #25
Source File: NpmTokenManager.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Verifies passed in principal/credentials combo, and creates (if not already exists) a npm token mapped to given
 * principal and returns the newly created token.
 */
public String login(final String username, final String password) {
  checkNotNull(username);
  checkNotNull(password);

  try {
    AuthenticationInfo authenticationInfo = securityHelper.getSecurityManager().authenticate(
        new UsernamePasswordToken(username, password));
    return super.createToken(authenticationInfo.getPrincipals());
  }
  catch (AuthenticationException e) {
    log.debug("Bad credentials provided for npm token creation", e);
    return null;
  }
}
 
Example #26
Source File: ExceptionModularRealmAuthenticator.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
	AuthenticationStrategy strategy = getAuthenticationStrategy();
	AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
	if (log.isTraceEnabled()) {
		log.trace("Iterating through {} realms for PAM authentication", realms.size());
	}

	for (Realm realm : realms) {
		aggregate = strategy.beforeAttempt(realm, token, aggregate);
		if (realm.supports(token)) {
			if (log.isTraceEnabled()) {
				log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);
			}

			AuthenticationInfo info = null;
			Throwable t = null;
			try {
				info = realm.getAuthenticationInfo(token);
			} catch (Throwable throwable) {
				t = throwable;
				throw new AuthenticationException(t);
			} finally {
				aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);
			}
		} else if (log.isDebugEnabled()) {
			log.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
		}
	}

	return strategy.afterAllAttempts(token, aggregate);
}
 
Example #27
Source File: CheckRealm.java    From notes with Apache License 2.0 5 votes vote down vote up
/**
 * @return org.apache.shiro.authc.AuthenticationInfo
 * @Author fruiqi
 * @Description 默认使用此方法进行用户名正确与否校验,出错抛出异常
 * @Date 2:30 2019/3/9
 * @Param [token]
 **/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    JwtToken jwtToken = (JwtToken) token;
    String tokenContent = (String) jwtToken.getCredentials();
    String name = JwtUtil.getUsername(tokenContent);
    AdminDto adminDto = AdminShiroService.selectAdminByAdminName(name);
    if (adminDto == null) {
        throw new AuthorizationException(ERROR_CHECK_NAME_ERROR100013.getInfo());
    }

    Map<String, Object> map = new HashMap<>();
    map.put("userName", name);
    map.put("userId", adminDto.getAdminId());
    map.put("timestamp", getTimeStamp(tokenContent));
    if (!JwtUtil.verify(tokenContent, map, JWT_SECRET)) {
        throw new AuthenticationException(ERROR_CHECK_NAME_ERROR100014.getInfo());
    }
    ;

    String admin = "admin";
    if (adminDto.getAdminGrade() == 1) {
        admin = "superAdmin";
    }

    if (adminDto.getAdminGrade() == 0) {
        admin = "admin" ;
    }


    return new SimpleAuthenticationInfo(tokenContent, tokenContent, admin);
}
 
Example #28
Source File: CreateShiroAuthProviderTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

  return new AuthenticationInfo() {
    @Override
    public PrincipalCollection getPrincipals() {
      return new SimplePrincipalCollection(token.getPrincipal(), getClass().getName());
    }

    @Override
    public Object getCredentials() {
      return token.getCredentials();
    }
  };
}
 
Example #29
Source File: GenericCredentialsHashedMatcher.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public boolean doMatching(IamAuthenticationToken token, AuthenticationInfo info, List<String> factors) {
	GenericAuthenticationToken tk = (GenericAuthenticationToken) token;
	// Before preCheck.
	if (!coprocessor.preAuthenticatingAllowed(tk, info)) {
		throw new AccountException(bundle.getMessage("ServerSecurityCoprocessor.accessDenied", tk.getPrincipal()));
	}

	// Matching credentials.
	CredentialsToken credentialsToken = new CredentialsToken((String) tk.getPrincipal(), (String) tk.getCredentials(),
			tk.getSecureAlgKind());
	return securer.validate(credentialsToken, info);
}
 
Example #30
Source File: CacheDelegator.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 清扫账号对应的认证、授权缓存
 */
public void clearAuthCache(String account, String realmName) {
	synchronized (cacheMonitor) {
		Cache<String, AuthenticationInfo> authenticationCache = this.cacheManager
				.getCache(ShiroProperties.CACHE_NAME_AUTHENTICATION);
		Cache<Object, AuthorizationInfo> authorizationCache = this.cacheManager
				.getCache(ShiroProperties.CACHE_NAME_AUTHORIZATION);
		authenticationCache.remove(account);
		authorizationCache.remove(new SimplePrincipalCollection(account, realmName));
	}
}