在springboot中使用springsecurity实现安全控制
SpringSecurity官方文檔
我們在編寫web應用時經常要對一些頁面做安全控制,比如:對于沒有訪問權限的用戶需要轉到登錄表單頁面。要實現訪問控制方法的多種多樣,可以通過AOP、攔截器實現,也可以通過框架實現(如:Apache shiro、spring security)。
本文主要學習一下在springboot中使用springsecurity實現安全控制。
定義控制層controller:
@Controller public class HelloController {@RequestMapping("/")public String index() {return "index"; //映射到首頁index.html}@RequestMapping("/hello")public String hello() {return "hello"; //映射到hello.html頁面}@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、通過 @EnableWebSecurity注解開啟Spring Security的功能
- 2、繼承WebSecurityConfigurerAdapter,并重寫它的方法來設置一些web安全的細節
- 1)configure(HttpSecurity http)方法
通過authorizeRequests()定義哪些URL需要被保護、哪些不需要被保護。例如以上代碼指定了/和/home不需要任何認證就可以訪問,其他的路徑都必須通過身份驗證。
通過formLogin()定義當需要用戶登錄時候,轉到的登錄頁面。 - 2)configure(AuthenticationManagerBuilder auth)方法,在內存中創建了一個用戶,該用戶的名稱為user,密碼為password,用戶角色為USER。
- 1)configure(HttpSecurity http)方法
根據配置,spring security提供了一個過濾器來攔截請求并驗證用戶身份。如果用戶沒有進行身份認證,直接訪問index頁面,頁面則會重定向到login登錄頁面,提示用戶進行登錄;如果用戶身份認證失敗,頁面就重定向到/login?error,并且頁面中會展現相應的錯誤信息。
幾行簡單的配置就實現我們需要的功能,由此可見spring security還是相當強大的。下面我們來詳細學習一下上面spring security的配置類。
WebSecurityConfigurerAdapter
在這個配置類中最主要的就是WebSecurityConfigurerAdapter這個類,這個類下面有很多方法
WebSecurityConfigurerAdapter在configure( HttpSecurity http)方法中提供了一個默認的配置,如下:
- 1、authorizeRequests()配置路徑攔截,表明路徑訪問所對應的權限,角色,認證信息。
- 2、formLogin()對應表單認證相關的配置
- 3、httpBasic()可以配置basic登錄
這是一個使用java configuration配置HTTPSecurity 的典型配置,其中http作為根開始配置,每一個and()對應了一個模塊的配置(等同于xml配置中的結束標簽)
回到我們最開始的spring security的配置類中的配置,除了“/”,”/home”(首頁),”/login”(登錄),”,之外,其他路徑都需要認證。并且指定“/login”該路徑為登錄頁面,當未登錄的用戶嘗試訪問任何受保護的資源時,都會跳轉到“/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 是一個組合注解,其中 @Import是springboot提供的用于引入外部的配置的注解,可以理解為: @EnableWebSecurity注解激活了@Import注解中包含的配置類。
- 1、SpringWebMvcImportSelector的作用是判斷當前的環境是否包含springmvc,因為spring security可以在非spring環境下使用,為了避免DispatcherServlet的重復配置,所以使用了這個注解來區分。
- 2、WebSecurityConfiguration顧名思義,是用來配置web安全的
- 3、@EnableGlobalAuthentication注解的源碼如下
@EnableWebSecurity完成的工作便是加載了WebSecurityConfiguration,AuthenticationConfiguration這兩個核心配置類,也就此將spring security的職責劃分為了配置安全信息,配置認證信息兩部分。
其中,WebSecurityConfiguration是spring security的核心過濾器(使用了代理模式來實現安全過濾),AuthenticationConfiguration主要實現了認證機制相關的內容。
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的在springboot中使用springsecurity实现安全控制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在项目启动时就执行某些操作
- 下一篇: 自定义Redis序列化工具