自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用 SpringBoot3.3 + SpEL 讓復(fù)雜權(quán)限控制變得很簡單!

開發(fā) 前端
通過本文的介紹,我們學(xué)習(xí)了如何使用 Spring Boot 3.3 和 SpEL 實(shí)現(xiàn)復(fù)雜的權(quán)限控制。通過 SpEL 強(qiáng)大的表達(dá)式支持,我們可以在業(yè)務(wù)邏輯中靈活地定義和執(zhí)行權(quán)限校驗(yàn),使得復(fù)雜的權(quán)限控制變得更加簡潔和直觀。

在現(xiàn)代應(yīng)用開發(fā)中,權(quán)限控制是一個(gè)至關(guān)重要的部分。復(fù)雜的業(yè)務(wù)場(chǎng)景往往要求靈活且細(xì)粒度的權(quán)限控制,而 Spring Expression Language (SpEL) 為我們提供了強(qiáng)大的表達(dá)式支持,使得權(quán)限控制的實(shí)現(xiàn)變得更加簡便和直觀。本文將詳細(xì)講解如何在 Spring Boot 3.3 中使用 SpEL 實(shí)現(xiàn)復(fù)雜權(quán)限控制,并結(jié)合代碼示例進(jìn)行深入探討。

運(yùn)行效果:

圖片圖片

圖片圖片

圖片圖片

圖片圖片

若想獲取項(xiàng)目完整代碼以及其他文章的項(xiàng)目源碼,且在代碼編寫時(shí)遇到問題需要咨詢交流,歡迎加入下方的知識(shí)星球。

項(xiàng)目環(huán)境配置

首先,我們需要設(shè)置項(xiàng)目的基本環(huán)境,包括 Maven 依賴和 Spring Boot 的配置文件。

pom.xml 配置

<?xml versinotallow="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.3.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.icoderoad</groupId>
	<artifactId>spelpermissions</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spelpermissions</name>
	<description>Demo project for Spring Boot</description>
	
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<!-- Spring Boot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Thymeleaf 模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    
        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

application.yaml 配置

server:
  port: 8080

spring:
  thymeleaf:
    cache: false
    prefix: classpath:/templates/
    suffix: .html
  security:
    user:
      name: admin
      password: admin

使用 SpEL 實(shí)現(xiàn)復(fù)雜權(quán)限控制

SpEL 提供了靈活的表達(dá)式支持,可以直接在注解中使用,結(jié)合 Spring Security 的 @PreAuthorize 注解,可以非常方便地實(shí)現(xiàn)基于業(yè)務(wù)邏輯的權(quán)限控制。

定義權(quán)限模型

首先,我們定義一個(gè)簡單的權(quán)限模型,假設(shè)我們有用戶(User)和資源(Resource),并且只有擁有特定權(quán)限的用戶可以訪問某些資源。

package com.icoderoad.spelpermissions.entity;

import java.util.List;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
	
    private String username;
    
    private List<String> roles;
    
}

package com.icoderoad.spelpermissions.entity;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Resource {
	
	private String resourceName;
	
	private String requiredRole;
	
}

權(quán)限校驗(yàn)邏輯

接下來,我們?cè)诜?wù)層編寫權(quán)限校驗(yàn)邏輯,并使用 SpEL 在控制層進(jìn)行權(quán)限控制。

package com.icoderoad.spelpermissions.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.icoderoad.spelpermissions.entity.Resource;
import com.icoderoad.spelpermissions.entity.User;

@Service
public class ResourceService {

    // 模擬資源列表(在實(shí)際應(yīng)用中,這些資源可能會(huì)從數(shù)據(jù)庫中獲?。?    private final List<Resource> resources = new ArrayList<>();

    public ResourceService() {
        // 初始化一些示例資源
        resources.add(new Resource("Resource1", "ROLE_USER"));
        resources.add(new Resource("Resource2", "ROLE_ADMIN"));
        resources.add(new Resource("Resource3", "ROLE_USER"));
        resources.add(new Resource("Resource4", "ROLE_ADMIN"));
    }

    // 獲取所有資源
    public List<Resource> getAllResources() {
        return resources;
    }

    // 獲取單個(gè)資源
    public Resource getResource(String resourceName) {
        return resources.stream()
                .filter(resource -> resource.getResourceName().equals(resourceName))
                .findFirst()
                .orElse(null);
    }

    // 檢查用戶是否有權(quán)限訪問某個(gè)資源
    public boolean hasPermission(User user, Resource resource) {
        return user.getRoles().contains(resource.getRequiredRole());
    }
}

用戶服務(wù)類實(shí)現(xiàn)

為了獲取用戶的詳細(xì)信息,我們需要實(shí)現(xiàn) UserService 類,負(fù)責(zé)處理用戶登錄、查找等業(yè)務(wù)邏輯。

package com.icoderoad.spelpermissions.service;

import java.util.Arrays;

import org.springframework.stereotype.Service;

import com.icoderoad.spelpermissions.entity.User;

@Service
public class UserService {

    // 模擬從數(shù)據(jù)庫獲取用戶信息
    public User findUserByUsername(String username) {
        // 假設(shè)我們有兩個(gè)用戶:admin 和 user
        if ("admin".equals(username)) {
            return new User(username, Arrays.asList("ROLE_ADMIN", "ROLE_USER"));
        } else if ("user".equals(username)) {
            return new User(username, Arrays.asList("ROLE_USER"));
        } else {
            return null; // 未找到用戶
        }
    }
}

Spring Security 配置

創(chuàng)建一個(gè)自定義的 AccessDeniedHandler 類,用于處理訪問拒絕的情況。

package com.icoderoad.spelpermissions.handler;

import java.io.IOException;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 設(shè)置響應(yīng)狀態(tài)碼
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        // 轉(zhuǎn)發(fā)到 accessDenied.html 頁面
        RequestDispatcher dispatcher = request.getRequestDispatcher("/accessDenied");
        dispatcher.forward(request, response);
    }
}

為了處理用戶登錄和權(quán)限驗(yàn)證,我們需要配置 Spring Security。

package com.icoderoad.spelpermissions.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 啟用方法級(jí)權(quán)限控制
public class SecurityConfig {
	
	@Autowired
    private AccessDeniedHandler customAccessDeniedHandler; // 自動(dòng)注入現(xiàn)有的 CustomAccessDeniedHandler

	
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests()
                .requestMatchers("/res/**").authenticated() // 保護(hù)資源頁面
                .anyRequest().permitAll() // 允許其他所有請(qǐng)求
            .and()
            .formLogin()
                .loginPage("/res/login") // 指定登錄頁面
                .defaultSuccessUrl("/res") // 登錄成功后跳轉(zhuǎn)的頁面
                .permitAll()
            .and()
            .logout()
            .permitAll()
	        .and()
	        .exceptionHandling()
	            .accessDeniedHandler(customAccessDeniedHandler); // 配置自定義的 AccessDeniedHandler


        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();

        UserDetails admin = User.withDefaultPasswordEncoder()
            .username("admin")
            .password("password")
            .roles("ADMIN", "USER")
            .build();

        return new InMemoryUserDetailsManager(user, admin);
    }
   
}

這個(gè)配置類的主要目的是設(shè)置基本的安全配置,包括路徑保護(hù)、表單登錄、登出處理以及自定義的權(quán)限拒絕處理。它使用了 Spring Security 提供的標(biāo)準(zhǔn)功能,并通過 @EnableGlobalMethodSecurity 啟用了方法級(jí)別的權(quán)限控制。

Controller 類的實(shí)現(xiàn)

我們首先實(shí)現(xiàn)用戶登錄、獲取資源列表和獲取用戶權(quán)限的控制器類。

package com.icoderoad.spelpermissions.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.icoderoad.spelpermissions.entity.Resource;
import com.icoderoad.spelpermissions.entity.User;
import com.icoderoad.spelpermissions.service.ResourceService;
import com.icoderoad.spelpermissions.service.UserService;

@Controller
@RequestMapping("/res")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private UserService userService;

    // 獲取資源列表并渲染到頁面
    @GetMapping
    public String listResources(Model model, @AuthenticationPrincipal UserDetails userDetails) {
        // 獲取當(dāng)前登錄用戶
        User user = userService.findUserByUsername(userDetails.getUsername());
        
        // 查詢所有資源
        List<Resource> resources = resourceService.getAllResources();
        
        model.addAttribute("resources", resources);
        model.addAttribute("username", user.getUsername());
        
        return "resources"; // 返回 Thymeleaf 模板頁面
    }

    // 獲取單個(gè)資源,并使用 @PreAuthorize 注解進(jìn)行權(quán)限驗(yàn)證
    @GetMapping("/{resourceName}")
    @PreAuthorize("@resourceService.hasPermission(authentication, #resourceName, 'VIEW')")
    public String getResource(@PathVariable String resourceName, Model model) {
        Resource resource = resourceService.getResource(resourceName);
        
        model.addAttribute("resource", resource);
        return "resourceDetail"; // 返回資源詳情頁面
    }

    
    // 用戶登錄頁面
    @GetMapping("/login")
    public String login() {
        return "login"; // 返回登錄頁面
    }
}

@PreAuthorize("@resourceService.hasPermission(authentication, #resourceName, 'VIEW')") 是 Spring Security 提供的一個(gè)注解,用于方法級(jí)別的權(quán)限控制。它利用了 Spring Expression Language (SpEL) 來執(zhí)行復(fù)雜的權(quán)限檢查。以下是這個(gè)注解的詳細(xì)說明:

組成部分

  1. @PreAuthorize 注解:
  • 用于方法級(jí)別的權(quán)限控制。它允許在方法調(diào)用之前檢查權(quán)限,如果檢查失敗,方法將不會(huì)執(zhí)行。
  1. @resourceService.hasPermission(authentication, #resourceName, 'VIEW'):
  • 這是一個(gè) SpEL 表達(dá)式,用于指定權(quán)限檢查的邏輯。
  • @resourceService 是 Spring 上下文中的一個(gè) Bean。它表示 ResourceService 類的實(shí)例。這個(gè)實(shí)例通常在 Spring 上下文中被管理,并且可以通過注入或引用來訪問。
  • hasPermission 是 ResourceService 類中的一個(gè)方法,用于檢查當(dāng)前用戶是否有權(quán)限執(zhí)行某項(xiàng)操作。
  • authentication 是當(dāng)前的認(rèn)證對(duì)象,代表當(dāng)前登錄的用戶。Spring Security 自動(dòng)將這個(gè)對(duì)象注入到 SpEL 表達(dá)式中。
  • #resourceName 是方法參數(shù)中的一個(gè)變量,代表資源的名稱。SpEL 表達(dá)式通過 # 符號(hào)訪問方法參數(shù)。
  • 'VIEW' 是硬編碼的字符串,表示所需的權(quán)限類型(在這個(gè)例子中是查看權(quán)限)。

視圖控制類

package com.icoderoad.spelpermissions.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

    @GetMapping("/")
    public String index() {
        return "login";
    }
    
    @GetMapping("/accessDenied")
    public String accessDenied() {
        return "accessDenied"; // 返回 Thymeleaf 模板名
    }
    
}

登錄和權(quán)限處理的前端頁面

登錄頁面 login.html

我們?yōu)橛脩舻卿泟?chuàng)建一個(gè)簡單的登錄頁面。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>登錄</title>
    <link rel="stylesheet" >
</head>
<body>
<div class="container">
    <h2>用戶登錄</h2>
    <form th:action="@{/login}" method="post">
        <div class="form-group">
            <label for="username">用戶名</label>
            <input type="text" class="form-control" id="username" name="username" required>
        </div>
        <div class="form-group">
            <label for="password">密碼</label>
            <input type="password" class="form-control" id="password" name="password" required>
        </div>
        <button type="submit" class="btn btn-primary">登錄</button>
    </form>
</div>
</body>
</html>

資源列表頁面 resources.html

當(dāng)用戶成功登錄后,會(huì)被重定向到資源列表頁面。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>資源管理</title>
    <link rel="stylesheet" >
</head>
<body>
<div class="container">
    <h1>資源列表</h1>
    <p>歡迎,<span th:text="${username}"></span>!</p>
    <ul class="list-group">
        <li class="list-group-item" th:each="resource : ${resources}">
            <span th:text="${resource.resourceName}"></span>
            <a th:href="@{/res/{resourceName}(resourceName=${resource.resourceName})}" class="btn btn-primary">
                查看
            </a>
        </li>
    </ul>
</div>
</body>
</html>

資源詳情頁面 resourceDetail.html

當(dāng)用戶點(diǎn)擊某個(gè)資源后,如果用戶有權(quán)限訪問,則會(huì)展示該資源的詳細(xì)信息。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>資源詳情</title>
    <link rel="stylesheet" >
</head>
<body>
<div class="container">
    <h1>資源詳情</h1>
    <p>資源名稱: <span th:text="${resource.resourceName}"></span></p>
    <p>需要權(quán)限: <span th:text="${resource.requiredRole}"></span></p>
    <!-- 返回資源列表按鈕 -->
    <a href="/res" class="btn btn-secondary">返回資源列表</a>
</div>
</body>
</html>

訪問被拒絕頁面 accessDenied.html

如果用戶沒有訪問權(quán)限,將顯示一個(gè)權(quán)限拒絕頁面。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>訪問被拒絕</title>
    <link rel="stylesheet" >
</head>
<body>
<div class="container">
    <h1>訪問被拒絕</h1>
    <p>抱歉,您沒有權(quán)限訪問此資源。</p>
   <!-- 返回資源列表按鈕 -->
    <a href="/res" class="btn btn-secondary">返回資源列表</a>
</div>
</body>
</html>

使用 Thymeleaf 結(jié)合 Bootstrap 實(shí)現(xiàn)一個(gè)簡單的前端頁面,用于展示資源列表和用戶權(quán)限。

** HTML 模板**

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Resource Management</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
</head>
<body>
<div class="container">
    <h1>資源列表</h1>
    <ul class="list-group">
        <li class="list-group-item" th:each="resource : ${resources}">
            <span th:text="${resource.resourceName}"></span>
            <button class="btn btn-primary" th:onclick="'location.href=\'/api/resources/' + ${resource.resourceName} + '\'" >
                查看
            </button>
        </li>
    </ul>
</div>
<script th:src="@{/js/bootstrap.min.js}"></script>
</body>
</html>

在這個(gè)示例中,用戶可以點(diǎn)擊按鈕查看特定資源的詳細(xì)信息。如果用戶沒有相應(yīng)的權(quán)限,則會(huì)返回一個(gè)錯(cuò)誤頁面。

總結(jié)

通過本文的介紹,我們學(xué)習(xí)了如何使用 Spring Boot 3.3 和 SpEL 實(shí)現(xiàn)復(fù)雜的權(quán)限控制。通過 SpEL 強(qiáng)大的表達(dá)式支持,我們可以在業(yè)務(wù)邏輯中靈活地定義和執(zhí)行權(quán)限校驗(yàn),使得復(fù)雜的權(quán)限控制變得更加簡潔和直觀。同時(shí),我們也探討了如何在前后端集成實(shí)現(xiàn)權(quán)限管理的功能。

使用 SpEL 實(shí)現(xiàn)權(quán)限控制是一種非常強(qiáng)大的方式,它不僅支持基本的權(quán)限判斷,還可以通過自定義表達(dá)式滿足各種復(fù)雜的業(yè)務(wù)需求。在實(shí)際應(yīng)用中,可以根據(jù)不同的場(chǎng)景靈活應(yīng)用這一技術(shù),以提高系統(tǒng)的安全性和靈活性。

責(zé)任編輯:武曉燕 來源: 路條編程
相關(guān)推薦

2024-09-04 11:16:44

端口Spring配置類

2024-08-30 11:28:09

2024-09-02 08:17:18

2024-09-03 10:44:32

2016-09-08 23:58:42

云運(yùn)維 云數(shù)據(jù)中心

2024-11-18 08:33:56

2021-10-28 19:35:48

Go 控制超時(shí)

2014-08-01 09:50:39

Oracle營銷云Oracle Eloq

2011-09-15 10:35:12

Android應(yīng)用IOS應(yīng)用著裝搭配

2019-07-10 10:20:36

前端用戶體驗(yàn)javascript

2009-11-06 09:56:46

Check Point軟件刀片安全

2009-11-02 17:42:53

2020-06-16 13:22:22

AI創(chuàng)新深度學(xué)習(xí)

2015-05-05 11:18:18

大數(shù)據(jù)Hadoop技術(shù)處理

2012-06-21 10:26:54

2012-07-24 23:02:40

2013-07-05 11:49:55

華為遠(yuǎn)程醫(yī)療看病

2009-06-18 15:51:52

SSL VPN負(fù)載均衡Array

2024-09-09 11:35:35

2019-01-18 13:13:40

Facebook 開發(fā)開源
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)