一分鐘帶你了解下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:接口添加保護



  1. pom文件添加依賴


pom文件中引入Spring Security的starter:


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>


  1. 訪問接口


打開瀏覽器再次訪問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下的資源


按照下面步驟操作即可。



  1. 新建一個配置類


對於用戶名、密碼、登錄頁面、訪問權限等都可以在 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");
}
}


  1. 創建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);
}
}


  1. 登錄驗證


瀏覽器打開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

結果和我們預期的一致,說明簡單的自定義認證和授權功能已經實現了。


完整源碼地址:


推薦閱讀








Java碎碎念,一個堅持原創的公眾號,為您提供一系列系統架構、微服務、Java、SpringBoot、SpringCloud等高質量技術文章。
如果覺得文章不錯,希望可以隨手轉發或者"在看"哦,非常感謝哈!
關注下方公眾號后回復「1024」,有驚喜哦!





本文由博客一文多發平台 發布!


本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※帶您來了解什麼是 USB CONNECTOR  ?



※自行創業 缺乏曝光? 下一步"網站設計"幫您第一時間規劃公司的門面形象



※如何讓商品強力曝光呢? 網頁設計公司幫您建置最吸引人的網站,提高曝光率!!



※綠能、環保無空污,成為電動車最新代名詞,目前市場使用率逐漸普及化



※廣告預算用在刀口上,網站設計公司幫您達到更多曝光效益



※試算大陸海運運費!




Orignal From: 一分鐘帶你了解下Spring Security!

留言