java框架之SpringBoot(15)-安全及整合SpringSecurity

SpringSecurity介紹

Spring Security 是針對 Spring 項目的安全框架,也是 Spring Boot 底層安全模塊默認的技術選型。它能夠實現強大的 Web 安全控制。對於安全控制吧,咱們僅如引入 Security 場景啓動器,進行少許配置,便可實現強大的安全管理。html

應用程序安全的主要兩個區域就是「認證」和「受權」:html5

  • 認證(Authentication):創建一個聲明主體的過程,主體通常是指用戶。
  • 受權(Authorization):指肯定一個主體是否容許在你的應用程序執行一個動做的過程。

SpringSecurity with Boot 快速開始 | SpringSecurity 官方文檔java

整合SpringSecurity

  • WebSecurityConfigurerAdapter:自定義 Security 策略。
  • AuthenticationManagerBuilder:自定義認證策略。
  • @EnableWebSecurity:開啓 WebSecurity 模式。

一、使用 maven 新建 SpringBoot 項目,引入 Web、Thymeleaf、Security 場景啓動器,依賴以下:web

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.19.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>zze.spring</groupId>
    <artifactId>security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <!--修改 thymeleaf 依賴版本爲 3 -->
        <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
        <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--thymeleaf 模板中使用 springsecurity 標籤-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
pom.xml

二、編寫測試模板頁:spring

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
<div sec:authorize="!isAuthenticated()">
    <a th:href="@{/login}">請登陸</a>
</div>
<div sec:authorize="isAuthenticated()">
    <span sec:authentication="name"/> 您好,您擁有角色:<span sec:authentication="principal.authorities"/>
    <form th:action="@{/logout}" method="post">
        <input type="submit" value="註銷">
    </form>
</div>
<div sec:authorize="hasRole('VIP1')"><a th:href="@{/level/1}">LEVEL 1</a></div>
<div sec:authorize="hasRole('VIP2')"><a th:href="@{/level/2}">LEVEL 2</a></div>
<div sec:authorize="hasRole('VIP3')"><a th:href="@{/level/3}">LEVEL 3</a></div>
</body>
</html>
templates/welcome.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陸頁</title>
</head>
<body>
<form th:action="@{/login}" method="post" >
    用戶名:<input type="text" name="username"> <br>
    密碼:<input type="text" name="password"> <br>
    <input type="checkbox" name="rememberMe">
    <input type="submit" value="登陸"/>
</form>

</body>
</html>
templates/login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>級別</title>
</head>
<body>
<a th:href="@{/}">首頁</a>

<h1 th:text="${level}"></h1>
</body>
</html>
templates/pages/level.html

三、編寫測試 Controller:apache

package zze.spring.security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class TestController {
    private final String PREFIX = "pages/";

    // 歡迎頁
    @GetMapping("/")
    public String index() {
        return "welcome";
    }

    @GetMapping("/level/{level}")
    public String level(@PathVariable Integer level, Model model) {
        model.addAttribute("level", level == 1 ? "初級" : level == 2 ? "中級" : "高級");
        return PREFIX + "level";
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }
}
zze.spring.security.controller.TestController

四、配置:瀏覽器

package zze.spring.security.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;

/**
 * 編寫配置類繼承 WebSecurityConfigurerAdapter
 */
@EnableWebSecurity // 啓用 WebSecurity 模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 控制請求的訪問權限
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        // 定製請求的受權規則
        http.authorizeRequests().antMatchers("/").permitAll() // "/" 容許任何人訪問
                .antMatchers("/level/1").hasRole("VIP1") // "/level/1" 僅容許擁有角色 VIP1 的主體訪問
                .antMatchers("/level/2").hasRole("VIP2") // "/level/2" 僅容許擁有角色 VIP2 的主體訪問
                .antMatchers("/level/3").hasRole("VIP3"); // "/level/3" 僅容許擁有角色 VIP3 的主體訪問

        // 開啓自動配置的登陸功能,開啓後未登陸狀態訪問將會自動重定向到 /login 登陸頁
        //   一、訪問 /login 來到登陸頁
        //   二、重定向到 /login?error 表示登陸失敗
        //   三、可經過 loginPage() 方法修改使用本身的登陸頁,登陸請求須要爲 post,的用戶名參數默認爲 username ,密碼參數爲 password 。
        //   四、若是使用了 loginPage() 方法修改了登陸頁,那麼該請求的 post 方式就是登陸請求。好比修改 /userLogin 爲登陸頁,那麼 post 請求 /userLogin 則是登陸操做
        http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/login");

        // 開啓自動配置的註銷
        //   一、訪問 /logout 表示用戶註銷,狀況 session
        //   二、註銷成功默認會重定向到 /login?logout
        //
        //  經過 logoutSuccessUrl("/") 方法指定註銷成功重定向的頁面
        http.logout().logoutSuccessUrl("/");

        // 開啓記住我功能
        //   一、登陸成功後,將 cookie 發送給瀏覽器保存,之後訪問都會帶上這個 cookie,經過檢查就能夠免登陸
        //   二、點擊註銷會刪除 cookie
        //   三、可經過 rememberMeParameter 方法定義登陸操做的記住我參數名
        http.rememberMe().rememberMeParameter("rememberMe");
    }

    // 定義認證規則
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("VIP1", "VIP2") // 內存中存入一個用戶(主體),用戶名爲 zhangsan 密碼爲 123456,擁有角色 VIP1 和 VIP2
                .and()
                .withUser("lisi").password("123456").roles("VIP2", "VIP3") // 內存中存入一個用戶(主體),用戶名爲 lisi 密碼爲 123456,擁有角色 VIP2 和 VIP3
                .and()
                .withUser("wangwu").password("123456").roles("VIP1", "VIP3"); // 內存中存入一個用戶(主體),用戶名爲 wangwu 密碼爲 123456,擁有角色 VIP1 和 VIP3
    }
}
zze.spring.security.config.SecurityConfig
相關文章
相關標籤/搜索