(二)手写一个简单的shiro实例

注:这里只是简单地写个demo,旨在理解shiro,在实际开发中并不会这么写。

1、新建一个Java项目,并导入以下jar包

  • log4j-1.2.7.jar
  • shiro-all-1.3.2.jar
  • slf4j-api-1.7.25.jar
  • slf4j-log4j12-1.7.25.jar

2、 在src目录下创建 log4j.properties和shiro.ini两个配置文件
log4j.properties

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=TRACE
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

shiro.ini

[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

3、创建Quickstart类

package com.lyz.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Quickstart {
    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);

    public static void main(String[] args) {
        //创建securityManager工厂  读取shiro的配置文件
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //获取SecurityManager实例
        SecurityManager securityManager = factory.getInstance();
        //将securityManager设置到运行环境中
        SecurityUtils.setSecurityManager(securityManager);
        // 获取当前的subject
        Subject currentUser = SecurityUtils.getSubject();
        //测试session
        //获取session
        Session session = currentUser.getSession();
        //设置session
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        //判断session中是否有aValue这个值
        if (value.equals("aValue")) {
            log.info("-->Retrieved the correct value! [" + value + "]");
        }

        // 判断当前用户是否被认证
        if (!currentUser.isAuthenticated()) {//认证失败
            //将用户名和密码封装到token中
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            //记住我
            token.setRememberMe(true);
            try {
                //执行登录
                currentUser.login(token);
            } catch (UnknownAccountException uae) {//没有指定的用户
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {//若账户存在,但密码不匹配,则抛出这个异常
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {//用户被锁定异常
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            } catch (AuthenticationException ae) {//所有认证异常的父类
                //unexpected condition?  error?
            }
        }
        //用户认证成功
        log.info("===User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //测试某个角色:
        if (currentUser.hasRole("schwartz")) {
            log.info("-->May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }

        //测试用户是否有具备某一个行为,
        if (currentUser.isPermitted("lightsaber:weild")) {
            log.info("++++You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //测试用户是否具备某个行为(更为具体的行为:如张三具有删除的行为
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("()()You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }
        //退出登录!
        currentUser.logout();
    }
}

4、测试 :运行main()方法

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42570879/article/details/84952691