一、前言
Spring Security
和 Apache Shiro
都是安全框架,為Java應用程序提供身份認證和授權。
二者區別
- Spring Security:
重
量級安全框架 - Apache Shiro:
輕
量級安全框架
關於shiro的權限認證與授權可參考小編的另外一篇文章 : SpringBoot集成Shiro 實現動態加載權限
二、SpringBoot集成Spring Security入門體驗
基本環境 : springboot 2.1.8
1、引入Spring Security依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、新建一個controller測試訪問
@RestController
public class IndexController {
@GetMapping("/index")
public String index() {
return "Hello World ~";
}
}
3、運行項目訪問 http://127.0.0.1:8080/index
溫馨小提示:在不進行任何配置的情況下,Spring Security 給出的默認用戶名為user
密碼則是項目在啟動運行時隨機生成的一串字符串,會打印在控制台,如下圖:
當我們訪問index首頁的時候,系統會默認跳轉到login頁面進行登錄認證
認證成功之后才會跳轉到我們的index頁面
三、Spring Security用戶密碼配置
除了上面Spring Security在不進行任何配置下默認給出的用戶user
密碼隨項目啟動生成隨機字符串,我們還可以通過以下方式配置
1、springboot配置文件中配置
spring:
security:
user:
name: admin # 用戶名
password: 123456 # 密碼
2、java代碼在內存中配置
新建Security 核心配置類繼承WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity // 啟用Spring Security的Web安全支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 將用戶設置在內存中
* @param auth
* @throws Exception
*/
@Autowired
public void config(AuthenticationManagerBuilder auth) throws Exception {
// 在內存中配置用戶,配置多個用戶調用`and()`方法
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder()) // 指定加密方式
.withUser("admin").password(passwordEncoder().encode("123456")).roles("ADMIN")
.and()
.withUser("test").password(passwordEncoder().encode("123456")).roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
// BCryptPasswordEncoder:Spring Security 提供的加密工具,可快速實現加密加鹽
return new BCryptPasswordEncoder();
}
}
3、從數據庫中獲取用戶賬號、密碼信息
這種方式也就是我們項目中通常使用的方式,這個留到后面的文章再說
四、Spring Security 登錄處理 與 忽略攔截
相關代碼都有注釋相信很容易理解
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 登錄處理
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 開啟登錄配置
http.authorizeRequests()
// 標識訪問 `/index` 這個接口,需要具備`ADMIN`角色
.antMatchers("/index").hasRole("ADMIN")
// 允許匿名的url - 可理解為放行接口 - 多個接口使用,分割
.antMatchers("/", "/home").permitAll()
// 其余所有請求都需要認證
.anyRequest().authenticated()
.and()
// 設置登錄認證頁面
.formLogin().loginPage("/login")
// 登錄成功后的處理接口 - 方式①
.loginProcessingUrl("/home")
// 自定義登陸用戶名和密碼屬性名,默認為 username和password
.usernameParameter("username")
.passwordParameter("password")
// 登錄成功后的處理器 - 方式②
// .successHandler((req, resp, authentication) -> {
// resp.setContentType("application/json;charset=utf-8");
// PrintWriter out = resp.getWriter();
// out.write("登錄成功...");
// out.flush();
// })
// 配置登錄失敗的回調
.failureHandler((req, resp, exception) -> {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("登錄失敗...");
out.flush();
})
.permitAll()//和表單登錄相關的接口統統都直接通過
.and()
.logout().logoutUrl("/logout")
// 配置注銷成功的回調
.logoutSuccessHandler((req, resp, authentication) -> {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("注銷成功...");
out.flush();
})
.permitAll()
.and()
.httpBasic()
.and()
// 關閉CSRF跨域
.csrf().disable();
}
/**
* 忽略攔截
* @param web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
// 設置攔截忽略url - 會直接過濾該url - 將不會經過Spring Security過濾器鏈
web.ignoring().antMatchers("/getUserInfo");
// 設置攔截忽略文件夾,可以對靜態資源放行
web.ignoring().antMatchers("/css/**", "/js/**");
}
}
五、總結
- 項目引入Spring Security依賴
- 自定義Security核心配置類繼承
WebSecurityConfigurerAdapter
- 賬號密碼配置
- 登錄處理
- 忽略攔截