java小王博客

记录菜B的一点一滴,欢迎各位好汉前来叨扰!


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>博主qq:1756691861

Shiro简单验证

2020-6-2 卑微小王

package com.qr.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
/**

 * @author LiuQi
 */
public class ShiroDemo {
    public static void main(String[] args) {
        //1.创建安全管理器对象
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //2.给安全管理器设置Realm
        defaultSecurityManager.setRealm(new IniRealm("classpath:shiro.ini"));
        //3.SecurityUtils 给全局安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //4.关键对象 subject 主体
        Subject subject = SecurityUtils.getSubject();
        //5.创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken("xiaobai", "123456");


        try {
            System.out.println("认证状态:" + subject.isAuthenticated());

            subject.login(token); //用户认证

            System.out.println("认证状态:" + subject.isAuthenticated());

            System.out.println("认证通过");
        } catch (UnknownAccountException e) {

            e.printStackTrace();
            System.out.println("该用户名不存在~~~");
            System.out.println("认证失败");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("该密码不存在~~~");
            System.out.println("认证失败");
        }


    }
}

文章转自:https://www.cnblogs.com/LQ970811/p/12986138.html

发表评论: