主頁 > 後端開發 > 3萬字《SpringBoot微服務開發——Shiro(安全)》

3萬字《SpringBoot微服務開發——Shiro(安全)》

2021-10-15 22:10:31 後端開發

SpringBoot微服務開發——Shiro(安全)

文章目錄

  • SpringBoot微服務開發——Shiro(安全)
    • Shiro(安全)
      • 1、Shiro簡介
      • 2、Shiro有哪些功能?
      • 3、Shiro架構(外部)
      • 4、Shiro架構(內部)
      • 5、進入實踐
        • 1、匯入依賴
        • 2、組態檔
        • 3、測驗Quickstart
      • 6、SpringBoot整合Shiro環境搭建
      • 7、shiro實作登錄攔截
      • 8、Shiro實作用戶認證
      • 9、Shiro整合Mybatis
      • 10、Shiro請求授權實作
        • 1、授權正常的情況下,沒有授權會跳轉到未授權頁面
        • 2、授予可以訪問的權限
        • 3、一般在資料庫里添加權限的欄位,修改資料庫,和物體類

Shiro(安全)

1、Shiro簡介

? Apache Shiro是一個強大且易用的Java安全框架,執行身份驗證、授權、密碼和會話管理,使用Shiro的易于理解的API,您可以快速、輕松地獲得任何應用程式,從最小的移動應用程式到最大的網路和企業應用程式,

Shiro可以非常容易的開發出足夠好的應用,不僅可以用在JavaSE環境,也可以用在JavaEE環境,

下載地址: http://shiro.apache.org/

2、Shiro有哪些功能?

img

  1. Authentication: 身份認證、登錄,驗證用戶是不是擁有相應的身份;
  2. Authorization:授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限,即判斷用戶能否進行什么操
  3. 作,如:驗證某個用戶是否擁有某個角色,或者細粒度的驗證某個用戶對某個資源是否具有某個權限!
  4. Session Manager:會話管理,即用戶登錄后就是第一次會話,在沒有退出之前,它的所有資訊都在會話中;
  5. 會話可以是普通的avaSE環境,也可以是Web環境;
  6. Cnyptography: 加密,保護資料的安全性,如密碼加密存盤到資料庫中,而不是明文存盤;
  7. Web Support: Web支持,可以非常容易的集成到Web環境;
  8. Caching: 快取,比如用戶登錄后,其用戶資訊,擁有的角色、權限不必每次去查,這樣可以提高效率
  9. Concurrency: Shiro支持多執行緒應用的并發驗證,即,如在一個執行緒中開啟另一 個執行緒,能把權限自動的傳
    播過去
  10. Testing:提供測驗支持;
  11. Run As: 允許一 個用戶假裝為另- -個用戶(如果他們允許)的身份進行訪問;
  12. Remember Me:記住我,這個是非常常見的功能,即一次登錄后,下次再來的話不用登錄了

3、Shiro架構(外部)

img

  1. subject: 應用代碼直接互動的物件是Subject, 也就是說Shiro的對外API核心就是Subject, Subject代表了當
    前的用戶,這個用戶不-定是一個具體的人, 與當前應用互動的任何東西都是Subject,如網路爬蟲,機器人
    等,與Subject的所有互動都會委托給SecurityManager; Subject其實是一 個門面, SecurityManageer 才是
    實際的執行者
  2. SecurityManager: 安全管理器,即所有與安全有關的操作都會與SercurityManager互動,并且它管理著所有
    的Subject,可以看出它是Shiro的核心,它負責與Shiro的其他組件進行互動,它相當于SpringMVC的
    DispatcherServlet的角色
  3. Realm: Shiro從Realm獲取安全資料 (如用戶,色,權限),就是說SecurityManager 要驗證用戶身份,
    那么它需要從Realm獲取相應的用戶進行比較,來確定用戶的身份是否合法;也需要從Realm得到用戶相應的
    角色、權限,進行驗證用戶的操作是否能夠進行,可以把Realm看成DataSource;

4、Shiro架構(內部)

img

  1. Subject: 任何可以與應用互動的"用戶;3
  2. Security Manager:相當于SpringMVC中的DispatcherServlet;是Shiro的心臟,所有具體的互動都通過
  3. Security Manager進行控制,它管理者所有的Subject,且負責進行認證,授權,會話,及快取的管理,
  4. Authenticator: 負責Subject認證,是一一個擴 展點,可以自定義實作;可以使用認證策略(AuthenticationStrategy),即什么情況下算用戶認證通過了;
  5. Authorizer:授權器,即訪問控制器,用來決定主體是否有權限進行相應的操作;即控制著用戶能訪問應用中
    的那些功能;
  6. Realm: 可以有一個或者多個的realm,可以認為是安全物體資料源,即用于獲取安全物體的,可以用DBC實
    現,也可以是記憶體實作等等,由用戶提供;所以- -般在應用中都需要實作自己的realm
  7. SessionManager: 管理Session生命周期的組件,而Shiro并不僅僅可以用在Web環境,也可以用在普通的
    JavaSE環境中
  8. CacheManager: 快取控制器,來管理如用戶,角色,權限等快取的;因為這些資料基本上很少改變,放到緩
    存中后可以提高訪問的性能;
  9. Cryptography:密碼模塊, Shiro 提高了一些常見的加密組件用于密碼加密, 解密等

5、進入實踐

打開官網檔案: http://shiro.apache.org//tutorial.html

  1. 創建一個普通的maven父工程
  2. 創建一個普通的Maven子工程: shiro-01-helloworld
  3. 根據官方檔案,我們來匯入Shiro的依賴

1、匯入依賴

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
    <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>
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.14.1</version>
    </dependency>

</dependencies>

2、組態檔

resources目錄下

log4j.properties

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

shiro.ini,需要安裝ini插件

img

[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、測驗Quickstart

/*
 * 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.
 */

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) {

        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):

        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);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
        //獲取當前的用戶物件  Subject
        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");
        //將aValue的session保存在someKey中
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Subject==》session [" + 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);
    }
}

img

這些功能在Spring-Secutiry都有

//獲取當前的用戶物件  Subject
Subject currentUser = SecurityUtils.getSubject();

    //通過當前物件獲取當前用戶的Session
   Session session = currentUser.getSession();
   
   //判斷當前的用戶是否被認證
   currentUser.isAuthenticated()
   
	//獲取當前用戶資訊
   currentUser.getPrincipal()
   
     //測驗角色  判斷當前用戶是什么角色
   currentUser.hasRole("schwartz")
   
   currentUser.isPermitted("lightsaber:wield")
   
     //注銷
currentUser.logout();

6、SpringBoot整合Shiro環境搭建

匯入相關依賴

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


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

        <!--thymeleaf模板,我們都是基于3.x開發-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

測驗SpringBoot環境是否搭建成功

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首頁</h1>
<p th:text="${msg}"></p>
<hr>

<a th:href="@{/user/add}">add</a>

<a th:href="@{/user/update}">update</a>
</body>
</html>

controller層

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

img

測驗SpringBoot整合Shiro環境搭建成功

Shiro配置

img

package com.kk.config;


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;

//自定義的 UserRealm         extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("執行科=》授權doGetAuthorizationInfo");
        return null;
    }


    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("執行科=》認證doGetAuthenticationInfo");
        return null;
    }
}

ShiroConfig

package com.kk.config;

import org.apache.shiro.mgt.DefaultSecurityManager;
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 {


    //ShiroFilterFactortBean  第三步
    @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
    public UserRealm userRealm() {
        return new UserRealm();
    }





}

MyController

package com.kk.controller;

import org.springframework.jmx.export.annotation.ManagedResource;
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";
    }



}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首頁</h1>
<p th:text="${msg}"></p>
<hr>

<a th:href="@{/user/add}">add</a>

<a th:href="@{/user/update}">update</a>
</body>
</html>

add.html

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

update.html

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

7、shiro實作登錄攔截

package com.kk.config;

import org.apache.shiro.mgt.DefaultSecurityManager;
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 {


    //ShiroFilterFactortBean  第三步
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //設定安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro的內置過濾器
        /*
        anon : 無需認證就可以訪問
       authc:必須認證才能訪問
       user:必須擁有 記住我 功能才能用
       perms 擁有某個資源的權限才能訪問
       role 擁有某個角色的權限才能訪問
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add", "authc");
        filterMap.put("/user/update", "authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //如果沒有權限 ,則跳轉到登陸頁面
        bean.setLoginUrl("/toLogin");

        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
    public UserRealm userRealm() {
        return new UserRealm();
    }


}

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登陸</h1>
<hr>
<form action="">
  <p>用戶名:<input type="text" name="username"></p>
  <p>密碼:<input type="text" name="password"></p>
  <p><input type="submit"></p>



</form>
</body>
</html>

MyController

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

8、Shiro實作用戶認證

MyController

@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";
    }

}

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登陸</h1>
<hr>
<p th:text="${msg}" style="color: red;"></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>

UserRealm

//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    System.out.println("執行了=》認證doGetAuthenticationInfo");

    //用戶名 密碼 ---資料庫
    String name="root";
    String password="123456";

    UsernamePasswordToken userToken = (UsernamePasswordToken) token;

    if (!userToken.getUsername().equals(name)){
        return null;//拋出例外UnknownAccountException

    }

    //密碼認證  shiro
    return new SimpleAuthenticationInfo("",password,"");

}

9、Shiro整合Mybatis

匯入依賴

<!--        連接資料庫-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
<!--        引入mybatis-springboot-->

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

2.連接資料庫application.yml

spring:
  datasource:
    username: root
    password: 981204
    #?serverTimezone=UTC解決時區的報錯
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默認是不注入這些屬性值的,需要自己系結
    #druid 資料源專有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置監控統計攔截的filters,stat:監控統計、log4j:日志記錄、wall:防御sql注入
    #如果允許時報錯  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #則匯入 log4j 依賴即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3.設定application.properties

# 整合mybatis
mybatis.type-aliases-package=com.kk.pojo
mybatis.mapper-locations=classpath:mapper/*.xml

4.物體類

package com.kk.pojo;

public class User {

    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

5.UserMapper

package com.kk.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public class UserMapper {

    public User queryUserByName(String name);
}

6.UserMapper.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.kk.mapper.UserMapper">
    <select id="queryUserByName" resultType="User">
        select * from mybatis.user where name = #{name}
    </select>

</mapper>

7.UserService

public interface UserService {
    public User queryUserByName(String name);
}

8.UserServiceImpl

package com.kk.service;

import org.springframework.stereotype.Service;

@Service
public class UserServiceImp implements UserService{
    @Autowired
    UserMapper userMapper;
    
    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

9.測驗查出對應User

@SpringBootTest
class ShiroSpringbootApplicationTests {
@Autowired
    UserServiceImpl userService;
    @Test
    void contextLoads() {
        System.out.println(userService.queryUserByName("雛田"));
    }
}

10、測驗成功后 將資料系結到安全配置中,再次啟動配置

package com.kk.config;


import com.kk.pojo.User;
import com.kk.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
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;

//自定義的 UserRealm         extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("執行了=》授權doGetAuthorizationInfo");
        return null;
    }


    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("執行了=》認證doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;


        //連接真實資料庫
        User user = userService.queryUserByName(userToken.getUsername());


     if (user==null){ //沒有這個用戶
         return null; //拋出例外UnknownAccountException

     }

        //密碼認證  shiro
        //可以加密 MD5加密 MD5鹽值加密
        return new SimpleAuthenticationInfo("",user.getPwd(),"");

    }
}

10、Shiro請求授權實作

1、授權正常的情況下,沒有授權會跳轉到未授權頁面

package com.kk.config;

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;

@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean:3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //設定安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        /*anon:無需認 證就可以訪問
        authc:必須認證了 才能讓問
        user:.必須擁有 記住我功能才能用
        perms:
        擁有對某個資源的權限才能訪間:
        role:擁有某 個角色權限才能訪問
        */
        Map<String, String> filterMap = new LinkedHashMap<>();

        //授權,正常的情況下,沒有授權會跳轉到未授權頁面
        filterMap.put("/user/add", "perms[user:add]");
        filterMap.put("/user/update", "perms[user:update]");
        //第二個為權限,只有persm=user:add/user:update] 才可能進入相應的頁面

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

        //設定獲錄的請求
        bean.setLoginUrl("/toLogin");
        //未授權頁面
        bean. setUnauthorizedUrl("/noauth");


        return bean;

    }




    //Dafaul tWebSecurityManager:2
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultwebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //關聯UserReaLm
        securityManager.setRealm(userRealm);
        return securityManager;
    }



    //創建UserRealm物件,需要自定義類:1
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }
}

controller

@RequestMapping("/noauth")
@ResponseBody
public String unauthorized() {
    return "未經授權無法訪問此頁面";
}

2、授予可以訪問的權限

package com.kk.config;

import com.kk.pojo.User;
import com.kk.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
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("執行了=》授權doGetAuthorizationInfo");
        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");
     
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("執行了=》驗證doGetAuthorizationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //連接真實的資料庫
        User user = userService.queryUserByName(userToken.getUsername());
        if (user == null) { //沒有這個用戶
            return null; //UnknownAccountException
        }
        //可以加密: MD5: e10adc3949ba59abbe56e057f20f883e MD5 鹽值加密: e10adc3949ba59abbe56e057f20f883eusername
        //密碼認證, shiro 做~
        return new SimpleAuthenticationInfo("", user.getPwd(), "");


    }
}

3、一般在資料庫里添加權限的欄位,修改資料庫,和物體類

img

物體類

private int id;
    private String name;
    private String pwd;
    private String perms;

UserRealm實作授權的分配

package com.kk.config;

import com.kk.pojo.User;
import com.kk.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
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("執行了=》授權doGetAuthorizationInfo");
        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");
        //拿到當登錄 的這個物件
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal(); //拿到User物件
        //設定當前用戶的權限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("執行了=》驗證doGetAuthorizationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //連接真實的資料庫
        User user = userService.queryUserByName(userToken.getUsername());
        if (user == null) { //沒有這個用戶
            return null; //UnknownAccountException
        }
        //可以加密: MD5: e10adc3949ba59abbe56e057f20f883e MD5 鹽值加密: e10adc3949ba59abbe56e057f20f883eusername
        //密碼認證, shiro 做~
        return new SimpleAuthenticationInfo(user, user.getPwd(), "");


    }
}

3.使用shirothymeleaf

在html頁面中匯入

xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro
<!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>首頁</h1>
<p>
    <a th:href="@{/toLogin}">登錄</a>
</p>
<p th:text="${msg}"></p>
<hr>
<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>

</body>
</html>

4.測驗

img

存在登錄按鈕的問題

UserRealm中添加session

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("執行了=》驗證doGetAuthorizationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //連接真實的資料庫
        User user = userService.queryUserByName(userToken.getUsername());
        if (user == null) { //沒有這個用戶
            return null; //UnknownAccountException
        }


        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);



        //可以加密: MD5: e10adc3949ba59abbe56e057f20f883e MD5 鹽值加密: e10adc3949ba59abbe56e057f20f883eusername
        //密碼認證, shiro 做~
        return new SimpleAuthenticationInfo(user, user.getPwd(), "");


    }
}

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>首頁</h1>
<div th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登錄</a>
</div>

<p th:text="${msg}"></p>
<hr>
<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>

</body>
</html>

專案結構

img

nInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//連接真實的資料庫
User user = userService.queryUserByName(userToken.getUsername());
if (user == null) { //沒有這個用戶
return null; //UnknownAccountException
}

    Subject currentSubject = SecurityUtils.getSubject();
    Session session = currentSubject.getSession();
    session.setAttribute("loginUser",user);



    //可以加密: MD5: e10adc3949ba59abbe56e057f20f883e MD5 鹽值加密: e10adc3949ba59abbe56e057f20f883eusername
    //密碼認證, shiro 做~
    return new SimpleAuthenticationInfo(user, user.getPwd(), "");


}

}


index.html

```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>首頁</h1>
<div th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登錄</a>
</div>

<p th:text="${msg}"></p>
<hr>
<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>

</body>
</html>

專案結構

[外鏈圖片轉存中…(img-z1gsNvzb-1634195014031)]

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/316602.html

標籤:java

上一篇:(聯想記憶法)JAVA如何巧妙的記憶位運算子號 !!小朋友都能學會

下一篇:初識Java--資料型別和運算子

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more