天天看點

SpringSecurity 入門

前言:

在web開發中,安全第一位!

功能性需求:否

做網站:安全應該在什麼時候考慮?設計之初!

  • 漏洞,隐私洩漏~
  • 架構一旦确定~

shiro,SpringSecurity:很像~除了類不一樣,名字不一樣;

認證,授權(vip1,vip2,vip3)

  • 功能權限
  • 通路權限
  • 菜單權限
  • …攔截器,過濾器:大量原生代碼~備援

SpringSecurity簡介

Spring Security是一個能夠為基于Spring的企業應用系統提供聲明式的安全通路控制解決方案的安全架構。

Spring Security對Web安全性的支援大量地依賴于Servlet過濾器。這些過濾器攔截進入請求,并且在應用程式處理該請求之前進行某些安全處理。 Spring Security提供有若幹個過濾器,它們能夠攔截Servlet請求,并将這些請求轉給認證和通路決策管理器處理,進而增強安全性。根據自己的需要,可以使用适當的過濾器來保護自己的應用程式。

資料來自百度百科~ SpringSecurity

記住幾個類:

  • WebSecurityConfigurationAdapter:自定義Security政策。
  • AuthenticationManagerBuilder:自定義認證政策
  • @EnableWebSecurity:開啟WbSercurity模式,@Enablexxx開啟某個功能

    Spring Security兩個重要目标"認證" “授權”(通路控制)

    “認證”(Authentication)

    “授權”(Authorization)

SpringSecurity環境配置

首頁,第一步還是導入依賴。這裡同時整合了thymeleaf。

<!--Spring security-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
 <!--thymeleaf依賴-->
 <dependency>
     <groupId>org.thymeleaf</groupId>
     <artifactId>thymeleaf-spring5</artifactId>
 </dependency>
 <dependency>
     <groupId>org.thymeleaf.extras</groupId>
     <artifactId>thymeleaf-extras-java8time</artifactId>
 </dependency>
 <dependency>
     <groupId>org.thymeleaf.extras</groupId>
     <artifactId>thymeleaf-extras-springsecurity5</artifactId>
 </dependency>
  <!--SpringBoot中使用thymeleaf功能可以直接用下面這個依賴-->
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-thymeleaf</artifactId>-->
<!--        </dependency>-->
  <!--thymeleaf整合springsecurity-->
           

SpringSecurity 使用者認證與授權

首先來看一下我們項目的初始分布

SpringSecurity 入門
SpringSecurity 入門

如上圖所示,我們将在views目錄下,給視圖分了等級level1、level2、level3。并提供了給前端的請求路徑。在沒有任何權限管理的情況下,隻要伺服器開啟,那麼前端使用者登入均可以通路這些頁面。以下使用Security進行授權與認證的案例。SecurityConfig為自定義類。

package com.kuang.config;

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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //首頁所有人可以通路,功能頁隻有對應有權限的人才能通路
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //請求授權的規則
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //設定沒有權限回到login頁面
        http.formLogin();
        //自定義登入頁面
//       http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login").usernameParameter("user").passwordParameter("pwd");

        //開啟登出功能,連結為 /logout
//        http.logout().deleteCookies("remove").invalidateHttpSession(false);
        http.logout().logoutUrl("/custom-logout").logoutSuccessUrl("/");//登出後的位址

        //添加記住我功能,儲存包含登入資訊的cookie。預設為兩周。
        http.rememberMe().rememberMeParameter("remember");
    }

    //認證,springboot 2.1.x可以直接使用
    //密碼編碼:PasswordEncoder
    //在Spring Security 5.0+ 新增了很多的加密方法~
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("tomcat").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2");
    }
}
           

登入頁面定制

<!DOCTYPE html>
<html lang="en"
    xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>定制登入頁面</h1>
<form th:action="@{/login}" method="post">
    <input type="text" name="user">
    <input type="password" name="pwd">
    <input type="submit" value="登入">
    記住我<input type="checkbox" name="remember">
</form>
</body>
</html>
           

首頁定制

<!DOCTYPE html>
<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" th:href="@{/css/index.css}"/>
</head>
<body>
<div class="nav-bar">
    <!--授權後不需要在登入-->
    <a th:href="@{/toLogin}" sec:authorize="!isAuthenticated()">登入</a>
<!--    <a th:href="@{/logout}" target="_blank" rel="external nofollow" >登出</a>-->
    <form th:action="@{/custom-logout}" method="post">
        <input type="submit" value="登出">
    </form>
    <span  sec:authorize="isAuthenticated()">
        使用者名:<i sec:authentication="name"></i>
        角色:<i sec:authentication="principal.authorities"></i>
    </span>
</div>
<div class="container">
 <div class="piece" sec:authorize="hasRole('vip1')">
     <p class="piece-title">等級:Level1</p>
     <div class="nav-link">
         <a th:href="@{/level1/1}">頁面1</a>
         <a th:href="@{/level1/2}">頁面2</a>
         <a th:href="@{/level1/3}">頁面3</a>
     </div>
 </div>
 <div class="piece" sec:authorize="hasRole('vip2')">
     <p class="piece-title">等級:Level2</p>
     <div class="nav-link">
         <a th:href="@{/level2/1}">頁面1</a>
         <a th:href="@{/level2/2}">頁面2</a>
         <a th:href="@{/level2/3}">頁面3</a>
     </div>
 </div>
 <div class="piece" sec:authorize="hasRole('vip3')">
     <p class="piece-title">等級:Level3</p>
     <div class="nav-link">
         <a th:href="@{/level3/1}">頁面1</a>
         <a th:href="@{/level3/2}">頁面2</a>
         <a th:href="@{/level3/3}">頁面3</a>
     </div>
 </div>
</div>
</body>
</html>
           

使用thymeleaf之前可以現在application.yaml配置檔案中關閉thymeleaf的緩存。

spring:
  thymeleaf:
    cache: false
           

Security項目案例 gitee倉庫

繼續閱讀