SpringBoot—Security
安全概念
Spring Security是針對Spring項目的安全框架,也是Spring Boot底層安全模塊默認的技術(shù)選型。他可以實現(xiàn)強大的web安全控制。對于安全控制,我們僅需引入spring-boot-starter-security模塊,進行少量的配置,即可實現(xiàn)強大的安全管理。
幾個類:
WebSecurityConfigurerAdapter:自定義Security策略
AuthenticationManagerBuilder:自定義認證策略
@EnableWebSecurity:開啟WebSecurity模式
- 應(yīng)用程序的兩個主要區(qū)域是“認證”和“授權(quán)”(或者訪問控制)。這兩個主要區(qū)域是Spring Security 的兩個目標(biāo)。
- “認證”(Authentication),是建立一個他聲明的主體的過程(一個“主體”一般是指用戶,設(shè)備或一些可以在你的應(yīng)用程序中執(zhí)行動作的其他系統(tǒng))
- “授權(quán)”(Authorization)指確定一個主體是否允許在你的應(yīng)用程序執(zhí)行一個動作的過程。為了抵達需要授權(quán)的店,主體的身份已經(jīng)有認證過程建立。
- 這個概念是通用的而不只在Spring Security中。
WEB&安全
-
登陸/注銷
HttpSecurity配置登陸、注銷功能 -
Thymeleaf提供的SpringSecurity標(biāo)簽支持
需要引入
thymeleaf-extras-springsecurity4sec:authentication=“name”獲得當(dāng)前用戶的用戶名sec:authorize=“hasRole(‘ADMIN’)”當(dāng)前用戶必須擁有ADMIN權(quán)限時才會顯示標(biāo)簽內(nèi)容 -
remember me
表單添加remember-me的checkbox
配置啟用remember-me功能
-
CSRF(Cross-site request forgery)跨站請求偽造
HttpSecurity啟用csrf功能,會為表單添加_csrf的值,提交攜帶來預(yù)防CSRF;
實例代碼
安全配置類
@EnableWebSecurity public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //super.configure(http); //定制請求的授權(quán)規(guī)則 http.authorizeRequests().antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("VIP1") .antMatchers("/level2/**").hasRole("VIP2") .antMatchers("/level3/**").hasRole("VIP3"); //開啟自動配置的登陸功能,效果,如果沒有登陸,沒有權(quán)限就會來到登陸頁面 http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin"); //1、 /login 來到登陸頁 //2、重定向到/login?error表示登陸失敗 //3、更多詳細功能 //4、默認post形式的 /login 代表處理登陸 //5、一旦定制loginPage 那么 loginPage的post請求就是登陸 //開啟自動配置的注銷功能 http.logout().logoutSuccessUrl("/"); //注銷成功以后來到首頁 //1、訪問/logout 表示用戶注銷。清空 session //2、注銷成功會返回 /login?logout 頁面 //3、默認post形式的 /login代表處理登陸 //開啟記住我功能 http.rememberMe().rememberMeParameter("remeber"); //登陸成功以后,將cookie發(fā)給瀏覽器保存,以后訪問頁面帶上這個cookie,只要通過檢查就可以免登陸 //點擊注銷會刪除cookie } //定義認證規(guī)則 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //super.configure(auth); //auth.jdbcAuthentication()... auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) //在Spring Security 5.0中新增了多種加密方式,頁改變了密碼的格式 .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2") .and() .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2", "VIP3") .and() .withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP3"); } }啟動類:
/** * 1、引入SpringSecurity; * 2、編寫SpringSecurity配置 * @EnableWebSecurity extends WebSecurityConfigurerAdapter * 3、控制請求的訪問權(quán)限 * */ @SpringBootApplication public class SecurityApplication { public static void main(String[] args) { SpringApplication.run(SecurityApplication.class, args); } }
學(xué)習(xí) 尚硅谷的springboot視頻security時 的學(xué)習(xí)筆記