最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合Spring Security實現基礎認證與授權

 更新時間:2026年04月24日 09:05:09   作者:希望永不加班  
在后端開發(fā)領域,認證(Authentication)?和授權(Authorization)?是系統安全的核心基石,Spring Security 作為 Spring 生態(tài)官方推薦的安全框架,是Java 后端安全開發(fā)的首選方案,本文給大家介紹了SpringBoot整合Spring Security實現基礎認證與授權

在后端開發(fā)領域,認證(Authentication) 和授權(Authorization) 是系統安全的核心基石。簡單來說:認證是確認「你是誰」,授權是決定「你能做什么」。

Spring Security 作為 Spring 生態(tài)官方推薦的安全框架,憑借高度模塊化、可擴展、無縫整合 SpringBoot 等特性,成為 Java 后端安全開發(fā)的首選方案。

一、前置知識與環(huán)境說明

1.1 核心概念

1. 認證(Authentication)
驗證用戶身份是否合法,比如輸入賬號密碼登錄、短信驗證碼登錄,都屬于認證流程。

2. 授權(Authorization)
認證通過后,根據用戶的角色/權限,控制用戶能訪問哪些接口、頁面,比如管理員能訪問所有接口,普通用戶只能訪問個人接口。

3. Spring Security
基于 Spring AOP 和 Servlet 過濾器實現的安全框架,默認提供了表單登錄、注銷、會話管理、csrf 防護、權限控制等全套安全能力。

1.2 開發(fā)環(huán)境

  • JDK 8+
  • SpringBoot 2.7.x(穩(wěn)定版,兼容絕大多數企業(yè)項目)
  • Maven 3.6+
  • IDEA 開發(fā)工具
  • Lombok(簡化代碼)

二、項目初始化與依賴引入

2.1 創(chuàng)建 SpringBoot 項目

打開 IDEA,創(chuàng)建一個標準的 SpringBoot 項目,項目名稱:springboot-security-demo。

2.2 核心依賴(pom.xml)

直接復制以下依賴,無需額外版本號,SpringBoot 自動管理版本兼容:

<?xml version="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>2.7.15</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-security-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-security-demo</name>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!-- SpringBoot Web 核心依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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>
            <optional>true</optional>
        </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>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2.3 啟動項目,體驗默認安全機制

直接啟動 SpringBoot 項目,控制臺會打印一段默認密碼

Using generated security password: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

默認用戶名:user
默認密碼:控制臺打印的隨機字符串

訪問測試接口:http://localhost:8080
會自動跳轉到 Spring Security 提供的默認登錄頁面,輸入賬號密碼即可登錄成功。

這就是 Spring Security 的自動配置機制,零代碼實現基礎登錄保護,但實際項目中,我們必須自定義登錄邏輯、用戶信息、權限規(guī)則。

三、Spring Security 核心架構理解

在動手寫代碼前,先搞懂核心組件,后續(xù)配置會一目了然:

1. SecurityContextHolder
安全上下文持有者,存儲當前登錄用戶的信息(Authentication 對象)。

2. Authentication
認證對象,包含用戶身份信息、權限信息、認證狀態(tài)。

3. UserDetailsService
核心接口,用于加載用戶信息(我們必須實現它,自定義查詢用戶邏輯)。

4. PasswordEncoder
密碼加密器,Spring Security 強制要求密碼加密,不能明文存儲。

5. SecurityFilterChain
安全過濾器鏈,所有認證、授權、防護邏輯都通過過濾器鏈執(zhí)行。

6. @PreAuthorize
權限注解,用于控制方法/接口的訪問權限。

四、內存用戶認證

第一步,我們先使用內存用戶實現登錄認證,不連接數據庫,快速理解配置邏輯。

4.1 創(chuàng)建 Security 配置類

創(chuàng)建配置類:com.example.config.SecurityConfig

package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/**
 * Spring Security 核心配置類
 * @EnableWebSecurity 開啟 Spring Security  web 安全支持
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    /**
     * 密碼加密器
     * 推薦使用 BCrypt 算法,自動加鹽,不可逆加密
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 內存用戶信息管理
     * 定義兩個用戶:admin(管理員)、user(普通用戶)
     */
    @Bean
    public UserDetailsService userDetailsService() {
        // 管理員用戶
        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("123456")) // 密碼加密
                .roles("ADMIN") // 角色
                .build();
        // 普通用戶
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("123456"))
                .roles("USER")
                .build();
        // 內存存儲用戶信息
        return new InMemoryUserDetailsManager(admin, user);
    }
}

4.2 配置說明

1. @EnableWebSecurity:開啟 Spring Security 安全配置。

2. PasswordEncoder:必須配置,Spring Security 禁止明文密碼,BCrypt 是官方推薦加密方式。

3. UserDetailsService:用戶信息加載接口,這里使用內存實現。

4. .roles():為用戶分配角色,用于后續(xù)授權控制。

4.3 測試登錄

重啟項目,訪問:http://localhost:8080/login

  • 管理員賬號:admin / 123456
  • 普通用戶賬號:user / 123456

登錄成功后,即可訪問所有接口(此時還未做權限控制)。

五、URL 權限控制

我們需要對不同接口設置不同的訪問權限,比如:

  • 公共接口:所有人可訪問(登錄、首頁、靜態(tài)資源)
  • 用戶接口:僅登錄用戶可訪問
  • 管理員接口:僅 ADMIN 角色可訪問

5.1 修改 SecurityConfig,添加 HttpSecurity 配置

在 SecurityConfig 類中添加以下方法:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.SecurityFilterChain;
/**
 *  SpringBoot 2.7+ 推薦使用 Lambda 風格配置
 *  棄用 WebSecurityConfigurerAdapter
 */
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        // 1. 授權配置
        .authorizeRequests()
            // 公共接口:無需登錄即可訪問
            .antMatchers("/", "/home", "/login", "/css/**", "/js/**").permitAll()
            // 管理員接口:僅 ADMIN 角色可訪問
            .antMatchers("/admin/**").hasRole("ADMIN")
            // 用戶接口:僅 USER 角色可訪問
            .antMatchers("/user/**").hasRole("USER")
            // 所有其他請求:必須登錄才能訪問
            .anyRequest().authenticated()
        .and()
        // 2. 表單登錄配置
        .formLogin()
            // 自定義登錄頁面(可選)
            .loginPage("/login")
            // 登錄請求處理接口
            .loginProcessingUrl("/doLogin")
            // 登錄成功默認跳轉頁面
            .defaultSuccessUrl("/home")
            // 登錄失敗跳轉頁面
            .failureUrl("/login?error=true")
            // 允許所有人訪問登錄相關接口
            .permitAll()
        .and()
        // 3. 登出配置
        .logout()
            // 登出請求接口
            .logoutUrl("/logout")
            // 登出成功跳轉頁面
            .logoutSuccessUrl("/login?logout=true")
            // 登出后清除會話
            .invalidateHttpSession(true)
            // 清除認證信息
            .clearAuthentication(true)
            .permitAll()
        .and()
        // 4. 關閉 CSRF 防護(前后端分離項目建議關閉)
        .csrf().disable();
    return http.build();
}

5.2 權限規(guī)則說明

1. permitAll():所有人可訪問,無需登錄。

2. hasRole("角色名"):必須擁有指定角色才能訪問。

3. anyRequest().authenticated():除了上面配置的接口,其余都需要登錄。

4. formLogin():開啟表單登錄,Spring Security 自動生成登錄接口。

5. logout():開啟登出功能,自動清理會話。

5.3 創(chuàng)建測試接口

創(chuàng)建控制器:com.example.controller.TestController

package com.example.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
    // 公共接口
    @GetMapping("/home")
    public String home() {
        return "首頁:所有人可訪問";
    }
    // 普通用戶接口
    @GetMapping("/user/info")
    public String userInfo() {
        return "用戶信息:僅 USER 角色可訪問";
    }
    // 管理員接口
    @GetMapping("/admin/info")
    public String adminInfo() {
        return "管理員信息:僅 ADMIN 角色可訪問";
    }
    // 測試接口
    @GetMapping("/test")
    public String test() {
        return "測試接口:僅登錄用戶可訪問";
    }
}

5.4 權限測試

1. 未登錄:訪問 /admin/info/user/info、/test 都會自動跳轉到登錄頁。

2. 登錄 user 用戶:

  • 可訪問:/home、/user/info、/test
  • 不可訪問:/admin/info(403 無權限)

3. 登錄 admin 用戶:

  • 完美實現基于角色的 URL 權限控制

六、注解式權限控制

除了 URL 配置,Spring Security 還支持方法級注解權限,更靈活,適合分布式、微服務項目。

6.1 開啟注解權限

在啟動類添加 @EnableMethodSecurity(SpringBoot 2.7+)或 @EnableGlobalMethodSecurity(舊版):

package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
// 開啟方法級權限控制
@EnableMethodSecurity(prePostEnabled = true)
@SpringBootApplication
public class SpringbootSecurityDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootSecurityDemoApplication.class, args);
    }
}

6.2 常用權限注解

1. @PreAuthorize:方法執(zhí)行前校驗權限(最常用)

2. @PostAuthorize:方法執(zhí)行后校驗權限

3. @Secured:舊版角色注解

6.3 實戰(zhàn)使用

@RestController
public class AuthController {
    // 僅 ADMIN 角色可訪問
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/auth/admin")
    public String authAdmin() {
        return "注解權限:管理員專屬接口";
    }
    // 僅 USER 角色可訪問
    @PreAuthorize("hasRole('USER')")
    @GetMapping("/auth/user")
    public String authUser() {
        return "注解權限:普通用戶專屬接口";
    }
    // 擁有 ADMIN 或 USER 角色均可訪問
    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    @GetMapping("/auth/common")
    public String authCommon() {
        return "注解權限:登錄用戶均可訪問";
    }
    // 擁有指定權限標識(非角色)
    @PreAuthorize("hasAuthority('user:add')")
    @GetMapping("/auth/authority")
    public String authAuthority() {
        return "注解權限:擁有 user:add 權限可訪問";
    }
}

注解式權限代碼侵入性低、靈活度高,是企業(yè)項目主流用法。

七、數據庫查詢用戶認證

內存用戶僅適合測試,真實項目必須從數據庫加載用戶

核心步驟:

1. 實現 UserDetailsService 接口

2. 重寫 loadUserByUsername 方法

3. 從數據庫查詢用戶信息+角色權限

4. 封裝成 UserDetails 對象返回

7.1 引入數據庫依賴(可選 MyBatis/MyBatis-Plus/JPA)

這里以 MyBatis-Plus 為例(簡化數據庫操作):

<!-- MySQL 驅動 --> <dependency>     <groupId>mysql</groupId>     <artifactId>mysql-connector-java</artifactId>     <scope>runtime</scope> </dependency> <!-- MyBatis-Plus --> <dependency>     <groupId>com.baomidou</groupId>     <artifactId>mybatis-plus-boot-starter</artifactId>     <version>3.5.3.1</version> </dependency>

7.2 數據庫表設計

-- 用戶表
CREATE TABLE `sys_user` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL COMMENT '用戶名',
  `password` varchar(100) NOT NULL COMMENT '密碼(BCrypt加密)',
  `status` int DEFAULT 1 COMMENT '狀態(tài) 0-禁用 1-正常',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 角色表
CREATE TABLE `sys_role` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `role_name` varchar(50) NOT NULL COMMENT '角色名稱',
  `role_code` varchar(50) NOT NULL COMMENT '角色編碼 ADMIN/USER',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 用戶角色關聯表
CREATE TABLE `sys_user_role` (
  `user_id` bigint NOT NULL,
  `role_id` bigint NOT NULL,
  PRIMARY KEY (`user_id`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 插入測試數據
INSERT INTO sys_user (username, password, status) VALUES 
('admin', '$2a$10$wJ5i4y9y9Q9m0pOe1x2L3u4S5D6F7G8H9J0K1L2M3N4B5V6C7X8Z9A', 1),
('user', '$2a$10$wJ5i4y9y9Q9m0pOe1x2L3u4S5D6F7G8H9J0K1L2M3N4B5V6C7X8Z9A', 1);
INSERT INTO sys_role (role_name, role_code) VALUES 
('管理員', 'ADMIN'),('普通用戶', 'USER');
INSERT INTO sys_user_role (user_id, role_id) VALUES (1,1),(2,2);

密碼明文:123456,已使用 BCrypt 加密。

7.3 自定義 UserDetails 實現類

Spring Security 默認的 User 類不夠用,我們自定義:

package com.example.entity;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
 * 自定義用戶詳情,實現 UserDetails 接口
 */
@Data
public class SecurityUser implements UserDetails {
    // 用戶ID
    private Long id;
    // 用戶名
    private String username;
    // 密碼
    private String password;
    // 狀態(tài)
    private Integer status;
    // 角色列表
    private List<String> roles;
    /**
     * 獲取權限/角色集合
     * Spring Security 要求角色必須以 ROLE_ 開頭
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                .collect(Collectors.toList());
    }
    @Override
    public String getPassword() {
        return this.password;
    }
    @Override
    public String getUsername() {
        return this.username;
    }
    // 賬戶是否未過期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    // 賬戶是否未鎖定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    // 密碼是否未過期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    // 賬戶是否可用
    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }
}

7.4 實現 UserDetailsService 核心接口

package com.example.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.entity.SecurityUser;
import com.example.entity.SysUser;
import com.example.service.SysRoleService;
import com.example.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * 自定義用戶認證服務
 * 核心:從數據庫查詢用戶信息
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;
    /**
     * 根據用戶名加載用戶信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 根據用戶名查詢用戶
        SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUsername, username));
        if (user == null) {
            throw new UsernameNotFoundException("用戶名不存在");
        }
        // 2. 查詢用戶角色
        List<String> roles = roleService.getRolesByUserId(user.getId());
        // 3. 封裝成 SecurityUser 對象返回
        SecurityUser securityUser = new SecurityUser();
        securityUser.setId(user.getId());
        securityUser.setUsername(user.getUsername());
        securityUser.setPassword(user.getPassword());
        securityUser.setStatus(user.getStatus());
        securityUser.setRoles(roles);
        return securityUser;
    }
}

7.5 配置類注入自定義 UserDetailsService

刪除之前的內存用戶配置,直接使用我們自定義的服務:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private UserDetailsService userDetailsService;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .userDetailsService(userDetailsService) // 注入自定義用戶服務
            .authorizeRequests()
                .antMatchers("/", "/home", "/login").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/doLogin")
                .defaultSuccessUrl("/home")
                .permitAll()
            .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
                .permitAll()
            .and()
            .csrf().disable();
        return http.build();
    }
}

至此,企業(yè)級數據庫認證配置完成!
登錄邏輯完全基于數據庫查詢,支持多角色、賬戶狀態(tài)控制。

八、登錄用戶信息獲取

在業(yè)務代碼中,我們經常需要獲取當前登錄用戶信息,Spring Security 提供了便捷工具:

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserInfoController {
    /**
     * 獲取當前登錄用戶信息
     */
    @GetMapping("/getUserInfo")
    public String getUserInfo() {
        // 1. 獲取認證對象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 2. 判斷是否登錄
        if (authentication == null || !authentication.isAuthenticated()) {
            return "未登錄";
        }
        // 3. 獲取用戶信息
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            SecurityUser securityUser = (SecurityUser) principal;
            return "當前登錄用戶:" + securityUser.getUsername() 
                    + ",角色:" + securityUser.getRoles();
        }
        return "獲取用戶信息失敗";
    }
}

九、異常處理:401 未認證 / 403 無權限

Spring Security 默認異常頁面不友好,我們可以自定義異常處理:

package com.example.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
 * 自定義安全異常處理
 */
@Configuration
public class SecurityExceptionConfig {
    /**
     * 401 未登錄處理
     */
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, authException) -> {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("msg", "未登錄,請先登錄");
            new ObjectMapper().writeValue(response.getWriter(), result);
        };
    }
    /**
     * 403 無權限處理
     */
    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return (request, response, accessDeniedException) -> {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 403);
            result.put("msg", "無權限訪問該資源");
            new ObjectMapper().writeValue(response.getWriter(), result);
        };
    }
}

在 SecurityConfig 中注入:

http.exceptionHandling()
    .authenticationEntryPoint(authenticationEntryPoint)
    .accessDeniedHandler(accessDeniedHandler);

十、Spring Security 核心知識點總結

1. 兩大核心:認證(登錄)+ 授權(權限)

2. 核心接口:UserDetailsService(加載用戶)、PasswordEncoder(密碼加密)

3. 兩種權限控制:URL 配置 + 方法注解

4. 密碼必須加密:BCrypt 算法是最佳實踐

5. 前后端分離:關閉 CSRF,使用 Token 認證(下篇文章講解)

6. 異常統一處理:401 未登錄、403 無權限

結語

Spring Security 是 Java 后端必備安全框架,掌握基礎認證與授權,足以應對絕大多數企業(yè)項目的安全需求。

如果文章對你有幫助,歡迎點贊、在看、轉發(fā),你的支持是我持續(xù)更新的動力!

有任何問題,歡迎在評論區(qū)留言交流~

  • 可訪問所有接口。

1. @PreAuthorize:方法執(zhí)行前校驗權限(最常用)

2. @PostAuthorize:方法執(zhí)行后校驗權限

3. @Secured:舊版角色注解

1. 實現 UserDetailsService 接口

2. 重寫 loadUserByUsername 方法

3. 從數據庫查詢用戶信息+角色權限

4. 封裝成 UserDetails 對象返回

1. 兩大核心:認證(登錄)+ 授權(權限)

2. 核心接口:UserDetailsService(加載用戶)、PasswordEncoder(密碼加密)

3. 兩種權限控制:URL 配置 + 方法注解

4. 密碼必須加密:BCrypt 算法是最佳實踐

5. 前后端分離:關閉 CSRF,使用 Token 認證(下篇文章講解)

6. 異常統一處理:401 未登錄、403 無權限

以上就是SpringBoot整合Spring Security實現基礎認證與授權的詳細內容,更多關于SpringBoot Spring Security認證與授權的資料請關注腳本之家其它相關文章!

相關文章

  • 教你用MAT工具分析Java堆內存泄漏問題的解決方法

    教你用MAT工具分析Java堆內存泄漏問題的解決方法

    今天給大家?guī)淼氖顷P于Java的相關知識,文章圍繞著如何使用MAT工具分析Java堆內存泄漏問題的解決方法展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • JavaWeb Servlet實現網頁登錄功能

    JavaWeb Servlet實現網頁登錄功能

    這篇文章主要為大家詳細介紹了JavaWeb Servlet實現網頁登錄功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • Java?多線程并發(fā)?ReentrantReadWriteLock詳情

    Java?多線程并發(fā)?ReentrantReadWriteLock詳情

    這篇文章主要介紹了Java多線程并發(fā)ReentrantReadWriteLock詳情,ReentrantReadWriteLock可重入讀寫鎖。實際使用場景中,我們需要處理的操作本質上是讀與寫,更多相關資料,感興趣的小伙伴可以參考一下下面文章內容
    2022-06-06
  • 淺談Java多線程處理中Future的妙用(附源碼)

    淺談Java多線程處理中Future的妙用(附源碼)

    這篇文章主要介紹了淺談Java多線程處理中Future的妙用(附源碼),還是比較不錯的,需要的朋友可以參考下。
    2017-10-10
  • Lambda表達式和Java集合框架

    Lambda表達式和Java集合框架

    本文主要介紹了Lambda表達式和Java集合框架的相關知識,具有很好的參考價值。下面跟著小編一起來看下吧
    2017-03-03
  • Java 基于TCP Socket 實現文件上傳

    Java 基于TCP Socket 實現文件上傳

    這篇文章主要介紹了Java 基于TCP Socket 實現文件上傳的示例代碼,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2020-12-12
  • java Unicode和UTF-8之間轉換實例

    java Unicode和UTF-8之間轉換實例

    這篇文章主要介紹了java Unicode和UTF-8之間轉換實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • SpringBoot實現緩存預熱的幾種常用方案

    SpringBoot實現緩存預熱的幾種常用方案

    緩存預熱是指在 Spring Boot 項目啟動時,預先將數據加載到緩存系統(如 Redis)中的一種機制,本文給大家介紹了SpringBoot實現緩存預熱的幾種常用方案,并通過代碼示例講解的非常詳細,需要的朋友可以參考下
    2024-02-02
  • Mybatis關聯查詢遇到的坑-無主鍵的關聯數據去重問題

    Mybatis關聯查詢遇到的坑-無主鍵的關聯數據去重問題

    這篇文章主要介紹了Mybatis關聯查詢遇到的坑-無主鍵的關聯數據去重問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • 如何使用Java調用Spark集群

    如何使用Java調用Spark集群

    這篇文章主要介紹了如何使用Java調用Spark集群,我搭建的Spark集群的版本是2.4.4,本文結合示例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
    2024-02-02

最新評論

商都县| 西畴县| 报价| 穆棱市| 资源县| 巨鹿县| 西吉县| 萨嘎县| 大悟县| 巨鹿县| 宁都县| 民乐县| 延吉市| 景泰县| 西丰县| 广饶县| 岫岩| 靖宇县| 凭祥市| 城固县| 乌拉特前旗| 通辽市| 依安县| 金寨县| 宁乡县| 阳东县| 甘洛县| 麟游县| 长武县| 玉溪市| 神农架林区| 鹿泉市| 加查县| 无棣县| 焦作市| 庄河市| 青神县| 拉萨市| 白朗县| 通道| 池州市|