springSecurity實現簡單的登錄功能
前言
1、不使用數據庫,實現一個簡單的登錄功能,只有在登錄后才能訪問我們的接口
2、springSecurity提供了一種基于內存的驗證方法(使用自己定義的用戶,不使用默認的)
一、實現用戶創(chuàng)建,登陸后才能訪問接口(注重用戶認證)
1.定義一個內存用戶,不使用默認用戶
重寫configure(AuthenticationManagerBuilder auth)方法,實現在內存中定義一個 (用戶名/密碼/權限:admin/123456/admin) 的用戶
package com.example.springsecurity; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { ? ? @Override ? ? protected void configure(AuthenticationManagerBuilder auth) throws Exception { ? ? ? ? //基于內存的驗證方法 ? ? ? ? auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); ? ? } ? ? @Override ? ? public void configure(WebSecurity web) throws Exception { ? ? ? ? ? ? //批處理靜態(tài)資源,都不攔截處理 ? ? ? ? web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); ? ? } ? ? @Override ? ? protected void configure(HttpSecurity http) throws Exception { ? ? ? // 這是一個重要的方法,這個方法決定了我們哪些請求會被攔截以及一些請求該怎么處理 ? ? ? ? http.authorizeRequests() ?//安全過濾策略 ? ? ? ? ? ? ? ? .antMatchers("/").permitAll() ? ? ? ? ? ? ? ? .anyRequest().authenticated() ? ? ? ? ? ? ? ? .and() //and添加允許別的操作 ? ? ? ? ? ? ? ? .logout().permitAll() //允許支持注銷,支持隨意訪問 ? ? ? ? ? ? ? ? .and() ? ? ? ? ? ? ? ? .formLogin(); ? //允許表單登錄 ? ? ? ? http.csrf().disable(); ?//關閉csrf認證 ? ? } }
2.效果
根目錄可以直接通過驗證,其他接口需要經過springSecurity,輸入admin 123456后登陸系統(tǒng)
3.退出登陸
地址欄輸入:http://localhost:8080/login?logout,執(zhí)行退出登陸
4.再創(chuàng)建一個張三用戶,同時支持多用戶登陸
package com.example.springsecurity; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { ? ? @Override ? ? protected void configure(AuthenticationManagerBuilder auth) throws Exception { ? ? ? ? //基于內存的驗證方法 ? ? ? ? auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); ? ? ? ? auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin"); ? ? } ? ? @Override ? ? public void configure(WebSecurity web) throws Exception { ? ? ? ? ? ? //批處理靜態(tài)資源,都不攔截處理 ? ? ? ? web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); ? ? } ? ? @Override ? ? protected void configure(HttpSecurity http) throws Exception { ? ? ? // 這是一個重要的方法,這個方法決定了我們哪些請求會被攔截以及一些請求該怎么處理 ? ? ? ? http.authorizeRequests() ?//安全過濾策略 ? ? ? ? ? ? ? ? .antMatchers("/").permitAll() ? ? ? ? ? ? ? ? .anyRequest().authenticated() ? ? ? ? ? ? ? ? .and() //and添加允許別的操作 ? ? ? ? ? ? ? ? .logout().permitAll() //允許支持注銷,支持隨意訪問 ? ? ? ? ? ? ? ? .and() ? ? ? ? ? ? ? ? .formLogin(); ? //允許表單登錄 ? ? ? ? http.csrf().disable(); ?//關閉csrf認證 ? ? } }
二、實現管理員功能(注重權限控制)
實現角色功能,不同角色擁有不同功能:管理員擁有管理功能,而普通組員只能擁有最普通的功能
1.創(chuàng)建一個普通用戶demo
auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");
創(chuàng)建demo用戶,角色為demo,詳細代碼如下
package com.example.springsecurity; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { ? ? @Override ? ? protected void configure(AuthenticationManagerBuilder auth) throws Exception { ? ? ? ? //基于內存的驗證方法 ? ? ? ? auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); ? ? ? ? auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin"); ? ? ? ? auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user"); ? ? } ? ? @Override ? ? public void configure(WebSecurity web) throws Exception { ? ? ? ? ? ? //批處理靜態(tài)資源,都不攔截處理 ? ? ? ? web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); ? ? } ? ? @Override ? ? protected void configure(HttpSecurity http) throws Exception { ? ? ? // 這是一個重要的方法,這個方法決定了我們哪些請求會被攔截以及一些請求該怎么處理 ? ? ? ? http.authorizeRequests() ?//安全過濾策略 ? ? ? ? ? ? ? ? .antMatchers("/").permitAll() ? ? ? ? ? ? ? ? .anyRequest().authenticated() ? ? ? ? ? ? ? ? .and() //and添加允許別的操作 ? ? ? ? ? ? ? ? .logout().permitAll() //允許支持注銷,支持隨意訪問 ? ? ? ? ? ? ? ? .and() ? ? ? ? ? ? ? ? .formLogin(); ? //允許表單登錄 ? ? ? ? http.csrf().disable(); ?//關閉csrf認證 ? ? } }
2.創(chuàng)建/roleAuth接口
此接口只能admin角色才能登陸
1)、@EnableGlobalMethodSecurity注解使role驗證注解生效
2)、@PreAuthorize(“hasRole(‘ROLE_admin’)”)注解聲明哪個角色能訪問此接口
package com.example.springsecurity; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication @EnableGlobalMethodSecurity(prePostEnabled = true) ?//必須加這行,不然role驗證無效 public class SpringsecurityApplication { ? ? public static void main(String[] args) { ? ? ? ? SpringApplication.run(SpringsecurityApplication.class, args); ? ? } ? ? @RequestMapping("/") ? ? public String home(){ ? ? ? ? return "hello spring boot"; ? ? } ? ? @RequestMapping("/hello") ? ? public String hello(){ ? ? ? ? return "hello word"; ? ? } ? ? @PreAuthorize("hasRole('ROLE_admin')") ?//當我們期望這個方法經過role驗證的時候,需要加這個注解;ROLE必須大寫 ? ? @RequestMapping("/roleAuth") ? ? public String role(){ ? ? ? ? return "admin ?Auth"; ? ? } }
3.效果
demo用戶登陸成功可以訪問/接口,但是不能訪問/roleAuth接口
admin管理員既能訪問/接口,也能訪問/roleAuth接口
三、實現數據庫管理用戶(注重數據庫認證用戶)
1.我們需要把之前創(chuàng)建的admin zhangsan demo三個用戶放到數據庫中 2.我們需要使用MyUserService來管理這些用戶
1.創(chuàng)建一個MyUserService類
1.此類實現UserDetailsService(這邊不真實查詢數據庫)
package com.example.springsecurity; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; @Component public class MyUserService implements UserDetailsService { ? ? @Override ? ? public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { ? ? ? ? return null;//數據庫操作邏輯 ? ? } }
2.密碼自定義驗證類
1.此類實現自定義密碼驗證
package com.example.springsecurity; import org.springframework.security.authentication.encoding.Md5PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; public class MyPasswdEncoder implements PasswordEncoder { ? ? private final static String SALT = "123456"; ? ? @Override ? ? public String encode(CharSequence rawPassword) { ? ? ? ? //加密:堆原始的密碼進行加密,這邊使用md5進行加密 ? ? ? ? Md5PasswordEncoder encoder = new Md5PasswordEncoder(); ? ? ? ? return encoder.encodePassword(rawPassword.toString(), SALT); ? ? } ? ? @Override ? ? public boolean matches(CharSequence rawPassword, String encodedPassword) { ? ? ? ? //拿原始的密碼和加密后的密碼進行匹配 ? ? ? ? Md5PasswordEncoder encoder = new Md5PasswordEncoder(); ? ? ? ? return encoder.isPasswordValid(encodedPassword,rawPassword.toString(),SALT); ? ? } }
3.自定義數據庫查詢&默認數據庫查詢、自定義密碼驗證配置
1.支持自定義數據庫查詢 2.支持默認數據庫查詢(數據庫結構必須和默認的一致) 兩者選擇其中一個
package com.example.springsecurity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.stereotype.Component; @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { ? ? @Autowired ? ? MyUserService myUserService; ? ? @Override ? ? protected void configure(AuthenticationManagerBuilder auth) throws Exception { ? ? ? ? //基于內存的驗證方法 // ? ? ? ?auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin"); // ? ? ? ?auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin"); // ? ? ? ?auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user"); ? ? ? ? //1、自己實現數據庫的查詢,指定我們要使用的UserService和自定義的密碼驗證器 ? ? ? ? auth.userDetailsService(myUserService).passwordEncoder(new MyPasswdEncoder()); ? ? ? ? //2、sprinSecurity在數據庫管理方面支持一套默認的處理,可以指定根據用戶查詢,權限查詢,這情況下用戶表必須和默認的表結構相同,具體查看user.ddl文件 ? ? ? ? auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(new MyPasswdEncoder()); ? ? } ? ? @Override ? ? public void configure(WebSecurity web) throws Exception { ? ? ? ? ? ? //批處理靜態(tài)資源,都不攔截處理 ? ? ? ? web.ignoring().mvcMatchers("/js/**","/css/**","/images/**"); ? ? } ? ? @Override ? ? protected void configure(HttpSecurity http) throws Exception { ? ? ? // 這是一個重要的方法,這個方法決定了我們哪些請求會被攔截以及一些請求該怎么處理 ? ? ? ? http.authorizeRequests() ?//安全過濾策略 ? ? ? ? ? ? ? ? .antMatchers("/").permitAll() ? ? ? ? ? ? ? ? .anyRequest().authenticated() ? ? ? ? ? ? ? ? .and() //and添加允許別的操作 ? ? ? ? ? ? ? ? .logout().permitAll() //允許支持注銷,支持隨意訪問 ? ? ? ? ? ? ? ? .and() ? ? ? ? ? ? ? ? .formLogin(); ? //允許表單登錄 ? ? ? ? http.csrf().disable(); ?//關閉csrf認證 ? ? } }
四、sprinSecurity支持的4種使用表達式的權限注解
1.支持的4種注解
@PreAuthorize("hasRole('ROLE_admin')") ?//1.方法調用前:當我們期望這個方法經過role驗證的時候,需要加這個注解;ROLE必須大寫 ? ? @PostAuthorize("hasRole('ROLE_admin')")//2.方法調用后 ? ? @PreFilter("")//2.對集合類的參數或返回值進行過濾 ? ? @PostFilter("")//2.對集合類的參數或返回值進行過濾 ? ? @RequestMapping("/roleAuth") ? ? public String role(){ ? ? ? ? return "admin ?Auth"; ? ? }
2.注解的參數該怎么傳
or用法:
參數的值判斷
and運算
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- springsecurity實現用戶登錄認證快速使用示例代碼(前后端分離項目)
- springsecurity記住我登錄時訪問無權限接口跳轉登錄界面的處理方案
- SpringSecurity自定義資源攔截規(guī)則及登錄界面跳轉問題
- 解決springSecurity 使用默認登陸界面登錄后無法跳轉問題
- SpringSecurity表單配置之登錄成功及頁面跳轉原理解析
- SpringSecurity?默認登錄認證的實現原理解析
- SpringSecurity默認登錄頁的使用示例教程
- SpringSecurityOAuth2實現微信授權登錄
- SpringSecurity實現前后端分離登錄token認證詳解
- SpringSecurity自定義登錄成功處理
- SpringSecurity多表多端賬戶登錄的實現
相關文章
Java日志logback的使用配置和logback.xml解讀
這篇文章主要介紹了Java日志logback的使用配置和logback.xml解讀,具有很好的價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06SpringBoot整合SpringSecurity實現JWT認證的項目實踐
本文會通過創(chuàng)建SpringBoot項目整合SpringSecurity,實現完整的JWT認證機制,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07如何理解Java中基類子對象的構建過程從"基類向外"進行擴散的?
今天小編就為大家分享一篇關于如何理解Java中基類子對象的構建過程從"基類向外"進行擴散的?,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-04-04Java畢業(yè)設計實戰(zhàn)之在線高中考試系統(tǒng)的實現
這是一個使用了java+SSM+Jsp+Mysql+Maven開發(fā)的在線高中考試系統(tǒng),是一個畢業(yè)設計的實戰(zhàn)練習,具有考試系統(tǒng)該有的所有功能,感興趣的朋友快來看看吧2022-02-02