springboot整合shiro


前言

Shiro是Apache下的一个开源项目。shiro属于轻量级框架,相对于SpringSecurity简单的多,也没有SpringSecurity那么复杂。


准备工作

1.创建springboot项目,导入web模块(thymeleaf可导可不导)

2.导入Maven依赖thymeleaf

<!--thymeleaf模板-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.5.4</version>
        </dependency>

3.编写index.html页面(templates目录下)

<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<hr>

<!--跳转需通过shiro认证-->
<a th:href="@{/user/add}">add</a> | <a th:href="@{/user/update}">update</a>
</body>
</html>

4.编写登录login.html页面

<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="${msg}" style="color:crimson"></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>

整合shiro

核心API:

  1. Subject:用户主体
  2. SecurityManager:安全管理器
  3. Realm:Shiro 连接数据
  • 导入shiro和spring整合依赖
<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.1</version>
 </dependency>
  • 编写Shiro 配置类 (config包下)
package com.kuang.config;
import org.springframework.context.annotation.Configuration;

//声明为配置类
@Configuration
public class ShiroConfig {
    
//创建 ShiroFilterFactoryBean
    
//创建 DefaultWebSecurityManager
    
//创建 realm 对象
}
  • 我们倒着来,先想办法创建一个 realm 对象
  • 我们需要自定义一个 realm 的类,用来编写一些查询的方法,或者认证与授权的逻辑
package com.huang.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权");
        return null;
    }

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

  • 将这个类注册到Ioc容器中( ShiroConfig中)

    @Configuration
    public class ShiroConfig {
    //创建 ShiroFilterFactoryBean
    //创建 DefaultWebSecurityManager
    //创建 realm 对象
    @Bean
    public UserRealm userRealm(){
    	return new UserRealm();
    }
    }
    
  • 接下来我们该去创建 DefaultWebSecurityManager

 //DafaultWebSecurityManager:2
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
  • 接下来我们该去创建 ShiroFilterFactoryBean
 @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        
//设置安全管理器        	
        bean.setSecurityManager(defaultWebSecurityManager);

        return bean;
    }
页面拦截实现

anon:无需认证就可以访问
authc:必须认证了才能访问
use: 必须拥有 记住我 功能才能用
perms: 拥有对某个资源的权限才能访问
role: 拥有某个角色权限才能访问

  1. 编写两个页面、在templates目录下新建一个 user 目录 add.html update.html
<body>
<h1>add</h1>
</body>
<body>
<h1>update</h1>
</body>

​ 2.编写跳转到页面的controller

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

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

​ 3.添加shiro内置过滤器

 @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro的内置过滤器
        /*
            anon:无需认证就可以访问
            authc:必须认证了才能访问
            use: 必须拥有 记住我 功能才能用
            perms: 拥有对某个资源的权限才能访问
            role: 拥有某个角色权限才能访问
         */
        Map<String,String> filterMap=new HashMap<>();

        filterMap.put("/user/add","authc");
        filterMap.put("/user/update","authc");

        bean.setFilterChainDefinitionMap(filterMap);

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

        return bean;
    }

​ 4.再起启动测试,访问链接进行测试!拦截OK!但是发现,点击后会跳转到一个shiro的Login.jsp页面,这 个不是我们想要的效果,我们需要自己定义一个Login页面!

​ 5.我们编写一个自己的Login页面

<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="${msg}" style="color:crimson"></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>

​ 6.编写跳转login页面的controller

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

​ ShiroFilterFactoryBean中设置拦截跳转页面

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

​ 7.再次测试跳转,成功跳转自定义页面

8.优化代码,拦截请求可以使用通配符操作

  //filterMap.put("/user/add","authc");
   // filterMap.put("/user/update","authc");
       filterMap.put("/user/*","authc");
       bean.setFilterChainDefinitionMap(filterMap);
登录认证操作

1.编写登录的controller

 @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前的用户
        Subject subject= SecurityUtils.getSubject();

        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try{
            subject.login(token);//执行登录方法,如果没有异常说明ok
            return "index";   //trycatch中的return是最后执行的
        }catch(UnknownAccountException uae){ //用户名不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg","密码错误");
            return "login";
        } catch (LockedAccountException lae) {
            model.addAttribute("msg","用户名被锁定");
            return "login";
        }


    }	

2.前端页面对应的msg提示信息和登录信息提交地址

<p th:text="${msg}" style="color:crimson"></p>
<form th:action="@{/login}">

3.我们提交表单,会经过shiro里的UserRealm,提交测试

请添加图片描述

4.在Userrealm中编写用户认证的判断逻辑

//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证逻辑AuthenticationToken");
        //用户名密码
        String name="root";
        String password="123456";

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //判断用户名
        if(!userToken.getUsername().equals(name)){
            return null; //抛出异常      UnknownAccountException
        }

        /*
            验证密码可以以使用一个AuthenticationInfo实现类SimpleAuthenticationInfo
            密码认证,shiro会自动帮我们验证!重点是第二个参数就是要验证的密码!

         */
        return new SimpleAuthenticationInfo("",password,"");


    }
3.5、用户授权操作

使用shiro的过滤器拦截请求

1.在ShiroFilterFactoryBean里添加一个过滤器

 	//授权过滤器
	 filterMap.put("/user/add","perms[user:add]");
	filterMap.put("/user/update","perms[user:update]");
		
    bean.setFilterChainDefinitionMap(filterMap);

2.添加一个未授权跳转页面

//未授权页面
    @RequestMapping("/noauth")
    @ResponseBody
    public String noAuth(){
        return "未经授权不能访问此页面";
    }

在ShiroFilterFactoryBean中设置跳转页面

 		//设置未授权页面
        bean.setUnauthorizedUrl("/noauth");

3.再次启动测试,访问/user/add,发现跳转到未授权页面注意:当我们实现权限拦截后,shiro会自动跳转到未授权的页面.

3.6、shiro授权
方式一:不推荐

在UserRealm的AuthorizationInfo中添加授权的逻辑,增加授权的字符串!

//执行授权逻辑
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection
principals) {
System.out.println("执行了=>授权逻辑PrincipalCollection");
//给资源进行授权
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//添加资源的授权字符串
info.addStringPermission("user:add");
return info;
}

我们再次登录测试,发现登录的用户是可以进行访问add 页面了!授权成功! 问题,我们现在完全是硬编码,无论是谁登录上来,都可以实现授权通过,但是真实的业务情况应该 是,每个用户拥有自己的一些权限,从而进行操作,所以说,权限,应该在用户的数据库中,正常的情 况下,应该数据库中是由一个权限表的,我们需要联表查询,但是这里为了大家操作理解方便一些,我 们直接在数据库表中增加一个字段来进行操作!

方式二:关联数据库中权限数据
  1. 修改实体类,增加一个字段
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
private String perms;
}
  1. 我们现在需要再自定义的授权认证中,获取登录的用户,从而实现动态认证授权操作!

    在用户登录授权的时候,将用户放在 Principal 中,改造下之前的代码

return new SimpleAuthenticationInfo(user, user.getPwd(), "");

​ 然后再授权的地方获得这个用户,从而获得它的权限

 //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权逻辑PrincipalCollection");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的用户对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到user对象

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

​ 3.我们给数据库中的用户增加一些权限
请添加图片描述

  1. 在过滤器中,将 update 请求也进行权限拦截下

    //授权过滤器
    filterMap.put("/user/add","perms[user:add]");
    filterMap.put("/user/update","perms[user:update]");
    

    5.启动项目测试,通过

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值