shiro-spring

前言

Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。
使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,
从最小的移动应用程序到最大的网络和企业应用程序。

核心组件

三个核心组件:Subject, SecurityManager 和 Realms.
Subject:即“当前操作用户”Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。
SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,
当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。

10分钟入门

官网,我们还可以在github上面直接下载他们的源码。
创建一个简单quickstart Maven项目。
pom文件
我们从github上面的pom拷贝过来

<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>1.7.1</version>
    </dependency>

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

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

log4j

# 
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
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 

Quickstart

package org.example;

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) {
        //创建具有配置的领域,用户,角色和权限的Shiro SecurityManager的最简单方法是使用简单的INI配置。
        //我们将通过使用可以提取.ini文件并返回SecurityManager实例的工厂来做到这一点:
        //在类路径的根目录下使用shiro.ini文件 ,使用工厂生成一个securityManager实例,将提前定义好的shiro.ini文件内容加载进去
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        // 对于这个简单的示例快速入门,使SecurityManager作为JVM单例进行访问。大多数应用程序不这样做,而是依靠其容器配置或web.xml来
        // webapps。这超出了此简单快速入门的范围,因此我们将只做最少的工作,以便您可以继续对事物有所了解。
        SecurityUtils.setSecurityManager(securityManager);


        //获取当前用户对象, 1.这里的currentUser对象说白了就是一个用户容器,可以用来载入前端输入的真实用户信息
        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 + "]");
        }

        // 判断当前用户是否被认证,
        // 2.这时currentUser还没有载入用户信息,执行isAuthenticated()实现与之前ini定义好的内容进行检索比较,肯定匹配不成功
        if (!currentUser.isAuthenticated()) {
            //Token:令牌  3.把输入的真实用户信息封装到token对象中
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true); //记住我
            try {
                // 4.把token注入currentUser对象的.login()方法中执行登录操作,这里的.login(XXX)方法会将token中的用户信息          // 和shiro.ini定义的用户信息进行匹配,若匹配成功则登录成功,且currentUser也会成为一个真正意义上的用户对象,而不是一个空的用户容器,          // 若匹配失败,则会catch 以下种类的异常信息
                currentUser.login(token); //执行登录操作
            } catch (UnknownAccountException uae) { //4.1 用户名不存在的异常
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) { //4.2 密码不对的异常
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) { //4.3 用户被锁定的异常
                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:
        //打印用户相关信息
        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.");
        }

        //测试用户是否具备某一个行为权限,调用subject的isPermitted()方法(不是实例级别)
        //粗粒度
        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.");
        }

        //(非常强大的)实例级别权限:
        //细粒度
        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();
    }}

Shiro

这个小demo是springboot+shiro+mybatis+thymeleaf
pom


<!--        导入shiro整合springboot 当用这个启动器的时候必须有Realm相关类 可以先使用下面的shiro-spring类-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-starter</artifactId>
            <version>1.7.1</version>
        </dependency>
        <!--        <dependency>-->
        <!--            <groupId>org.apache.shiro</groupId>-->
        <!--            <artifactId>shiro-spring</artifactId>-->
        <!--            <version>1.7.1</version>-->
        <!--        </dependency>-->

        <!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<!--        shiro整合thymeleaf-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>   
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
<!--        druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

applicaton.yml

#我们在首次登录的时候 url中jsessionid jsessionid是存储在cookie中的
#如果客户端禁用cookie 就要重写url显示将jsessionid重写到url中
#所以我们要打开cookie
server:
  servlet:
    session:
      tracking-modes: cookie
      cookie:
        http-only: true
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/aw?useUicode=true&characterEncoding=utf-8&serverTimezone=UTC
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      filters: stat
      #最大连接池数量
      max-active: 200
      #初始化时建立物理连接的个数
      initial-size: 10
      #获取连接时最大等待时间,单位毫秒
      max-wait: 60000
      #最小连接池数量
      min-idle: 10
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: select 1
      #validation-query: select 1 from dual
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      #是否缓存preparedStatement
      pool-prepared-statements: true
      #要启用PSCache,必须配置大于0
      max-open-prepared-statements: 200
      break-after-acquire-failure: true
      time-between-connect-error-millis: 300000

mybatis:
  type-aliases-package: com.aw.springshiro.model
  mapper-locations: classpath:/mapper/*.xml

核心配置类
Realm类他是继承AuthorizingRealm,重写他的授权、认证方法。

package com.aw.springshiro.config;

import com.aw.springshiro.model.User;
import com.aw.springshiro.service.UserService;
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
    private UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //设置授权信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //获取认证成功传递过来的对象
        Subject subject = SecurityUtils.getSubject();
        //获取当前用户信息
        User currentUser = (User) subject.getPrincipal();
        //从数据库中获取用户的权限 添加权限用户信息
        authorizationInfo.addStringPermission(currentUser.getPerm());
        return authorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //前端传过来的
       UsernamePasswordToken token =(UsernamePasswordToken)authenticationToken;
       //通过用户名从数据库中查找用户
        User user = userService.getUser(token.getUsername());
        if (user==null){
            return null;
        }
        // SimpleAuthenticationInfo 用来密码认证的
        // 这里的第一个参数是传递用户是为了我们在授权的时候能够拿到用户的信息
        //认证完进入授权检验
       return new SimpleAuthenticationInfo(user,token.getPassword(),"");
    }
}

Shiro配置

@Configuration
public class ShiroConfig {
		
	//拦截过滤  @Qualifier()此注解是指定从spring规定好的方法名字 我们可以在    @Bean(name = "securityManager")设置他的名字
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
       //设置安全管理器
        factoryBean.setSecurityManager(defaultSecurityManager);
        //添加Shiro内置过滤器
        /**
         * anon:无需认证就能访问
         * authc:必须认证了才能访问
         * user:必须有记住我
         * perms:拥有对某个权限才能访问
         *role:拥有某个角色才能访问
         */
        LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<>();
        //设置用户权限
        linkedHashMap.put("/user/add","perms[user:add]");
        linkedHashMap.put("/user/update","perms[user:update]");
        //设置用户的认证 拦截user下的所有用户
        linkedHashMap.put("/user/*","authc");

        factoryBean.setFilterChainDefinitionMap(linkedHashMap);
        //设置登录认证界面
        factoryBean.setLoginUrl("/toLogin");
        //设置为授权跳转的界面
        factoryBean.setUnauthorizedUrl("/Unauthorized");

      return factoryBean;
    }
	//安全管理
    @Bean(name = "securityManager")
    public DefaultSecurityManager defaultSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//        关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
	//spring接管创建Realm
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
}

controller层
核心代码是上面的配置类。下面的代码就是相应的springboot

package com.aw.springshiro.controller;

import com.aw.springshiro.config.UserRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

@Controller
public class MyController {

    @RequestMapping({"/", "/index"})
    String test(Model model) {
        model.addAttribute("name", "aw");
        return "index";
    }

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

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

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

    @RequestMapping("/login")
    public String login(String username, String password,Model model) {
        //获取主题
        Subject subject = SecurityUtils.getSubject();
        //将前端传递过来的用户名和密码做成令牌token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            //走到Reaml中的进行认证
            subject.login(token);
            model.addAttribute("username",username);
            return "index";
        } catch (UnknownAccountException uae) { //4.1 用户名不存在的异常
                model.addAttribute("msg","用户名不正确");
        } catch (IncorrectCredentialsException ice){
            model.addAttribute("msg","密码不正确");
        }
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
    @RequestMapping("/Unauthorized")
    public String Unauthorized(){
        return "/user/Unauthorized";
    }
}


service层

package com.aw.springshiro.service;

import com.aw.springshiro.mapper.UserMapper;
import com.aw.springshiro.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    public  User getUser(String username){
        User user = userMapper.getByUsername(username);
        return user;
    }
}

mapper

@Repository
public interface UserMapper {
    User getByUsername(@PathParam("username") String username);
}

mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aw.springshiro.mapper.UserMapper">
    <select id="getByUsername" parameterType="java.lang.String" resultType="com.aw.springshiro.model.User">
        select * from student where name=#{username}
    </select>
</mapper>

model层

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String name;
    private String age;
    private String sex;
    private Integer score;
    private String perm;
}

index.html
这里使用shiro:hasPermission="user:update"报错,就没有添加相应的权限显示

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

    <a th:href="@{/login}">登录</a>
<div >
    <a th:href="@{/logout}">退出</a>
</div>
    <a th:href="@{/user/add}" >add</a>
    <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>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}" method="post">
  用户名:<input type="text" name="username"> <br>
  密码:<input type="password" name="password"> <br>
  <button type="submit">登录</button>
</form>
</body>
</html>

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>添加用户</h1>
</body>
</html>

update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>修改用户</h1>
</body>
</html>

Unauthorized.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>此用户没有授权</h1>
</body>
</html>

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值