學習學習SpringSecurity

2020-12-24 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中

這樣就完成了高階教程

相關焦點

  • springboot+springsecurity實現前後端分離簡單實現!
    1、前言部分1.1、如何學習?看springsecurtiy原理圖的時候以為灑灑水,結果自己動手做的時候一竅不通,所以一定不要眼高手低,實踐出真知!通過各種方式學習springsecurity,在B站、騰訊課堂、網易課堂、慕課網沒有springsecurity的前後端分離的教學視頻,那我就去csdn去尋找springsecurity博客,發現幾個問題:要麼就是前後端不分離,要麼就是通過內存方式讀取數據,而不是通過資料庫的方式讀取數據,要麼就是大佬們給的代碼不全、把代碼講的太繞,關鍵部分沒有注釋
  • Spring Security(二)--Guides
    2 Spring Security Guides2.1 引入依賴<dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId
  • Spring boot + Spring Security實現權限管理
    基於Spring boot + Spring Security實現第一版傳統架構本文是實訓邦的權限管理SpringSecurity+JWT的一個講義,分享給粉絲學習。5.構建成功2.使用Thymeleaf製作項目業務頁面具體步驟: 在com.sxbang.fridaysecuritytask包上右鍵選擇 New - > Java Class,輸入名字『controller.HomeController』,點擊回車確定
  • Spring Boot與Shiro整合實現用戶認證
    導入shiro與spring整合依賴修改pom.xml<!;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration
  • SpringSecurity + JWT前後端分離架構實現
    JWT令牌的用戶進行授權 UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());//交給spring
  • 做「有內涵的英語學習」
    作為一種語言學習,我們如何能突破「從單純的英語學習」,提升到「有內涵的英語學習」?1) 單純的英語學習指的是:單純的「英語字面」=單純的「中文意思」。於是,「英語字面」stablize employment就等同於「中文意思」:穩定就業。這就是一種只為語言學習而學習的「初淺」學習。
  • Spring 官方周報-2017/11/22
    https://spring.io/blog/2017/11/18/spring-cloud-finchley-m4-releasedhttps://spring.io/blog/2017/11/15/spring-tips-the-spring-boot-build-plugin
  • 看劇學英語2 | 美劇《戰士》及外文原著閱讀學習
    2/ I share your anger and your outrage(憤怒 ) share這個單詞和大多數英文單詞一樣,很常見,但怎麼用,怎麼樣才能用好很關鍵,這也是我現在學習的目標,日常說話無需高大上的單詞,把這些常見的單詞掌握,並靈活運用就很不錯了。spring 當然不只是春天的意思,今天著重學習下這個單詞。
  • Spring chicken啥意思?「春天的雞」?
    還好卡卡我在英語方面博學多才,並沒有被這個問題所難倒。螢屏上充斥著的大量的「小鮮肉」,就可以稱之為spring chicken,辦公室裡來的新人,也可以稱之為spring chicken,I am a spring chicken, but I lie about my age to get served in bars.我雖然還是個小年輕,但為了能在酒吧裡找到工作,我就謊報了年齡。
  • SpringBoot整合Spring Security
  • 「停課不停學」,來學習「線上課堂」用英語怎麼說!
    那麼,我們一起來學習,開學用英語怎麼說吧!提到開學,有的同學會想,是不是open school呢?千萬不要提到開,就是open啊!由the spring semester 和 fall semester組成指春季學期和秋季學期term常用於英國,學校一年分三個學期。
  • 「spring water」是指泉水,那「spring back」是指什麼呢?
    難道是「春天回來了」,不,這裡的spring不能做「春天」解釋,應該是動詞「回彈;跳回;恢復原狀」的意思。所以spring back意思是「恢復健康」。例句:It's not as easy to spring back from injury when you get older.等你變老,想從傷痛中恢復過來可就沒那麼容易了。
  • 【聚焦項目式學習】農林下路小學:英語項目式學習,線下自主,線上...
    項目式學習項目式學習是廣州市越秀區農林下路小學的特色課程,然而,當項目式學習遇上「宅家」學習,廣州市越秀區農林下路小學應該怎麼開展探究活動呢?隨著線上課程的全面落地,英語科組延續空中課堂的精彩,結合疫情防控和本學科特點,開展線下自主、線上交流的英語項目式學習。
  • 學習能力——庫伯學習圈
    「學習學習再學習」當看到李笑來老師這句話的時候,我是一頭霧水的,只有聽了他的解釋才恍然大悟:我們要學會「學習」的方法,才能更好的學習;「學習學習再學習」,第一個「學習」是動詞,第二個「學習」是名詞,第三個「學習」又是動詞。
  • 「學習強國」的學習達人:老高真「高」!
    6月10日上午,登封市中嶽街道辦事處康村村民高書省在自家的紅薯地裡除草,不大一會兒,汗水就溼透了衣服,老高索性就放下鋤頭,找了個陰涼處就坐下來休息,並從口袋中掏出手機,開始進行他每天的「必修課」,瀏覽閱讀起「學習強國」。「今天的『學習強國』我還沒學習呢,趁著這會休息,趕緊學一會。」
  • 「華研大學習」學習動態
    —— 「做新時代的有為青年」5月12日晚,土木工程學院研究生會在D2-301舉辦第三十八期華研大學習專題活動,主題為「做新時代的有為青年」。本期大學習由華僑大學研究生會、華僑大學青年理論研究會主辦,土木工程學院研究生會承辦,邀請了土木學院研究生第六黨支部的林凡、張茜茜同志作報告,第六黨支部全體成員、院研會全體成員出席會議。