Spring Boot2.0使用Spring Security的示例代碼
一、Spring Secutity簡介
Spring 是一個非常流行和成功的 Java 應(yīng)用開發(fā)框架。Spring Security 基于 Spring 框架,提供了一套 Web 應(yīng)用安全性的完整解決方案。一般來說,Web 應(yīng)用的安全性包括用戶認(rèn)證(Authentication)和用戶授權(quán)(Authorization)兩個部分。用戶認(rèn)證指的是驗(yàn)證某個用戶是否為系統(tǒng)中的合法主體,也就是說用戶能否訪問該系統(tǒng)。用戶認(rèn)證一般要求用戶提供用戶名和密碼。系統(tǒng)通過校驗(yàn)用戶名和密碼來完成認(rèn)證過程。用戶授權(quán)指的是驗(yàn)證某個用戶是否有權(quán)限執(zhí)行某個操作。在一個系統(tǒng)中,不同用戶所具有的權(quán)限是不同的。比如對一個文件來說,有的用戶只能進(jìn)行讀取,而有的用戶可以進(jìn)行修改。一般來說,系統(tǒng)會為不同的用戶分配不同的角色,而每個角色則對應(yīng)一系列的權(quán)限。
對于上面提到的兩種應(yīng)用情景,Spring Security 框架都有很好的支持。在用戶認(rèn)證方面,Spring Security 框架支持主流的認(rèn)證方式,包括 HTTP 基本認(rèn)證、HTTP 表單驗(yàn)證、HTTP 摘要認(rèn)證、OpenID 和 LDAP 等。在用戶授權(quán)方面,Spring Security 提供了基于角色的訪問控制和訪問控制列表(Access Control List,ACL),可以對應(yīng)用中的領(lǐng)域?qū)ο筮M(jìn)行細(xì)粒度的控制。
另外Spring Security也集成了OAuth2.0,接下來我們就介紹下這兩種使用的,當(dāng)然Spring Security還集成CAS等等,如果你要了解更多請查看 官方文檔 ,我們下面的都是使用Spring Boot2.0做的demo,2.0以后已經(jīng)集成了Spring Security5.0以上的版本;
二、Basic認(rèn)證
這個也是我們經(jīng)常使用的基于表單的認(rèn)證,輸入一個賬號和密碼點(diǎn)擊登錄這種,就是Basic認(rèn)證,我們接下主要會講一下使用以及5.0以后做了那些升級;
1.使用以及常用的一些參數(shù)的介紹
第一步使用Maven引入Spring Security jia包,這里我們使用Thymeleaf作為前端模板頁面,這里也有一個地方可以探討一波,為什么Spring MVC可以自由切換模板,這個地方我們找個機(jī)會一起探討,這里先做下簡單的介紹;
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- 前端模板 thymeleaf 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--安全認(rèn)證框架--> <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.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies>
第二步引入Java配置配置方案
這里我們先使用@Configuration和@EnableWebSecurity對Java類進(jìn)行配置,接下來我們就是繼承WebSecurityConfigurerAdapter,對里面的方法重寫就可以了,分別是對AuthenticationManagerBuilder,WebSecurity,HttpSecurity方法,我們主要介紹AuthenticationManagerBuilder和HttpSecurity,通過對這兩種方法重寫最終實(shí)現(xiàn)我們自定義認(rèn)證;
先來介紹一下HttpSecurity常用參數(shù),如下圖用法基本脫離不了下面這些方法,可以基于認(rèn)證的方式有formLogin、openidLogin、oauth2Login,還可以做一些記住賬號操作rememberMe,還可以進(jìn)行session配置管理,還支持登出loginout等等,使用起來還是蠻簡單的,大家可以參照一下這篇文章,還是蠻詳細(xì)的;

接下來我們再看下AuthenticationManagerBuilder,我們重寫這個方法,可以基于內(nèi)存用戶認(rèn)證、數(shù)據(jù)庫認(rèn)證、LDAP認(rèn)證、還可以自定義用戶服務(wù)、還可以自己定義認(rèn)證。這里我們使用自定義認(rèn)證的做demo,另外這個大家還可能有一個困惑的點(diǎn),configGlobal和configure的差別在哪里,這里大家可以 參考下這篇文章 ,Spring Security從3.2版本以后就默認(rèn)開啟了CRSF防護(hù),這里是通過Token方式去檢測的,在登陸的時候Thymeleaf模板會生成_csrf的標(biāo)簽來防止CRSF,對CSRF不懂的大家可以看下這篇文章 ,這個里面介紹一些防護(hù)CSRF的手段,大家可以思考下,我的demo只是一個簡單的架子,為了是給大家介紹一些知識,可擴(kuò)展大家根據(jù)這些介紹的知識可以隨心所欲的擴(kuò)展自己想要的,不要拘泥于一種方法;
最后我還要介紹一下加密的方式,Spring Security 4的時候我們常用的加密方式是MD5加鹽的方式,5.0以后版本就找不到Md5PasswordEncoder,說明這個方法還是不夠安全,還是可以通過暴力破解可以搞定,可能我不行但是攔不住一些高手,大家可以看下官方支持的以及棄用一些方法:

使用我就不介紹了,有興趣可以自己探索一波,還可以參考一下 文章一 、文章二 ,下面我粘貼我的代碼,講到的這些可以擴(kuò)展的地方大家我在代碼中會標(biāo)識清楚,喜歡動手可以嘗試一下,我的重點(diǎn)是OAuth2驗(yàn)證;
/**
*自定義認(rèn)證
* Created by wangt on 2018/7/29.
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* http資源認(rèn)證
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/","/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
/**
* 自定義認(rèn)證策略
*/
@Autowired
public void configGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider()).eraseCredentials(true);
}
@Bean
public AuthProvider authProvider(){
return new AuthProvider();
}
}
/**
* 自定義認(rèn)證
* Created by wangt on 2018/8/18.
*/
public class AuthProvider implements AuthenticationProvider {
private final BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userName = authentication.getName();
String inputPassword = (String) authentication.getCredentials();
//如果你要使用thymeleaf認(rèn)證方言可以擴(kuò)展一下User
//GrantedAuthority這個是使用方言的屬性,有興趣了解下
//其實(shí)也就是通過這個使用if去判斷
User user =new User();
user.setName("admin");
user.setPassword("admin");
if (user == null) {
throw new AuthenticationCredentialsNotFoundException("authError");
}
//這一塊可以自定義一些加密方式
//自己動手實(shí)現(xiàn)一下
if (true) {
//這塊有好幾個構(gòu)造
//如果使用方言你可以使用3個參數(shù)的構(gòu)造函數(shù)
return new UsernamePasswordAuthenticationToken(user, null);
}
throw new BadCredentialsException("authError");
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
/**
* Created by wangt on 2018/8/18.
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
//如果使用thymeleaf方言在這塊擴(kuò)展
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("index");
registry.addViewController("/").setViewName("index");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--主頁面 index-->
您好!歡迎光臨!
<a href="/login">登錄</a>
<a href="/hello">限制訪問的頁面</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--hello頁面-->
hello
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--登錄頁面-->
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="登錄"/></div>
</form>
</body>
</html>
/**
* 登錄控制器
* Created by wangt on 2018/8/18.
*/
@Controller
public class LoginController {
@GetMapping("/login")
public String login(){
return "/login";
}
}
/**
* 主頁
* Created by wangt on 2018/7/28.
*/
@Controller
public class HomeController {
@GetMapping("/")
public String index(){
return "index";
}
}
/**
* hello頁
* Created by wangt on 2018/8/19.
*/
@Controller
public class HelloController {
@GetMapping("/hello")
public String index(){
return "hello";
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 詳解Spring Boot Security工作流程
- Spring Boot Security 結(jié)合 JWT 實(shí)現(xiàn)無狀態(tài)的分布式API接口
- SpringBoot+Spring Security+JWT實(shí)現(xiàn)RESTful Api權(quán)限控制的方法
- Spring Boot整合Spring Security簡單實(shí)現(xiàn)登入登出從零搭建教程
- SpringBoot + SpringSecurity 短信驗(yàn)證碼登錄功能實(shí)現(xiàn)
- SpringBoot結(jié)合SpringSecurity實(shí)現(xiàn)圖形驗(yàn)證碼功能
- Spring Boot Security配置教程
相關(guān)文章
java ThreadPoolExecutor線程池拒絕策略避坑
這篇文章主要為大家介紹了java ThreadPoolExecutor拒絕策略避坑踩坑示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
SpringBoot中@ConditionalOnBean實(shí)現(xiàn)原理解讀
這篇文章主要介紹了SpringBoot中@ConditionalOnBean實(shí)現(xiàn)原理,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
Java實(shí)現(xiàn)幀動畫的實(shí)例代碼
這篇文章主要介紹了Java實(shí)現(xiàn)幀動畫的實(shí)例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
spring security獲取用戶信息的實(shí)現(xiàn)代碼
這篇文章主要介紹了spring security獲取用戶信息的實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
java線程池的四種創(chuàng)建方式詳細(xì)分析
這篇文章主要介紹了java線程池的四種創(chuàng)建方式詳細(xì)分析,連接池是創(chuàng)建和管理一個連接的緩沖池的技術(shù),這些連接準(zhǔn)備好被任何需要它們的線程使用2022-07-07
詳解Java弱引用(WeakReference)的理解與使用
這篇文章主要介紹了Java弱引用(WeakReference)的理解與使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04

