shiro 简单的身份验证 案例

Apache Shiro是Java的一个安全框架,Shiro可以帮助我们完成:认证、授权、加密、会话管理、与Web集成、缓存等.

简单的身份验证

项目目录:

首先,在shiro.ini里配置了用户名和密码

 用户名为 hello 密码为 123

项目使用了maven

在pom.xml中添加所需要的依赖

SayHello.java

package com.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.mgt.SecurityManager;

public class SayHello {

    /**
     * @return
     */
    public static void main(String[] args) {
        
        // 读取配置文件,初始化SecurityManager工厂 读取shiro.ini文件
        Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");
        
        // 获取securityManager实例
        SecurityManager securityManager=factory.getInstance();
        
        // 把securityManager实例绑定到SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        
        // 得到当前执行的用户
        Subject currentUser=SecurityUtils.getSubject();
        
        // 创建token令牌,用户名/密码
        UsernamePasswordToken token=new UsernamePasswordToken("hello", "1234");
        
        try{
            //身份认证
            currentUser.login(token);    
            System.out.println("身份认证成功!sayHello");
        }catch(AuthenticationException e){
            e.printStackTrace();
            System.out.println("身份认证失败!");
        }
        // 退出
        currentUser.logout();
        
    }

}

 测试:

  1), 当用户名,密码与shiro.ini中的配置一致时

    

  控制台显示身份验证通过

    

  2), 当用户名,密码与shiro.ini中的配置不一致的时候

    

   控制台显示身份验证失败,抛出异常

    

  抛出的异常

    org.apache.shiro.authc.IncorrectCredentialsException: Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - hello, rememberMe=false] did not match the expected credentials.

   did not match the expected credentials. 与预期的凭证不匹配 其实就是用户名与密码不对

  以上就是一简单的身份验证过程,在上面shiro.ini里配置了用户名与密码,在实际开发中用户信息应该是在数据库中检索出来的数据,详见下一站

  

  本篇只是为了记录自己的学习

          学习需沉淀,厚积而薄发

  感谢: http://www.java1234.com/

原文地址:https://www.cnblogs.com/cmyxn/p/5825099.html