Shiro安全框架(SpringBoot整合Shiro)

搭建一个Shiro

在这里插入图片描述
Subject:用户
SecurityManager:管理所有用户
Realm:连接数据

第一步:导入依赖

    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.1</version>
        </dependency>

        <!-- configure logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>

        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

第二步:配置文件
配置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=INFO

# 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 with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[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

实现Quickstart类

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;


/**
 * Simple Quickstart application showing how to use Shiro's API.
 *
 * @since 0.9 RC2
 */
public class Quickstart {
    
    

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


    public static void main(String[] args) {
    
    

        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        SecurityUtils.setSecurityManager(securityManager);

        //以上三步是固定的:大致意思就是将这个通过配置文件,创建出一个对象,我们再去获取这个对象(这个对象是单例的)
        
        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
        //获取当前的对象
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        //通过当前用户拿到Session
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
    
    
            log.info("Retrieved the correct value! [" + value + "]");
        }

        // let's login the current user so we can check against roles and permissions:
        //测试当前的用户是否被认证
        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 more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
    
    
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        //存一些信息
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        //获得用户拥有什么角色
        if (currentUser.hasRole("schwartz")) {
    
    
            log.info("May the Schwartz be with you!");
        } else {
    
    
            log.info("Hello, mere mortal.");
        }

        //粗粒度
        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:wield")) {
    
    
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
    
    
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //细粒度
        //a (very powerful) Instance Level permission:
        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!");
        }

        //注销
        //all done - log out!
        currentUser.logout();

        //结束
        System.exit(0);
    }
}
 //获取当前的对象
 Subject currentUser = SecurityUtils.getSubject();
 //通过当前用户拿到Session
 Session session = currentUser.getSession();
 //测试当前的用户是否被认证
 !currentUser.isAuthenticated()
 //存一些信息
 currentUser.getPrincipal() 
 //获得用户拥有什么角色
 currentUser.hasRole("schwartz")
 //粗粒度
 currentUser.isPermitted("lightsaber:wield")
 //注销
 currentUser.logout();

即可开启Shiro
在这里插入图片描述

SpringBoot整合Shiro

第一步:导入依赖

<!--spring整合shiro-->
<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-spring</artifactId>
   <version>1.4.1</version>
</dependency>

第二步和第三步是核心配置

第二步:自定义UserRealm对象(用户认证和授权登录) 可以对比SpringSecurity

/**
 * @author acoffee
 * @create 2021-09-22 19:13
 */
//自定义的需要UserRealm继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    
    

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    
    
        System.out.println("执行了→授权doGetAuthorizationInfo");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    
    
        System.out.println("执行了→认证doGetAuthenticationInfo");
        return null;
    }
}

第三步:配置ShiroConfig(Shiro对比SpringSecurity就多了以下几步,这三个Bean)

@Configuration
public class ShiroConfig {
    
    

    //这三个方法环环相扣,与我们最开始那张图相对应,我们为了对应哪张图的顺序,所以在这里我们采取了这种写法
    //第三步
    //ShiroFilterFactoryBean
    //@Qualifier:Qualifier的意思是合格者,通过这个标示,表明了哪个实现类才是我们所需要的;
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager")DefaultSecurityManager defaultSecurityManager ){
    
    
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);
        return bean;
    }

    //第二步
    //DefaultWebSecurityManager
    @Bean(name = "SecurityManager")
    public DefaultWebSecurityManager getDefaultSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
    
    
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager ();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //第一步
    //创建Realm对象,需要自定义类
    @Bean
    public UserRealm userRealm(){
    
    
        return new UserRealm();
    }
}

拦截功能

我们接下来写一个controller和几张页面测试
index.html

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>

<a th:href="@{/user/add}">add</a> |
<a th:href="@{/user/update}">update</a>

</body>
</html>

update.html

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>

add.html

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>登录</h1>
    <form action=""></form>
    <p>用户名:<input type="text" name="username"></p>
    <p>密码:<input type="text" name="password"></p>
    <p><input type="submit"></p>
</body>
</html>

controller

/**
 * @author acoffee
 * @create 2021-09-22 18:56
 */

@Controller
public class MyController {
    
    

    @RequestMapping({
    
    "/","/index"})
    public String toIndex(Model model){
    
    
        model.addAttribute("msg","hello,Shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String toAdd(){
    
    
       return "user/add";
    }

    @RequestMapping("/user/update")
    public String toUpdate(){
    
    
       return "user/update";
    }

    @RequestMapping("toLogin")
    public String toLogin(){
    
    
        return "login";
    }
}

我们在 ShiroConfig 中添加过滤条件

名称 作用
anon 无需认证就可以访问
authc 必须认证了才能访问
user 必须拥有记住我功能才能用
perms 拥有对某个资源的权限才能访问;
role 拥有某个角色权限才能访问
@Configuration
public class ShiroConfig {
    
    

    //这三个方法环环相扣,与我们最开始那张图相对应,我们为了对应哪张图的顺序,所以在这里我们采取了这种写法
    //第三步
    //ShiroFilterFactoryBean
    //@Qualifier:Qualifier的意思是合格者,通过这个标示,表明了哪个实现类才是我们所需要的;
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager")DefaultSecurityManager defaultSecurityManager ){
    
    
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);
        /*
        * anon:无需认证就可以访问
        * authc:必须认证了才能访问
        * user:必须拥有记住我功能才能用
        * perms :拥有对某个资源的权限才能访问;
        * role:拥有某个角色权限才能访问
        * */
        Map<String, String> filterMap = new LinkedHashMap<>();

        filterMap.put("/user/*","authc");

        //Chain:链式的,所以我们这里采用LinkedHashMap
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        bean.setLoginUrl("/toLogin");

        return bean;
    }

    //第二步
    //DefaultWebSecurityManager
    @Bean(name = "SecurityManager")
    public DefaultWebSecurityManager getDefaultSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
    
    
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //第一步
    //创建Realm对象,需要自定义类
    @Bean
    public UserRealm userRealm(){
    
    
        return new UserRealm();
    }
}

这两个都会被拦截,从而跳转到 登录页面
在这里插入图片描述

认证功能

我们将我们的login.html 改以下

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>登录</h1>
    <hr>
    <p th:text="${msg}" style="color: red;"></p>
    <form th:action="@{/login}">
    <p>用户名:<input type="text" name="username"></p>
    <p>密码:<input type="text" name="password"></p>
    <p><input type="submit"></p>
    </form>
</body>
</html>

在Controller组件的中添加login方法

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
    
    
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //执行登录的方法,如果没有异常就ok了
        //即登录成功就进入首页,登录失败就返回登录页
        try {
    
    
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
    
    
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e) {
    
    
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

修改UserRealm 类中的认证方法

//自定义的需要UserRealm继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    
    

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    
    
        System.out.println("执行了→授权doGetAuthorizationInfo");
        return null;
    }

    //认证
    //只要点登录就会走以下方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    
    
        System.out.println("执行了→认证doGetAuthenticationInfo");

        //用户名,密码 在数据库中取
        //我们在这里模拟数据库
        String name = "root";
        String password = "123456";

        //我们这个类在Controller中的login方法中被用到过,去接收用户名和密码,
        // 他是全局的所以在这里我们也能通过他去得到用户输入的用户名和密码
        UsernamePasswordToken usertoken = (UsernamePasswordToken)token;

        if(!usertoken.getUsername().equals(name)){
    
    
            return null;//我们在这里return null,它会自动抛出我们在Controller写的UnknownAccountException异常
        }

        //密码认证,不需要我们做,shiro帮我们做,因为害怕密码泄露
        return new SimpleAuthenticationInfo("",password,"");
    }
}

我们来测试

输入错误的密码
在这里插入图片描述

输入错误的用户名
在这里插入图片描述
输入正确的用户名和密码即可登录
在这里插入图片描述

授权功能

在这里插入图片描述
ShiroConfig 类:

@Configuration
public class ShiroConfig {
    
    

    //这三个方法环环相扣,与我们最开始那张图相对应,我们为了对应哪张图的顺序,所以在这里我们采取了这种写法
    //第三步
    //ShiroFilterFactoryBean
    //@Qualifier:Qualifier的意思是合格者,通过这个标示,表明了哪个实现类才是我们所需要的;
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager")DefaultSecurityManager defaultSecurityManager ){
    
    
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);
        /*
        * anon:无需认证就可以访问
        * authc:必须认证了才能访问
        * user:必须拥有记住我功能才能用
        * perms :拥有对某个资源的权限才能访问;
        * role:拥有某个角色权限才能访问
        * */
        //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();

        //授权,正常的情况下,没有授权会跳转到提示未授权页面
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");

        filterMap.put("/user/*","authc");

        //Chain:链式的,所以我们这里采用LinkedHashMap
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        bean.setLoginUrl("/toLogin");

        //未授权的请求
        bean.setUnauthorizedUrl("/noauth");

        return bean;
    }

    //第二步
    //DefaultWebSecurityManager
    @Bean(name = "SecurityManager")
    public DefaultWebSecurityManager getDefaultSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
    
    
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //第一步
    //创建Realm对象,需要自定义类
    @Bean
    public UserRealm userRealm(){
    
    
        return new UserRealm();
    }
}

UserRealm 类:

public class UserRealm extends AuthorizingRealm {
    
    

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    
    
        System.out.println("执行了→授权doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //增加权限
        //info.addStringPermission("user:add");

        //从 认证中 拿到 当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currUser = (User)subject.getPrincipal();

        //设置当前用户的权限:从数据中去get当前用户的权限
        info.addStringPermission(currUser.getPerms());

        return info;
    }

    //认证
    //只要点登录就会走以下方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    
    
        System.out.println("执行了→认证doGetAuthenticationInfo");

        //我们这个类在Controller中的login方法中被用到过,去接收用户名和密码,
        // 他是全局的所以在这里我们也能通过他去得到用户输入的用户名和密码
        UsernamePasswordToken usertoken = (UsernamePasswordToken)token;

        //连接真实的数据库
        User user = userService.queryUserByUname(usertoken.getUsername());

        if(user == null){
    
    
            return null;//UnknownAccountException
        }


        //默认SimpleCredentialsMatcher 我们可以使用MD5加密:e10adc3949ba59abbe56e057f20f883e(123456)
        //但是因为是固定的 容易破解所以我们一般使用MD5盐值加密,
        // 例如在e10adc3949ba59abbe56e057f20f883e+username这种组合
        //密码认证,不需要我们做,shiro帮我们做,因为害怕密码泄露
        //将user存入第一个位置我们就可以在授权中拿到
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");

    }
}

我们登陆root用户
在这里插入图片描述
执行结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44742328/article/details/120355797