Spring Security、Spring Boot、Thymeleaf Example

摘要:在這篇文章中,我們主要來講解一下Spring Security、Spring Boot、Thymeleaf整合,實現安全的訪問應用,下面就來看下具體步驟。

一:項目結構

二:框架版本列表

Spring Security 5.0.7.RELEASE

Spring Boot 2.0.4.RELEASE

Thymeleaf 3.0.1.RELEASE

三:核心依賴

3.1:父模塊依賴:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
  </parent>

3.2:子模塊依賴:

<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</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.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>

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

四:核心配置類

SecurityConfig類是核心的提供安全認證的類,該類繼承了Spring Secrity的WebSecurityConfigurerAdapter類,重寫了configure()方法,以實現對應用的安全認證

package com.micai.spring.security.config;

import org.springframework.beans.factory.annotation.Autowired;
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.core.userdetails.User;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/8/3 14:47
 * @Description:
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/css/**", "/index").permitAll()
            .antMatchers("/user/**").hasRole("USER")
            .and()
            .formLogin().loginPage("/login").failureUrl("/login-error");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser(User.withDefaultPasswordEncoder().username("admin").password("admin").roles("USER"));
    }

}

五:核心控制器類

5.1:MainController類主要是控制請求轉發到對應的頁面的

package com.micai.spring.security.web;

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

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/8/3 14:52
 * @Description:
 */
@Controller
public class MainController  {

    @RequestMapping("/")
    public String root() {
        return "redirect:/index";
    }

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

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

    @RequestMapping("/user/index")
    public String userIndex() {
        return "user/index";
    }

    @RequestMapping("/login-error")
    public String loginError(Model model) {
        model.addAttribute("loginError", true);
        return "login";
    }

}

5.2:應用啓動類Application

package com.micai.spring.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/8/3 14:59
 * @Description:
 */
@SpringBootApplication
public class Application {

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

5.3:application.yml配置文件

server:
  port: 8080

logging:
  level:
    root: WARN
    org.springframework.web: INFO
    org.springframework.security: INFO

spring:
  thymeleaf:
    cache: false

5.4:login.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>登錄頁</title>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
	</head>
    <body>
        <center>
            <h1>登錄頁</h1>
            <p>樣例用戶(用戶名/密碼): admin / admin</p>
            <p th:if="${loginError}" class="error">錯誤的用戶名、密碼</p>
            <form th:action="@{/login}" method="post">
                <label for="username">用戶名</label>:
                <input type="text" id="username" name="username" autofocus="autofocus" /> <br />
                <label for="password">密碼</label>:
                <input type="password" id="password" name="password" /> <br />
                <input type="submit" value="登錄" />
            </form>
            <p><a href="/index" th:href="@{/index}">回到首頁</a></p>
        </center>
    </body>
</html>

5.5:index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    <head>
        <title>Hello + Spring Security 5.x + Spring Boot 2.x</title>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
    </head>
    <body>
        <div th:fragment="logout" class="logout" sec:authorize="isAuthenticated()">
            登錄的用戶: <span sec:authentication="name"></span> |
            擁有的角色: <span sec:authentication="principal.authorities"></span>
            <div>
                <form action="#" th:action="@{/logout}" method="post">
                    <input type="submit" value="退出" />
                </form>
            </div>
        </div>
        <h1>Hello + Spring Security 5.x + Spring Boot 2.x</h1>
        <p>這是一個不需要認證的頁面,但是您可以在認證後訪問安全頁面.</p>
        <ul>
            <li>去 <a href="/user/index" th:href="@{/user/index}">需要認證的頁面</a></li>
        </ul>
    </body>
</html>

5.6:user/index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Hello + Spring Security 5.x + Spring Boot 2.x</title>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
    </head>
    <body>
        <div th:substituteby="index::logout"></div>
        <br/>
        <h1>這是一個安全頁面!</h1>
        <p><a href="/index" th:href="@{/index}">回到首頁</a></p>
    </body>
</html>

六:運行結果

 

 

七:源代碼下載

https://gitee.com/micai/micai-spring-security.git

八:參考地址

https://docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/htmlsingle/#get-spring-security

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章