SpringBoot使用篇---SpringBoot整合springSecurity

在這裏插入圖片描述

目錄:

   前言
   SpringBoot整合SpringSecurity
   總結
   
分享與交流html

前言

   安全是項目運行的重要保障,每個項目在公測以前都會進行嚴格的認證和受權,阻擋惡意請求,保護項目安全。儘管如此,咱們依然有時候能聽到某某公司數據泄露,某某公司有重大Bug,因此安全驗證就變得愈來愈重要,是咱們在項目中須要考慮的重要因素。
   Java領域經常使用的安全框架有Shiro和SpringBoot。Shiro擁有輕量級的特性從而被普遍使用,但它是第三方框架;Spring Security是一個相對重量級的安全框架,經過名字咱們應該也能看到,它是Spring官方的框架,所以在整合方面要佔有必定的優點,並且它的功能比Shiro強大些,只要Shiro能實現通常它都能實現。同時SpringBoot提供了自動化配置,作到了開箱即用,所以Spring Security相對來講是Java領域安全框架的最優選擇之一。java

SpringBoot整合SpringSecurity

  具體步驟以下👇
(1)SpringBoot工程如何搭建能夠參考SpringBoot框架搭建
(2)引入SpringBoot相關依賴web

<parent>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-parent</artifactId>
	        <version>2.2.4.RELEASE</version>
	        <relativePath/> <!-- lookup parent from repository --> </parent>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.23</version>
        </dependency>

(3)引入SpringSecurity依賴spring

<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

(4)配置SpringBoot配置文件數據庫

#注意每一個屬性名和屬性值之間至少一個空格,註釋使用#不是//
spring:
  thymeleaf:
    prefix: classpath:/templates/ #前綴
    suffix: .html #後綴
    servlet:
      content-type: text/html #在請求中,客戶端告訴服務端實際請求的內容
                              #在響應中,服務端告訴請求端實際響應的內容
    encoding: utf-8 #設置編碼格式
    mode: HTML  #校驗HTML格式
    cache: false #關閉緩存,在開發過程當中可當即看到修改後的結果

(5)建立Handler緩存

@Controller
@RequestMapping("security")
public class SecurityController {

    @RequestMapping("add")
    public String add(){
        return "add";
    }

    @RequestMapping("update")
    public String update(){
        return "update";
    }

    @RequestMapping("find")
    public String find(){
        return "find";
    }

    @RequestMapping("delete")
    public String delete(){
        return "delete";
    }
}
@RequestMapping("index")
    public String index(){
        return "index";
    }

    @RequestMapping("error403")
    public String forbidden(){
        return "error403";
    }
    
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

(6)建立相對應頁面
index.html安全

<body>
<a href="/security/add">添加功能</a>
<a href="/security/update">修改功能</a>
<a href="/security/find">查詢功能</a>
<a href="/security/delete">刪除功能</a>
</body>

add.htmlmvc

<body>
添加功能頁面
</body>

find.htmlapp

<body>
查找功能頁面
</body>

delete.html框架

<body>
刪除功能頁面
</body>

update.html

<body>
刪除功能頁面
</body>

login.html

<body>
<form action="/login" method="post">
    用戶名:<input type="text" name="userName"><br/>
    密碼:<input type="password" name="password"><br/>
    <input type="submit" value="登陸">
</form>
</body>

(7)一個簡單的mvc就完成了,咱們繼續實現SpringSecurity
建立SpringSecurityConfig

@Configuration
@EnableWebSecurity //啓動SpringSecurity過濾器鏈
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    //該方法做用是代替配置文件中配置的<security:authentication-manager>
    /* <security:authentication-manager>用於配置對用戶輸入密碼進行加密並與數據庫密碼進行配對 */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //若是程序報錯There is no PasswordEncoder mapped for the id "null",就將該段註釋添加下邊代碼
        //或者在MyPasswordEncoder類上加一個@Component註解,使它成爲一個Bean
        auth.inMemoryAuthentication().withUser("admin").password("123456").authorities("ADMIN_ADD","ADMIN_FIND");//自定義登陸用戶用戶名和密碼並賦予一些權限

        //上邊代碼若是使程序報錯,就更換如下代碼,這個是使用了匿名內部類
        //auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("lxy").password("lxy").authorities("ADMIN_ADD","ADMIN_FIND");
    }

    /*該方法做用是代替配置文件中配置的<security:http>標籤 <security:http> 用來配置攔截資源--攔截什麼資源,須要什麼樣的身份進行訪問 自定義spring security攔截器 權限不足的處理 ReadMe功能 */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/security/add").hasAuthority("ADMIN_ADD") //ADMIN_ADD身份用戶可訪問/security/add頁面
                    .antMatchers("/security/find").hasAuthority("ADMIN_FIND")
                    .antMatchers("/security/update").hasAuthority("ADMIN_UPDATE")
                    .antMatchers("/security/delete").hasAuthority("ADMIN_DELETE")
                    .antMatchers("/login").permitAll() //login頁面不攔截,任何權限均可訪問login頁面
                    .antMatchers("/**") //表明攔截全部的訪問請求
                    .fullyAuthenticated()
                    .and()
                    .formLogin()  //登錄頁面是springSecurity默認的  .formLogin().loginPage("/login")自定義登錄頁面  也可設置爲 .httpBasic()  登錄頁面是彈窗框
                    .and()
                    .csrf().disable(); //關閉跨站請求攔截
    }
}

(8)建立MyPasswordEncoder

@Component
public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence.toString());
    }
}

(9)建立錯誤頁面處理類ErrorPageConfig
   環境是基於SpringBoot2.0以上版本,如下版本是繼承mbeddedServletContainerCustomizer

@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {


    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage error403Page=new ErrorPage(HttpStatus.FORBIDDEN,"/error403");
        registry.addErrorPages(error403Page);
    }
}

(10)配置SpringBoot啓動類

@SpringBootApplication
@MapperScan("cn.lxy.spring_boot1.repository")
public class SpringBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot1Application.class, args);
    }

}

(11)測試
   訪問localhost:8080/index
在這裏插入圖片描述
   頁面被攔截自動跳轉到登錄頁面,登錄頁面是SpringSecurity默認的登錄頁面,也可自定義登錄頁面。
在這裏插入圖片描述
   帳號或密碼輸入錯誤,登錄失敗
在這裏插入圖片描述
   輸入上邊咱們設置好的admin/123456,進入localhost:8080/index
在這裏插入圖片描述
   訪問添加功能查詢功能
在這裏插入圖片描述
在這裏插入圖片描述
   訪問修改功能刪除功能
在這裏插入圖片描述
在這裏插入圖片描述

總結

   以上是SpringBoot整合SpringSecurity的簡單使用,SpringSecurity還有不少須要學習的地方。相比於Shiro,Spring Security因其是Spring全家桶中的一員,所以能夠和Spring應用無縫銜接,使用起來會更加方便,系統安全是項目運行的重中之重,使用Spring Security進行管理,能夠對訪問權限進行認證,從而提升項目的安全性。

分享與總結

   因爲能力有限,博客總結不免有不足,還請大佬們不吝賜教😄