在springboot中使用springsecurity实现安全控制
SpringSecurity官方文檔
我們?cè)诰帉?xiě)web應(yīng)用時(shí)經(jīng)常要對(duì)一些頁(yè)面做安全控制,比如:對(duì)于沒(méi)有訪問(wèn)權(quán)限的用戶需要轉(zhuǎn)到登錄表單頁(yè)面。要實(shí)現(xiàn)訪問(wèn)控制方法的多種多樣,可以通過(guò)AOP、攔截器實(shí)現(xiàn),也可以通過(guò)框架實(shí)現(xiàn)(如:Apache shiro、spring security)。
本文主要學(xué)習(xí)一下在springboot中使用springsecurity實(shí)現(xiàn)安全控制。
定義控制層controller:
@Controller public class HelloController {@RequestMapping("/")public String index() {return "index"; //映射到首頁(yè)index.html}@RequestMapping("/hello")public String hello() {return "hello"; //映射到hello.html頁(yè)面}@RequestMapping("/login")public String login() {return "login"; //映射到login.html} }添加pom依賴
<!-- spring security依賴 --> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId> </dependency>spring security的配置類
package com.example.springboottest;import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;/*** spring security的配置類* @author: liumengbing* @date: 2019/04/23 14:16**/ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/","/home").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");} }- 1、通過(guò) @EnableWebSecurity注解開(kāi)啟Spring Security的功能
- 2、繼承WebSecurityConfigurerAdapter,并重寫(xiě)它的方法來(lái)設(shè)置一些web安全的細(xì)節(jié)
- 1)configure(HttpSecurity http)方法
通過(guò)authorizeRequests()定義哪些URL需要被保護(hù)、哪些不需要被保護(hù)。例如以上代碼指定了/和/home不需要任何認(rèn)證就可以訪問(wèn),其他的路徑都必須通過(guò)身份驗(yàn)證。
通過(guò)formLogin()定義當(dāng)需要用戶登錄時(shí)候,轉(zhuǎn)到的登錄頁(yè)面。 - 2)configure(AuthenticationManagerBuilder auth)方法,在內(nèi)存中創(chuàng)建了一個(gè)用戶,該用戶的名稱為user,密碼為password,用戶角色為USER。
- 1)configure(HttpSecurity http)方法
根據(jù)配置,spring security提供了一個(gè)過(guò)濾器來(lái)攔截請(qǐng)求并驗(yàn)證用戶身份。如果用戶沒(méi)有進(jìn)行身份認(rèn)證,直接訪問(wèn)index頁(yè)面,頁(yè)面則會(huì)重定向到login登錄頁(yè)面,提示用戶進(jìn)行登錄;如果用戶身份認(rèn)證失敗,頁(yè)面就重定向到/login?error,并且頁(yè)面中會(huì)展現(xiàn)相應(yīng)的錯(cuò)誤信息。
幾行簡(jiǎn)單的配置就實(shí)現(xiàn)我們需要的功能,由此可見(jiàn)spring security還是相當(dāng)強(qiáng)大的。下面我們來(lái)詳細(xì)學(xué)習(xí)一下上面spring security的配置類。
WebSecurityConfigurerAdapter
在這個(gè)配置類中最主要的就是WebSecurityConfigurerAdapter這個(gè)類,這個(gè)類下面有很多方法
WebSecurityConfigurerAdapter在configure( HttpSecurity http)方法中提供了一個(gè)默認(rèn)的配置,如下:
- 1、authorizeRequests()配置路徑攔截,表明路徑訪問(wèn)所對(duì)應(yīng)的權(quán)限,角色,認(rèn)證信息。
- 2、formLogin()對(duì)應(yīng)表單認(rèn)證相關(guān)的配置
- 3、httpBasic()可以配置basic登錄
這是一個(gè)使用java configuration配置HTTPSecurity 的典型配置,其中http作為根開(kāi)始配置,每一個(gè)and()對(duì)應(yīng)了一個(gè)模塊的配置(等同于xml配置中的結(jié)束標(biāo)簽)
回到我們最開(kāi)始的spring security的配置類中的配置,除了“/”,”/home”(首頁(yè)),”/login”(登錄),”,之外,其他路徑都需要認(rèn)證。并且指定“/login”該路徑為登錄頁(yè)面,當(dāng)未登錄的用戶嘗試訪問(wèn)任何受保護(hù)的資源時(shí),都會(huì)跳轉(zhuǎn)到“/login”。
@EnableWebSecurity
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) @Target(value = { java.lang.annotation.ElementType.TYPE }) @Documented @Import({ WebSecurityConfiguration.class,SpringWebMvcImportSelector.class }) @EnableGlobalAuthentication @Configuration public @interface EnableWebSecurity {/*** Controls debugging support for Spring Security. Default is false.* @return if true, enables debug support with Spring Security*/boolean debug() default false; }@EnableWebSecurity 是一個(gè)組合注解,其中 @Import是springboot提供的用于引入外部的配置的注解,可以理解為: @EnableWebSecurity注解激活了@Import注解中包含的配置類。
- 1、SpringWebMvcImportSelector的作用是判斷當(dāng)前的環(huán)境是否包含springmvc,因?yàn)閟pring security可以在非spring環(huán)境下使用,為了避免DispatcherServlet的重復(fù)配置,所以使用了這個(gè)注解來(lái)區(qū)分。
- 2、WebSecurityConfiguration顧名思義,是用來(lái)配置web安全的
- 3、@EnableGlobalAuthentication注解的源碼如下
@EnableWebSecurity完成的工作便是加載了WebSecurityConfiguration,AuthenticationConfiguration這兩個(gè)核心配置類,也就此將spring security的職責(zé)劃分為了配置安全信息,配置認(rèn)證信息兩部分。
其中,WebSecurityConfiguration是spring security的核心過(guò)濾器(使用了代理模式來(lái)實(shí)現(xiàn)安全過(guò)濾),AuthenticationConfiguration主要實(shí)現(xiàn)了認(rèn)證機(jī)制相關(guān)的內(nèi)容。
超強(qiáng)干貨來(lái)襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的在springboot中使用springsecurity实现安全控制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何在项目启动时就执行某些操作
- 下一篇: 使用HttpMessageConvert