Shiro(登录拦截,登录认证,请求授权,和Thymeleaf整合)

前言:Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
这个类对于我们理解Shiro很重要,他是官方提供的一个快速入门Shiro的例子。完整代码https://github.com/apache/shiro/tree/master/samples/quickstart

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
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) {
        //获取
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
        securityManager.setRealm(iniRealm);
        SecurityUtils.setSecurityManager(securityManager);

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

        //通过当前用户拿到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 + "]");
        }

        // 判断当前的用户是否被认证
        if (!currentUser.isAuthenticated()) {//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?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        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.");
        }

        //测试是否有更高级的权限
        //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!");
        }

        //注销
        currentUser.logout();

        System.exit(0);
    }
}
1、整合SpringBoot进行环境搭建

导入依赖

<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-starter</artifactId>
            <version>1.5.3</version>
</dependency>

自定义的UserRealm

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

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

编写ShiroConfig类

@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //关联安全管理器
        factoryBean.setSecurityManager(securityManager);
        return factoryBean;
    }

    //DefaultWebSecurityManager
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

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

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}"></h1><hr>
<a th:href="@{/user/add}">add</a><hr>
<a th:href="@{/user/update}">update</a>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<from th:action="@{/login}">
    用户名:<input type="text" name="username"><hr>
    密码:<input type="password" name="password"><hr>
    <input type="submit" value="提交">
</from>
</body>
</html>

add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>

update.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>

MyController

package com.example.Controller;
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 index(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、登录拦截实现
 /*
        * anon:无需认证乐意访问
        * authc:认证后才能访问
        * user:必须拥有记住我功能才能使用
        * perms:拥有对某个资源的权限才能访问
        * role:拥有某个角色权限才能访问
        * */
@Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
       factoryBean.setSecurityManager(securityManager);
        //添加shiro的内置过滤器
       HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("/user/*","authc");
        factoryBean.setFilterChainDefinitionMap(hashMap);
        //设置登录的请求
        factoryBean.setLoginUrl("/toLogin");
        return factoryBean;
    }
3、登录认证

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";//登录成功返回首页
        } catch (UnknownAccountException e) {//用户名不存在
           model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){//密码不存在
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

自定义的UserRealm

//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");
        //用户名密码 从数据库获取
        String username="root";
        String password="123456";
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        if(!token.getUsername().equals(username)){
            return null;//抛出UnknownAccountException异常
        }
        //密码认证
        return new SimpleAuthenticationInfo("",password,"");
    }

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: red"></p><hr>
<form th:action="@{/login}">
    用户名:<input type="text" name="username"><hr>
    密码:<input type="password" name="password"><hr>
    <input type="submit" value="提交">
</form>
</body>
</html>
4、整合mybatis

导入依赖

       <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

yml配置

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mydeno?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
mybatis:
  type-aliases-package: com.example.Pojo
  mapper-locations: classpath:mapper/*.xml

自定义的UserRealm

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

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");
        //用户名密码 从数据库获取
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.QueryByName(token.getUsername());
        if(user==null){
            return null;//抛出UnknownAccountException异常
        }
        //密码认证 加密
        return new SimpleAuthenticationInfo("",user.getPassword(),"");
    }
5、请求授权

数据库表,admin只能访问add页面,root只能访问update页面。
在这里插入图片描述
ShiroConfig代码

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

        //添加shiro的内置过滤器
        /*
        * anon:无需认证乐意访问
        * authc:认证后才能访问
        * user:必须拥有记住我功能才能使用
        * perms:拥有对某个资源的权限才能访问
        * role:拥有某个角色权限才能访问
        * */

        LinkedHashMap<String, String> hashMap = new LinkedHashMap<>();

        //设置权限,有权限才能访问那个页面
        // 没有授权会跳转到未授权页面
        hashMap.put("/user/add","perms[user:add]");
        hashMap.put("/user/update","perms[user:update]");
        /*登录拦截*/
        hashMap.put("/user/*","authc");

        factoryBean.setFilterChainDefinitionMap(hashMap);

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

        //未授权页面
        factoryBean.setUnauthorizedUrl("/Unauth");
        return factoryBean;
    }

授权代码

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

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给用户授予某种权限 权限应从数据库中获取
        //获取当前登录的用户对象
        Subject subject = SecurityUtils.getSubject();
        User principal = (User) subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission(principal.getPerms());
        return info;
    }

没有权限时的处理

 @RequestMapping("/Unauth")
    @ResponseBody
    public String Unauthorized(){
        return "未经授权,无法访问";
    }
6、Shiro整合Thymeleaf

和Thymeleaf整合,实现当用户登录时,根据用户权限的不同,动态显示菜单。
导入依赖

<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>

引入命名空间

xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"

登录成功将用户名保存在session中

 //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");
        //用户名密码 从数据库获取
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.QueryByName(token.getUsername());

        if(user==null){
            return null;//抛出UnknownAccountException异常
        }
        Subject subject1 = SecurityUtils.getSubject();
        Session session = subject1.getSession();
        session.setAttribute("loginUser",user);
        //密码认证 加密
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");

    }

index.html

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

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}"></h1><hr>
<div th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登录</a><hr>
</div>
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">add</a><hr>
</div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">update</a>
</div>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值