學習學習SpringSecurity

2020-12-10 mySoulCode

Spring Security思維導圖

簡介

SpringSecurity是Spring下的一個安全框架,與shiro 類似,一般用於用戶認證(Authentication)和用戶授權(Authorization)兩個部分,常與與SpringBoot相整合。

初階 Spring Security

添加maven依賴

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>重新部署,會看到一個登陸頁面。

密碼,翻看日誌可以查看到

用戶名默認為 user輸入用戶名和密碼

登錄成功

中階 Security 內存用戶名和密碼

用戶名密碼登錄

在上面的章節中,添加了Security依賴,直接就出現了登錄界面,這次讓用戶名,密碼保存到內存當中

寫一個extends WebSecurityConfigurerAdapter的配置類:

配置類內容如下

package com.example.demo.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled =true, securedEnabled =true, jsr250Enabled =true)publicclassWebSecurityConfigextendsWebSecurityConfigurerAdapter{//密碼加密函數@BeanPasswordEncoder passwordEncoder(){returnnewBCryptPasswordEncoder();}//password為BCryptPasswordEncoder加密123後的值@Overrideprotectedvoid configure(AuthenticationManagerBuilder auth)throwsException{ auth.inMemoryAuthentication().withUser("admin").password("$2a$10$2cPRItUHyE1GSZnrYWHiQevpbxn4ikWgOa1PYL5miWvqK8GFVCWb6").roles("admin").and().withUser("java").password("$2a$10$rygGQylvmoAFmPcKQP6xvepNVAw9Bxp0sbAphxKQwhAV79Au0ECvq").roles("user");}@Overrideprotectedvoid configure(HttpSecurity http)throwsException{ http.authorizeRequests().antMatchers("/admin/**").hasRole("admin").antMatchers("/user/**").hasAnyRole("admin","user").anyRequest().authenticated()//其他路徑認證之後就可以訪問.and().formLogin().loginProcessingUrl("/doLogin")//處理登錄請求的地址.permitAll().and().csrf().disable();}}輸入用戶名,密碼,進行登錄

可以看到,登錄成功

其中,1.通過 @EnableWebSecurity註解開啟Spring Security的功能。使用@EnableGlobalMethodSecurity(prePostEnabled = true)這個註解,可以開啟security的註解,我們可以在需要控制權限的方法上面使用@PreAuthorize,@PreFilter這些註解。

2.extends 繼承 WebSecurityConfigurerAdapter 類,並重寫它的方法來設置一些web安全的細節。我們結合@EnableWebSecurity註解和繼承WebSecurityConfigurerAdapter,來給我們的系統加上基於web的安全機制。

## 角色權限控制當我們的系統功能模塊當需求發展到一定程度時,會不同的用戶,不同角色使用我們的系統。這樣就要求我們的系統可以做到,能夠對不同的系統功能模塊,開放給對應的擁有其訪問權限的用戶使用。

Spring Security提供了Spring EL表達式,允許我們在定義URL路徑訪問(@RequestMapping)的方法上面添加註解,來控制訪問權限。

在標註訪問權限時,根據對應的表達式返回結果,控制訪問權限:

true,表示有權限fasle,表示無權限

新建新的控制器

package com.example.demo.web;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/test")publicclassTest{@RequestMapping("/mapping")@ResponseBodypublicString test(){return"test";}}可以看到已經訪問成功

添加權限註解

package com.example.demo.web;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/test")publicclassTest{@RequestMapping("/mapping")@ResponseBody@PreAuthorize("hasRole('admin')")// Spring Security默認的角色前綴是」ROLE_」,使用hasRole方法時已經默認加上了publicString test(){return"test";}}此時訪問

403錯誤

高階:使用資料庫保存用戶名和密碼

用戶表

@EntityclassUser{@Id@GeneratedValue(strategy =GenerationType.AUTO)@BeanPropertyvar id:Integer= _@BeanPropertyvar userName:String= _@BeanPropertyvar password:String= _}角色表

@EntityclassRole{@Id@GeneratedValue(strategy =GenerationType.AUTO)@BeanPropertyvar id:Integer= _@BeanPropertyvar role:String= _}用戶角色表

@EntityclassUserRole{@Id@GeneratedValue(strategy =GenerationType.AUTO)@BeanPropertyvar id:Integer= _@BeanPropertyvar userId:Integer= _@BeanPropertyvar roleId:Integer= _}更改SpringSecurity

@Overrideprotectedvoid configure(AuthenticationManagerBuilder auth)throwsException{ auth.inMemoryAuthentication().withUser("admin").password("$2a$10$2cPRItUHyE1GSZnrYWHiQevpbxn4ikWgOa1PYL5miWvqK8GFVCWb6").roles("admin").and().withUser("java").password("$2a$10$rygGQylvmoAFmPcKQP6xvepNVAw9Bxp0sbAphxKQwhAV79Au0ECvq").roles("user");}更改為

@Override@BeanpublicUserDetailsService userDetailsService(){//覆蓋寫userDetailsService方法 (1)returnnewLightSwordUserDetailService();}//AuthenticationManager使用我們的 lightSwordUserDetailService 來獲取用戶信息 auth.userDetailsService(userDetailsService());具體的 new LightSwordUserDetailService(); 實現類,需要自己進行配置

這個接口需要我們實現一個方法:loadUserByUsername。即從資料庫中取出用戶名、密碼以及權限相關的信息。最後返回一個UserDetails 實現類。

@ServiceclassLightSwordUserDetailServiceextendsUserDetailsService{@Autowiredvar userRoleDao:UserRoleDao= _@Autowiredvar userDao:UserDao= _@Autowiredvar roleDao:RoleDao= _overridedef loadUserByUsername(username:String):UserDetails={// val user = userDao.findByUsername(username) // 直接調用jpa自動生成的方法 val user = userDao.getUserByUsername(username)if(user ==null)thrownewUsernameNotFoundException(username +" not found") val authorities =new util.ArrayList[SimpleGrantedAuthority] val userRoles = userRoleDao.listByUserId(user.id)// Scala中調用java的collection類,使用scala的foreach,編譯器會提示無法找到result的foreach方法。因為這裡的userRoles的類型為java.util.List。若要將其轉換為Scala的集合,就需要增加如下語句:import scala.collection.JavaConversions._for(userRole <- userRoles){ val roleId = userRole.roleId val roleName = roleDao.findOne(roleId).roleif(!StringUtils.isEmpty(roleName)){ authorities.add(newSimpleGrantedAuthority(roleName))}System.err.println("username is "+ username +", "+ roleName)}newUser(username, user.password, authorities)}}在上方,通過內部類的方式,獲取到了一個User對象。並添加進入了UserDetails中

這樣就完成了高階教程

相關焦點

  • spring security 整合 springboot 入門案例
    序言前面我們學習了 spring security 與 springmvc 的整合入門教程。這一節我們來學習一下 spring security 與 springboot 整合,為了力求簡單,此處不演示資料庫相關操作。
  • springboot+springsecurity實現前後端分離簡單實現!
    1、前言部分1.1、如何學習?看springsecurtiy原理圖的時候以為灑灑水,結果自己動手做的時候一竅不通,所以一定不要眼高手低,實踐出真知!通過各種方式學習springsecurity,在B站、騰訊課堂、網易課堂、慕課網沒有springsecurity的前後端分離的教學視頻,那我就去csdn去尋找springsecurity博客,發現幾個問題:要麼就是前後端不分離,要麼就是通過內存方式讀取數據,而不是通過資料庫的方式讀取數據,要麼就是大佬們給的代碼不全、把代碼講的太繞,關鍵部分沒有注釋
  • 超全的springboot+springsecurity實現前後端分離簡單實現!
    通過各種方式學習springsecurity,在B站、騰訊課堂、網易課堂、慕課網沒有springsecurity的前後端分離的教學視頻,那我就去csdn去尋找springsecurity博客,發現幾個問題:  實在不行我又跑去github上找開源項目學習,github由於是外國網站,國內訪問速度有點慢!!
  • SpringSecurity + JWT,從入門到精通!
    org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
  • Spring Boot Security 詳解
    </groupId> <artifactId>spring-boot-starter-security</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId>
  • 船新「漲薪秘籍」阿里巴巴內部爆款頂配版Spring Security筆記
    由於它是Spring生態系統中的一員,因此它伴隨著整個Spring生態系統不斷修正、升級,在spring boot項目中加入springsecurity更是十分簡單,使用Spring Security 減少了為企業系統安全控制編寫大量重複代碼的工作。
  • 「SpringSecurity-1」Springboot+Security+Oauth2授權碼模式
    話不多說開始搞……項目搭建項目中使用到的相關框架的版本號:springboot版本:2.3.0.RELEASEspring-security-oauth2版本:2.3.3.RELEASE創建認證伺服器添加依賴pom.xml中添加依賴,特別說明這是一個父子項目,父pom中添加了spring-boot-dependencies
  • 網際網路安全下的Spring Security之初體驗
    今天咱們就來學習一下使用SpringBoot 集成SpringSecurity,我們都知道SpringBoot也是基於Spring的,所以SpringBoot對於SpringSecurity也提供很好的支持,通常情況下,Spring生態內的技術在使用的時候都是比較容易上手的,接下裡就讓我們實戰為先吧!
  • Spring Security 5.1 GA 正式發布! - OSCHINA - 中文開源技術交流...
    -->    <dependency>        <groupId>org.springframework.security</groupId>        <artifactId>spring-security-web</artifactId>        <version>5.1.0.RELEASE</version
  • Spring Security 5.2.2、5.1.8 和 5.0.14 發布
    默認情況下,不要使用 Accept: text/event-stream 來緩存請求 提供 AuthorizedClientServiceOAuth2AuthorizedClientManager 的反應式實現 刪除重定向驗證的多餘驗證 刪除 SecurityExpressionRoot 中不必要的代碼 提取 HTTPS 文檔更新說明:https://github.com/spring-projects
  • Spring Security基於表達式的權限控制
    前言spring security 3.0已經可以使用spring el表達式來控制授權,允許在表達式中使用複雜的布爾邏輯來控制訪問的權限。表達式描述hasRole([role])用戶擁有制定的角色時返回true (Spring security 默認會帶有ROLE_前綴),去除參考Remove the ROLE_hasAnyRole([role1,role2])用戶擁有任意一個制定的角色時返回truehasAuthority
  • 「SpringSecurity-3」Springboot+Security + Oauth2授權碼模式
    授權登錄頁面自定義實現授權登陸頁修改第一步修改security配置文件。獲取授權碼時修改登錄頁面,需要對授權伺服器配置進行修改,修改如下:第二步添加login.htmlpom.xml文件中引入 spring-boot-starter-thymeleaf 依賴在resources文件夾下創建static文件夾並創建login.html文件login.html文件如下:這樣我們就自定義了一個登陸頁面,並且將登陸頁面集成到
  • Spring Security 5.1.0.M2 發布,Spring 安全框架
    源碼下載 >>> https://github.com/spring-projects/spring-security/releases/tag/5.1.0.M2
  • Spring Boot 和 Spring 到底有啥區別?
    Java技術棧www.javastack.cn關注閱讀更多優質文章https://www.leshalv.net/posts/1090913254概述對於Spring和SpringBoot到底有什麼區別,我聽到了很多答案,剛開始邁入學習
  • Spring Security接管Swagger認證授權,我發現僅用了3行關鍵代碼!
    以Maven為例,向pom.xml文件添加如下配置信息:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId
  • Spring-Framework 學習-1
    Spring閱讀源碼環境搭建關於Spring, 我們平時接觸最多的其實應該是Spring Boot, 但是Spring Boot, 只是Spring的大集成者,所以,學習引入pom我這裡使用的是spring 5.2.x系列版本,建議使用5.0以上版本<dependency>      <groupId>org.springframework</groupId>      <artifactId
  • .net core+Spring Cloud學習之路 一
    現在明白了只有不斷的學習才能不被淘汰,只有不斷的學習才能拿到更高的工資。  言歸正傳,在今早發現張隊在元旦前的博客「年末展望:Oracle 對 JDK收費和.NET Core 給我們的機遇」,說明了以後.net core會越來越好,而我本人在2017年的時候開始接觸過.net core的時候,就沒有放棄過對.net core的學習,現在覺得微服務是個不錯的方向,而自己也在學習這塊的東西,所以寫個博客記錄一下自己的學習的筆記。
  • spring學習總結(一)_Ioc基礎(上)
    閱讀目錄spring概述Ioc基礎使用XML配置方式實現IOC>最近經歷了許許多多的事情,學習荒廢了很久。看了他寫的spring系列的博客,寫的不錯。於是本文的內容參考自他的博客,當然都是手打書寫。由於我感覺他寫的博客篇幅過長。我根據我的習慣進行拆分學習。而且他的文章一系列很清楚。也值得我去學習。自己寫博客就零零散散。不是很系統。spring概述spring可以做很多事情,它為企業級開發提供了豐富的功能。
  • Spring5.0源碼學習系列之Spring AOP簡述
    在學習Spring AOP源碼之前,您是否對AOP有足夠熟悉的理解?
  • Spring 和 Spring Boot 之間到底有啥區別?
    概述對於 Spring和 SpringBoot到底有什麼區別,我聽到了很多答案,剛開始邁入學習 SpringBoot的我當時也是一頭霧水,隨著經驗的積累、我慢慢理解了這兩個框架到底有什麼區別,相信對於用了 SpringBoot很久的同學來說,還不是很理解 SpringBoot到底和 Spring有什麼區別,看完文章中的比較,或許你有了不同的答案和看法!