Spring Boot 集成教程
- Spring Boot 介紹
- Spring Boot 開發環境搭建(Eclipse)
- Spring Boot Hello World (restful接口)例子
- spring boot 連接Mysql
- spring boot配置druid連接池連接mysql
- spring boot集成mybatis(1)
- spring boot集成mybatis(2) – 使用pagehelper實現分頁
- spring boot集成mybatis(3) – mybatis generator 配置
- spring boot 接口返回值封裝
- spring boot輸入數據校驗(validation)
- spring boot rest 接口集成 spring security(1) – 最簡配置
- spring boot rest 接口集成 spring security(2) – JWT配置
- spring boot 異常(exception)處理
- spring boot 環境配置(profile)切換
- spring boot redis 緩存(cache)集成
概述
本篇教程我們將介紹spring security的集成,為易於學習,我們會盡量剔除無關部分,用最小的配置集成spring security。當你學會怎么集成spring security之后,下一篇我們將集成jwt,在那篇教程中,我們會進一步介紹spring security,完善配置。在前后端分離的大趨勢下,Java后端都是實現REST接口,所以本篇內容僅針對REST接口,如需了解不是接口的情況,可自行參考相關資料。
spring security的實現基於servlet過濾器,在每個請求被spring MVC處理之前,先要經過spring security過濾器,從而實現權限控制。權限控制分兩部分,認證和授權,用戶認證就是指登錄,有些接口要用戶登錄后才能訪問;授權是指根據用戶角色授予不同權限,有些接口要具有一定角色的用戶才能訪問,如管理相關的接口只限admin角色訪問。
我們會創建幾個接口,部分接口需要登錄才能訪問,部分接口完全放開,驗證spring security是否成功集成。
項目依賴
創建spring boot項目
打開Eclipse,創建spring boot的spring starter project項目,選擇菜單:File > New > Project ...,彈出對話框,選擇:Spring Boot > Spring Starter Project,在配置依賴時,勾選web, security,如不清楚怎樣創建spring boot項目,參照教程: [spring boot hello world (restful接口)例子]。

完整的pom.xml
<?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 http://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.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qikegu</groupId>
<artifactId>springboot-security-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-security-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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>
項目配置
spring security Java 配置
spring可以用java配置,也可用xml配置,spring官方推薦用java配置,我們這里用java配置。
添加java配置文件:

a. 添加spring security過濾器
最簡單的注冊spring security過濾器的方法是給java配置類添加@EnableWebSecurity注解:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
// ...
}
b. 用哪種方法加密密碼明文
用戶密碼保存到數據庫時,一般避免明文而以hash值的方式保存,我們可以為spring security配置用什么方法加密密碼明文,此處使用官方推薦的BCryptPasswordEncoder
@Bean
public PasswordEncoder myEncoder() {
return new BCryptPasswordEncoder();
}
c. 配置用戶信息加載
用戶認證/登錄時需要加載用戶信息比對用戶名與密碼,一般用戶信息從數據庫加載,此處為簡便起見,在內存中創建用戶信息,包括用戶名、密碼、用戶角色信息
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password(myEncoder().encode("12345")).roles("ADMIN")
.and()
.withUser("user").password(myEncoder().encode("12345")).roles("USER");
}
d. 配置接口權限控制
通過配置HttpSecurity,可以匹配不同的url路徑,為他們指定不同權限,在這里對於/hello3接口作了權限限制,必須登錄后才能訪問
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 基於token,不需要csrf
.csrf().disable()
// 基於token,不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 下面開始設置權限
.authorizeRequests()
// 需要登錄
.antMatchers("/hello3").authenticated()
// 除上面外的所有請求全部放開
.anyRequest().permitAll();
}
完整的SecurityConfig.java文件
package com.qikegu.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity // 添加security過濾器
public class SecurityConfig extends WebSecurityConfigurerAdapter{
// 密碼明文加密方式配置
@Bean
public PasswordEncoder myEncoder() {
return new BCryptPasswordEncoder();
}
// 認證用戶時用戶信息加載配置
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password(myEncoder().encode("12345")).roles("ADMIN")
.and()
.withUser("user").password(myEncoder().encode("12345")).roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 基於token,不需要csrf
.csrf().disable()
// 基於token,不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 下面開始設置權限
.authorizeRequests()
// 需要登錄
.antMatchers("/hello3").authenticated()
// 除上面外的所有請求全部放開
.anyRequest().permitAll();
}
}
添加代碼
添加一個控制類,實現幾個測試接口。
在項目中添加文件

添加幾個接口,文件內容如下
package com.qikegu.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping(value="/hello1", method=RequestMethod.GET)
public String hello1() {
return "Hello1!";
}
@RequestMapping(value="/hello2", method=RequestMethod.GET)
public String hello2() {
return "Hello2!";
}
@RequestMapping(value="/hello3", method=RequestMethod.GET)
public String hello3() {
return "Hello3!";
}
}
我們實現了3個接口,其中/hello3被配置為需要登錄訪問,所以訪問/hello3時會返回權限受限的錯誤。
運行項目
Eclipse左側,在項目根目錄上點擊鼠標右鍵彈出菜單,選擇:run as -> spring boot app運行程序。 打開Postman訪問接口,運行結果如下:
訪問/hello1接口,不受限

訪問/hello3接口,受限。后面教程將會介紹登錄訪問接口的過程。

總結
本文介紹了spring boot項目中集成spring security的過程,盡量以簡單的方式配置security,下一篇教程將更加詳細地介紹spring security以及jwt的集成。
