栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Springboot】整合Shiro实现登录拦截、用户认证、请求授权(thymeleaf、mybatis)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Springboot】整合Shiro实现登录拦截、用户认证、请求授权(thymeleaf、mybatis)

Shiro地址:https://shiro.apache.org/
参考:狂神说Java Springboot

简介

使用Springboot框架整合Shiro实现对用户的登录拦截、用户认证、请求授权等。

  1. 搭建项目:创建Springboot工程,添加依赖以及简单的前端页面。
  2. 基本配置:配置控制器实现路由,UserRealm继承AuthorizingRealm重写认证和授权方法(先写一个框架,后面完善),配置类ShiroConfig对shiro进行简单的配置(也是先写一个框架,后面完善)。
  3. 登录拦截:配置ShiroConfig类中的方法,设置访问权限,实现登录拦截。只有登陆后才能跳转到其他页面,否则请求将被拦截。
  4. 用户认证:登录拦截后将跳转到登录页面,输入正确的账号密码(暂时使用固定的账号密码)即可得到认证,访问其他页面。
  5. 整合Mybaits:完善上一步用户认证,从数据库中获取用户的账号密码进行认证登录。
  6. 请求授权:不同的用户有不同的权限,根据数据库中用户的权限为其授权,使其可以访问权限内的页面。
  7. 整合thymeleaf:完善前端页面,用户只能看到权限以内的东西(不该它看的内容看不到)。

文章目录
  • 一、搭建项目
    • 1.1 配置依赖
    • 1.2 前端页面
      • 1.2.1 首页index
      • 1.2.2 登录login
      • 1.2.3 其他
  • 二、基本配置
    • 2.1 MyController
    • 2.2 UserRealm
    • 2.3 ShiroConfig
  • 三、登录拦截
    • 3.1 修改ShiroConfig
    • 3.2 测试
  • 四、用户认证
    • 4.1 修改MyController
    • 4.2 修改UserRealm
    • 4.3 测试
  • 五、整合Mybatis完成用户认证
    • 5.1 创建数据库
    • 5.2 配置依赖
    • 5.3 配置文件
    • 5.4 实体类USer
    • 5.5 Mapper
    • 5.6 Service
    • 5.7 测试数据库
    • 5.8 修改UserRealm
    • 5.9 测试
  • 六、请求授权
    • 6.1 MyController
    • 6.2 修改ShiroConfig
    • 6.3 修改数据库和实体类
    • 6.4 修改UserRealm
    • 6.5 测试
  • 七、整合thymeleaf
    • 7.1 依赖
    • 7.2 修改shiroConfig
    • 7.3 修改index.html
    • 7.4 测试

一、搭建项目 1.1 配置依赖

选择Springboot项目进行搭建,并选择web和thymeleaf模板,将会自动导入spring-boot-starter-thymeleaf、spring-boot-starter-web和spring-boot-starter-test。

初始化项目后导入springboot与Shiro整合依赖shiro-spring。

pom.xml中的依赖如下:


    
    
        org.apache.shiro
        shiro-spring
        1.7.1
    
    
        org.springframework.boot
        spring-boot-starter-thymeleaf
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
    

1.2 前端页面

通过theamleaf获取数据和页面跳转。项目目录如下:

1.2.1 首页index

src/main/resources/templates/index.html




    
    Title


首页

add | update
1.2.2 登录login

src/main/resources/templates/login.html




    
    Title


登录


用户:

密码:

1.2.3 其他

其他页面均为空页面,只有一个与文件名相对应的p标签。

二、基本配置

首先搭建最基本的配置代码。

2.1 MyController

控制页面跳转

src/main/java/com/zqc/springbootshiro/controller/MyController.java

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {

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

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

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

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

src/main/java/com/zqc/springbootshiro/config/UserRealm.java

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

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;
    }
}
2.3 ShiroConfig

src/main/java/com/zqc/springbootshiro/config/ShiroConfig.java

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.linkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

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

    // DefaultWebSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    // 创建realm对象,需要自定义类
    @Bean(name = "userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }
}
三、登录拦截 3.1 修改ShiroConfig

修改src/main/java/com/zqc/springbootshiro/config/ShiroConfig.java中的getShiroFilterFactoryBean()方法实现登录拦截。

新建一个map用于存储配置信息,并通过bean.setFilterChainDefinitionMap(filterMap);进行设置。

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

    // 添加shiro的内置过滤器
    
    Map filterMap = new linkedHashMap<>();
    // user目录下的文件,必须要认证才能访问。
    filterMap.put("/user
        Map filterMap = new linkedHashMap<>();
        filterMap.put("/user/add", "perms[user:add]");
        filterMap.put("/user/update", "perms[user:update]");

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

        // 如果没有权限,设置登录的请求
        bean.setLoginUrl("/toLogin");

        // 未授权页面
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }

    // DefaultWebSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    // 创建realm对象,需要自定义类
    @Bean(name = "userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }
}

访问http://localhost:8080/,登陆后访问add页面:

6.3 修改数据库和实体类

增添perms字段(varchar(100)),设置每个用户的权限。后面通过查询数据库中用户的权限,对其权授权。

数据库中的数据:

同时修改User类,增添perms属性。

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private String perms;
}
6.4 修改UserRealm

修改doGetAuthenticationInfo()方法:

修改前:return new SimpleAuthenticationInfo("", user.getPwd(),"");
修改后:return new SimpleAuthenticationInfo(user, user.getPwd(),"");。

在认证的时候,将user对象存储进去,后面将拿出来使用。

修改doGetAuthorizationInfo()方法:

SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 拿到当前登录用户的对象
Subject subject = SecurityUtils.getSubject();
// 取出上面存储的user
User currentUser = (User) subject.getPrincipal(); 
// 设置当前用户的权限
info.addStringPermission(currentUser.getPerms());  

修改后的代码如下:

import com.zqc.springbootshiro.pojo.User;
import com.zqc.springbootshiro.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

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

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 拿到当前登录用户的对象
        Subject subject = SecurityUtils.getSubject();
        // 取出上面存储的user
        User currentUser = (User) subject.getPrincipal();
        // 设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        // 连接数据库
        User user = userService.queryUSerByName(userToken.getUsername());

        if (user==null) {
            // 没有这个人
            return null;// 抛出异常 UnknownAccountException
        }

        // 可以加密,MD5 MD5盐值加密
        // shiro密码认证,加密了。
        return new SimpleAuthenticationInfo(user, user.getPwd(),"");
    }
}
6.5 测试

同样,访问http://localhost:8080/,登陆后访问add或update页面。登录以下数据库中的账户。

zqc用户可访问add页面;root用户可访问update页面;其他用户无法访问任何页面。

七、整合thymeleaf 7.1 依赖

    com.github.theborakompanioni
    thymeleaf-extras-shiro
    2.0.0

7.2 修改shiroConfig

增加以下内容

// 整合ShiroDialect:用来整合shiro和thymeleaf
@Bean
public ShiroDialect getShiroDialect() {
    return new ShiroDialect();
}
7.3 修改index.html



    
    Title


首页


add
7.4 测试

此时会根据登录用户的权限来显示对应的a标签。

zqc可查看到add的访问标签;root可以查看到update的访问标签。


完结~~~!!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/346574.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号