Shiro入门

2 篇文章 0 订阅

Shiro入门

三大核心对象

subject———-用户

SecurityManager———- 管理所有用户

Realm————-连接数据

shiro 快速开始

1、导入依赖

<dependencies>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.8.0</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>

2、配置文件

#
# 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

#
# 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.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================
# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[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

3、HelloWorld

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) {
        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);
        // 获取当前的用户对象
        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);
    }
}

shiro核心方法

// 获取当前的用户对象
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核心的SecurityUtils.getSubject(); 可以拿到当前用户 session等

1、导入依赖

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

2、创建pojo

package com.wen.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
 * @Author WangEn
 * @CreateTime: 2021-12-23-15-32
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private String perms;
}

3、mapper接口

package com.wen.mapper;
import com.wen.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
 * @Author WangEn
 * @CreateTime: 2021-12-23-15-38
 */
@Repository
@Mapper
public interface UserMapper {
    User queryByName(@Param("name") String name);
}

4、service和serviceImpl

package com.wen.service;
import com.wen.pojo.User;
/**
 * @Author WangEn
 * @CreateTime: 2021-12-23-15-44
 */
public interface UserService {
    User queryByName(String name);
}

package com.wen.service.impl;
import com.wen.mapper.UserMapper;
import com.wen.pojo.User;
import com.wen.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @Author WangEn
 * @CreateTime: 2021-12-23-15-44
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User queryByName(String name) {
        return userMapper.queryByName(name);
    }
}

5、搭建环境controller

package com.wen.controller;
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 org.springframework.web.bind.annotation.ResponseBody;
/**
 * @Author WangEn
 * @CreateTime: 2021-12-22-17-28
 */
@Controller
public class IndexController {
    @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 login(){
        return "login";
    }
    @RequestMapping("/noAuth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无权访问";
    }
}

6、前端templates下 gitee shiro仓库

shiro实现登录拦截

@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    // 设置安全管理器
    bean.setSecurityManager(securityManager);
    // 添加shiro的内置过滤器
    /**
         * anon:无需认证  就能  访问
         * authc:必须认证  才能  访问
         * user:必须有  记住我  才能  访问
         * perms:拥有对某个资源的权限才能访问
         * role:拥有某个角色  才能  访问
         */
    Map<String, String> map = new LinkedHashMap<>();
    bean.setLoginUrl("/toLogin");  // 设置登录页面
    return bean;
}

shiro实现用户认证

// ShiroFilterFactoryBean      3    倒叙编写  会发现  上调用下
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    // 设置安全管理器
    bean.setSecurityManager(securityManager);
    // 添加shiro的内置过滤器
    /**
         * anon:无需认证  就能  访问
         * authc:必须认证  才能  访问
         * user:必须有  记住我  才能  访问
         * perms:拥有对某个资源的权限才能访问
         * role:拥有某个角色  才能  访问
         */
    Map<String, String> map = new LinkedHashMap<>();
    //map.put("user/add","authc");  // 必须认证才能访问
    //map.put("user/update","authc");
    map.put("/user/add","perms[user:add]");  //  perms:拥有add的权限才能访问
    map.put("/user/update","perms[user:update]");  //  perms:拥有add的权限才能访问
    map.put("/user/*","authc");     /* key  为路径  要在路径前面 + / 才能找到 */
    bean.setFilterChainDefinitionMap(map);
    bean.setLoginUrl("/toLogin");  // 设置登录页面
    bean.setUnauthorizedUrl("/noAuth");  // 没有授权跳转的路径
    return bean;
}

shiro整合mybaits

1、导入依赖

<!--mybait-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<!--数据库驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>

2、配置properties yml文件

spring.thymeleaf.cache=false
# 别名
mybatis.type-aliases-package=com.wen.pojo
# 指定mapper映射文件
mybatis.mapper-locations=classpath:mapper/*.xml
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis?useSSL=true&characterEncoding=utf-8&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
    #则导入log4j 依赖就行
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionoProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3、在resources下创建mapper文件夹、创建mapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mapper.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wen.mapper.UserMapper">
    <select id="queryByName" parameterType="String" resultType="User">
        select * from tb_user where name = #{name};
    </select>
</mapper>

shiro请求授权实现

1、在自定义Realm类中 重写 了 授权 和认证方法

在这里进行授权实现

 @Override  // 授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了==>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 通过认证return  传递的  参数   通过工具类拿到  传递的参数
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        // 设置用户权限            从数据库中  查出来的
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

2、开始认证

@Override // 认证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    System.out.println("执行了==>认证doGetAuthenticationInfo");
    /*        String userName = "root";  // 假数据
        String password = "12345";*/
    Subject subject = SecurityUtils.getSubject();
    // 强转 token
    UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
    User user = userService.queryByName(userToken.getUsername());
    Session session = subject.getSession();
    session.setAttribute("loginUser",user);
    if (user == null) {  // 用户为空  就是  UnknownAccountException
        return null;
    }
    /*if (!userToken.getUsername().equals(userName)){
            return null;
        }*/
    // 密码认证,shiro自动做~  通过shiro底层  调用自定义用户类 和 配置类 组合认证
    //return new SimpleAuthenticationInfo("",password,"");
    //return new SimpleAuthenticationInfo("",user.getPwd(),"");
    return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}

shiro整合thymeleaf

1、导入依赖

<!--shiro整合thymeleaf-->
<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.1.0</version>
</dependency>

2、前端引入头文件

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

3、后端配置thymeleaf对象 在自定义Realm中写 extends AuthorizingRealm

// shiroDialect:整个shiro和thymeleaf
@Bean
public ShiroDialect dialect(){
    return new ShiroDialect();
}

4、前端写html

<p th:text="${msg}"></p>
<div th:if="${#strings.isEmpty(session.loginUser)}">
    <a th:href="@{/toLogin}">登录</a>
</div>
<div shiro:hasPermission="user:add">
    <a th:href="@{user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
    <a th:href="@{user/update}">update</a>
</div>

shiro总结

shiro核心:subject对象、securityManager、Realm对象

通过自定义UserRealm来extends AuthorizingRealm这个类,重写 授权 认证方法 那么这个类就是自定义类

然后配置shiroconfig类,通过倒叙三部曲需要自定义 类 1 DefaultWebSecurityManager 2 ShiroFilterFactoryBean 3 倒叙编写 会发现 上调用下 两个类通过底层相互结合,来达到shiro安全控制

1、自定义UserRealm

package com.wen.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.wen.pojo.User;
import com.wen.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.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
/**
 * @Author WangEn
 * @CreateTime: 2021-12-22-17-31
 */
// 自定义的  UserRealm    Authorizing :授权  extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm{
    @Autowired
    UserService userService;
    @Override  // 授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了==>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 通过认证return  传递的  参数   通过工具类拿到  传递的参数
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        // 设置用户权限            从数据库中  查出来的
        info.addStringPermission(currentUser.getPerms());
        return info;
    }
    @Override // 认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了==>认证doGetAuthenticationInfo");
/*        String userName = "root";  // 假数据
        String password = "12345";*/
        Subject subject = SecurityUtils.getSubject();
        // 强转 token
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        User user = userService.queryByName(userToken.getUsername());
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);
        if (user == null) {  // 用户为空  就是  UnknownAccountException
            return null;
        }
        /*if (!userToken.getUsername().equals(userName)){
            return null;
        }*/
        // 密码认证,shiro自动做~  通过shiro底层  调用自定义用户类 和 配置类 组合认证
        //return new SimpleAuthenticationInfo("",password,"");
        //return new SimpleAuthenticationInfo("",user.getPwd(),"");
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
    // shiroDialect:整个shiro和thymeleaf
    @Bean
    public ShiroDialect dialect(){
        return new ShiroDialect();
    }
}

2、shiroConfig配置类

package com.wen.config;
import org.apache.shiro.realm.AuthorizingRealm;
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.LinkedHashMap;
import java.util.Map;
/**
 * @Author WangEn
 * @CreateTime: 2021-12-22-17-30
 */
@Configuration
public class ShiroConfig {
    // ShiroFilterFactoryBean      3    倒叙编写  会发现  上调用下
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        bean.setSecurityManager(securityManager);
        // 添加shiro的内置过滤器
        /**
         * anon:无需认证  就能  访问
         * authc:必须认证  才能  访问
         * user:必须有  记住我  才能  访问
         * perms:拥有对某个资源的权限才能访问
         * role:拥有某个角色  才能  访问
         */
        Map<String, String> map = new LinkedHashMap<>();
        //map.put("user/add","authc");  // 必须认证才能访问
        //map.put("user/update","authc");
        map.put("/user/add","perms[user:add]");  //  perms:拥有add的权限才能访问
        map.put("/user/update","perms[user:update]");  //  perms:拥有add的权限才能访问
        map.put("/user/*","authc");     /* key  为路径  要在路径前面 + / 才能找到 */
        bean.setFilterChainDefinitionMap(map);
        bean.setLoginUrl("/toLogin");  // 设置登录页面
        bean.setUnauthorizedUrl("/noAuth");  // 没有授权跳转的路径
        return bean;
    }
    // DefaultWebSecurityManager   2
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager securityManager(@Qualifier("userRealm")AuthorizingRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联自定义的Realm对象
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    // 常见Realm对象,需要自定义 类  1
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
}

………

其余代码在gitee shiro仓库https://gitee.com/w-en/dashboard/projects?sort=&scope=&state=private

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值