01 springboot+spring security

spring security

官網介紹
security是一款用於認證和授權模塊的代碼,對web應用提供防護支持。具體的請查看官網內容。

引入spring-security

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

引入後默認自動開發了安全驗證
測試

package com.example.securitydemo01.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * *@ClassName homeController
 * *@Author yyc
 * *@Date 2020/5/20 11:34
 **/
@RestController
public class homeController {

    @GetMapping("/")
    public String Index(){
        return "home";
    }
}

訪問localhost:8081/ 彈出需要輸入驗證用戶和密碼
在這裏插入圖片描述
用戶名默認是user
密碼在控制檯輸出
在這裏插入圖片描述
輸入用戶和密碼後,轉到對應的url地址
在這裏插入圖片描述
可以看出,我們只要引入spring-security,就默認開啓了表單驗證。
在這裏插入圖片描述
如果使用簡單的驗證,需要手動配置

package com.example.securitydemo01.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * *@ClassName webSecurityConfig
 * *@Author yyc
 * *@Date 2020/5/20 14:37
 **/
@Configuration
public class webSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected  void configure(HttpSecurity http) throws  Exception{
        http.httpBasic()//簡單認證
                .and()
                .authorizeRequests()//授權配置
                .anyRequest()//所有請求
                .authenticated();//都需要認證
    }
}

如果想要實現表單驗證,需要將httpBasic改成formlogin

 @Override
    protected  void configure(HttpSecurity http) throws  Exception{
        http.formLogin()//表單認證
                .and()
                .authorizeRequests()//授權配置
                .anyRequest()//所有請求
                .authenticated();//都需要認證
    }

原理

表單驗證流程
在這裏插入圖片描述

  1. 首先用戶發送一個未授權的請求來獲取一個未授權的資源。比如訪問localhost:8082/
  2. spring-security的安全過濾攔截器檢測到當前的請求是未授權的,然後拋出一個AccessDeniedException錯誤
  3. 只要檢測到用戶點擊是未授權的,ExceptionTranslationFilter初始開始授權的程序,併發送一個login請求
  4. 瀏覽器響應login.html頁面
  5. 用戶輸入用戶名和密碼登錄到應用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章