一、什么是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. There was an unexpected error (type=Forbidden, status=403). Forbidden
結果和我們預期的一致,說明簡單的自定義認證和授權功能已經實現了。