一分鐘帶你瞭解下Spring Security!
一、什麼是Spring Security?
Spring Security是一個功能強大且高度可定製的身份驗證和訪問控制框架,它是用於保護基於Spring的應用程式的實際標準。
Spring Security是一個框架,致力於為Java應用程式提供身份驗證和授權。與所有Spring專案一樣,Spring Security的真正強大之處在於可以輕鬆擴充套件以滿足自定義要求。
更多資訊可以檢視官網:https://spring.io/projects/spring-security
二、Spring Security的主要功能
- 認證:驗證使用者名稱和密碼是否合法(是否系統中使用者)
- 授權:是系統使用者不代表你能使用某些功能,因為你可能沒有許可權
- 防禦會話固定,點選劫持,跨站點請求偽造等攻擊
- Servlet API整合
- 與Spring Web MVC的可選整合
三、快速入門
新建一個SpringBoot的web專案spring-boot-security。
案例1:介面不新增保護
pom檔案中不引入Spring Security,然後新建一個controller:
@RestController public class AppController { @GetMapping("/hello") public String hello() { return "Hello,spring security!"; } }
然後開啟瀏覽器訪問:http://localhost:8080/hello,成功後返回:
Hello,spring security!
案例2:介面新增保護
- pom檔案新增依賴
pom檔案中引入Spring Security的starter:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
- 訪問介面
開啟瀏覽器再次訪問http://localhost:8080/hello,會被重定向到登入頁http://localhost:8080/login,截圖如下:
要登入系統,我們需要知道使用者名稱和密碼,Spring Security預設的使用者名稱是user,專案啟動的時候會生成預設密碼(在啟動日誌中可以看到),輸入使用者名稱和密碼後就可以訪問/hello介面了。
當然也可以自定義使用者名稱密碼,在配置檔案新增如下內容即可:
spring.security.user.name=java_suisui
spring.security.user.password=123456
四、自定義認證和授權
上面說過Spring Security的功能有“認證”和“授權”,下面通過一個簡單的例子實現下自定義的認證和授權。
假設系統中有兩個角色:
- ADMIN 可以訪問/admin下的資源
- USER 可以訪問/user下的資源
按照下面步驟操作即可。
- 新建一個配置類
對於使用者名稱、密碼、登入頁面、訪問許可權等都可以在 WebSecurityConfigurerAdapter 的實現類中配置。
WebSecurityConfig程式碼如下:
/**
* 配置類
* @Author java_suisui
*
*/
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//配置記憶體中的 使用者名稱、密碼和角色
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("user").password("123456").roles("USER");
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("admin").password("123456").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/user").hasRole("USER") //訪問 /user這個介面,需要有USER角色
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated() //剩餘的其他介面,登入之後就能訪問
.and()
.formLogin().defaultSuccessUrl("/hello");
}
}
- 建立PasswordEncorder的實現類
記憶體使用者驗證時,Spring Boot 2.0以上版本引用的security 依賴是 spring security 5.X版本,此版本需要提供一個PasswordEncorder的例項。
MyPasswordEncoder程式碼如下:
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(rawPassword);
}
}
- 登入驗證
瀏覽器開啟http://localhost:8080/login,
- 使用user登入,可以訪問/user
- 使用admin登入,可以訪問/admin
如果使用user登入後訪問/admin,會報403錯誤,具體錯誤資訊如下:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Nov 19 16:26:28 CST 2019
There was an unexpected error (type=Forbidden, status=403).
Forbidden
結果和我們預期的一致,說明簡單的自定義認證和授權功能已經實現了。
完整原始碼地址: https://github.com/suisui2019/springboot-study
推薦閱讀
1.一分鐘帶你學會利用mybatis-generator自動生成程式碼!
2.手把手帶你實戰下Spring的七種事務傳播行為
3.SpringBoot系列-整合Mybatis(註解方式)
4.SpringBoot系列-整合Mybatis(XML配置方式)
5.Java中列印日誌,這4點很重要!
Java碎碎念,一個堅持原創的公眾號,為您提供一系列系統架構、微服務、Java、SpringBoot、SpringCloud等高質量技術文章。
如果覺得文章不錯,希望可以隨手轉發或者”在看“哦,非常感謝哈!
關注下方公眾號後回覆「1024」,有驚喜哦!
本文由部落格一文多發平臺 OpenWrite 釋出!