spring-boot-starter-security的簡單使用方式
基于配置文件使用security
首先引入兩個必備的依賴
<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>
由于springboot對starter依賴進行了自動化的配置,即約定大于配置,也就是帶有starter的依賴在整合springboot時,在我們不做任何配置時,默認(rèn)使用starter約定的配置,只有當(dāng)我們進行自定義配置時,springboot才會使用我們的配置
通過配置文件的方式在內(nèi)存中配置一個用戶
spring: application: name: spring-security security: user: name: user roles: admin password: 123456 server: port: 8848
由于spring-boot-starter-security默認(rèn)開啟登錄認(rèn)證,所以我們需要新建一個TestController的controller類
@RestController @RequestMapping("/test") public class TestConteoller { @GetMapping("/security") public String security(){ return "test-spring-security登陸成功"; } }
啟動應(yīng)用并訪問http://localhost:8848/test/security,我們會看到spring-boot-starter-security自帶的登陸頁面,輸入我們在配置文件中配置的用戶名稱和密碼,之后我們會在頁面看到
test-spring-security登陸成功
基于配置類使用security
上面我們實現(xiàn)了基于配置文件的security簡單配置,顯然這樣并不適用現(xiàn)實場景,下面我們見通過配置類的方式實現(xiàn)security的自定義配置
新建config文件夾并其中新建SecurityConfig配置類,讓其繼承WebSecurityConfigurerAdapter抽象類并重寫兩個configure方法,實現(xiàn)web環(huán)境下的security自定義配置
具體如下:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { //自定義配置URL資源的權(quán)限控制 @Override protected void configure(HttpSecurity http) throws Exception { http. //對所有請求進行權(quán)限認(rèn)證 authorizeRequests() //自定義配置請求地址權(quán)限 .mvcMatchers("/test/security").permitAll() // permitAll() 對所有請求放行 .mvcMatchers("/admin/security").hasRole("admin") .mvcMatchers("/user/security").hasRole("user") .mvcMatchers("/tUser/selectAll").anonymous() // anonymous() 允許匿名訪問,登陸狀態(tài)不能訪問 .anyRequest().authenticated() //所有請求都需要進行認(rèn)證 .and() .formLogin() //.loginPage("login") 自定義登陸頁面 .permitAll() //所有用戶都可以訪問 .and() .logout() //.logoutUrl("logout") 自定義配置退出登陸頁面 .permitAll(); } //自定義配置認(rèn)證規(guī)則 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //spring內(nèi)置了兩種UserDetailManager實現(xiàn),一種基于內(nèi)存的InMemoryUserDetailsManager,另一種是基于數(shù)據(jù)庫的JdbcUserDetailsManager auth. //使用內(nèi)存中的InMemoryUserDetailsManager(內(nèi)存用戶管理器) inMemoryAuthentication() //不使用passwordEncoder密碼加密 .passwordEncoder(NoOpPasswordEncoder.getInstance()) //在內(nèi)存中給配置user用戶 .withUser("admin").password("admin").roles("admin") .and() //在內(nèi)存中配置admin用戶 .withUser("user").password("user").roles("user"); } }
security配置類搞定之后,我們新建UserController和AdminController兩個接口測試類
具體如下:
@RestController @RequestMapping("/user") public class UserController { @GetMapping("/security") public String security(){ return "user-spring-security登陸成功"; } } @RestController @RequestMapping("/admin") public class AdminController { @GetMapping("/security") public String security(){ return "admin-spring-security登陸成功"; } }
重新啟動應(yīng)用,并分別訪問http://localhost/test/security、http://localhost/user/security、http://localhost/admin/security三個地址,我們會發(fā)現(xiàn)第一個地址不用登陸就能直接訪問,第二個地址需要user角色權(quán)限,第三個地址需要admin角色權(quán)限;
需要注意的是,當(dāng)我們訪問第二個地址并使用user角色登錄之后,我們訪問第三個地址會報403錯誤,其原因是瀏覽器在我們使用user登錄時緩存了user的登錄會話信息即session狀態(tài),所以當(dāng)我們登錄第三個地址時瀏覽器會以user的登錄狀態(tài)去訪問admin角色下的接口,顯然這是訪問不到的。
基于注解的方式實現(xiàn)對接口中方法的權(quán)限認(rèn)證
首先在SecurityConfig配置類中添加@EnableGlobalMethodSecurity(prePostEnabled = true) 注解開啟該功能
@Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) //開啟基于方法的注解權(quán)限認(rèn)證,默認(rèn)為false public class SecurityConfig extends WebSecurityConfigurerAdapter {
然后我們就可以在想要進行權(quán)限校驗的方法上使用@PreAuthorize("hasAuthority('ROLE_user')")或者@PreAuthorize("hasRole('user')")進行相應(yīng)的權(quán)限校驗了。
特別說明:
hasRole和hasAuthority基本上沒有區(qū)別,主要差異在于hasRole會在我們添加的角色名稱前添加ROLE_前綴,所以在數(shù)據(jù)庫中的權(quán)限字符串需要加上 ROLE_ 前綴。
即數(shù)據(jù)庫中存儲的用戶角色如果是 ROLE_admin,這里就是 admin。hasAuthority和數(shù)據(jù)庫一樣就行
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用SpringBoot配置多數(shù)據(jù)源的經(jīng)驗分享
這篇文章主要介紹了使用SpringBoot配置多數(shù)據(jù)源的經(jīng)驗分享,本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04idea創(chuàng)建spring boot項目及java版本只能選擇17和21的問題
這篇文章主要介紹了idea創(chuàng)建spring boot項目及java版本只能選擇17和21的問題,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01Spring?Cloud?Hystrix?服務(wù)降級限流策略詳解
這篇文章主要為大家介紹了Spring?Cloud?Hystrix?服務(wù)降級限流策略詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01