Spring Boot + Spring Security + Thymeleaf 快速搭建入門

1 前言

Java EE目前比較主流的authorization和authetication的庫一個為Spring Security,另一個為apache shiro。由于之前的項目是用spring boot 和shiro + vue實現前后分離,shiro的文檔和使用體驗比較友好也沒有什么需要特別記錄的地方,權限控制粒度可以直接精確到方法。至于Spring Security屬于Spring的全家桶系列怎么也得體驗下。筆者原先用python的flask與php的laravel進行服務端開發(fā),權限管理在python的項目中完全是輕量級的自我實現,收獲良多,對于新手的建議先不要一來就上手這種設計復雜的庫,對于源碼的閱讀和設計的理解會有很多障礙,最好先自己實現相應功能后再去學習Shiro與Spring Security的源碼設計。 本來不太想寫這種記錄流水文,但是為了節(jié)約大家在Spring Boot + Spring Security + Thymeleaf的搭建時間,現在對搭建基礎框架做詳細說明,相關代碼可以在Github獲取。本人包含搭建流程與說明以及搭建過程中踩坑(對框架不夠理解就會踩坑)心得。如果跟隨文檔搭建過程中遇到什么問題請拉到末尾看看友情提示中有無對應的解決辦法。筆者盡量在代碼注釋中說明具體功能。

項目地址: https://github.com/alexli0707/spring_boot_security_themeleaf

2 目的

這是一個Spring Boot + Spring Security + Thymeleaf 的示例項目,我們將使用Spring Security 來進行權限控制。其中/admin/user是兩個角色不同權限的訪問path。

3 項目

image.png

項目配置文件就不細說,在pom.xml里,為了排除干擾,所有依賴和代碼都是最簡配置。

3.1 Spring Boot 配置

3.1.1 DefaultController

返回對應路由請求所要訪問的模板文件。

package com.walkerlee.example.spring_boot_security_themeleaf.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class DefaultController {

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

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

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

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

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

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

    @GetMapping("/403")
    public String error403() {
        return "/error/403";
    }

}

注意這邊用的是@Controller不是@RestController二者的區(qū)別可以查閱對應文檔。

3.1.2 SpringBootSecurityThemeleafApplication

應用啟動入口。

package com.walkerlee.example.spring_boot_security_themeleaf;

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

@SpringBootApplication
public class SpringBootSecurityThemeleafApplication {

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

3.2 Spring Securtiy 配置

3.2.1 SecurityConfig

繼承WebSecurityConfigurerAdapter,目前配置用戶帳號密碼角色于內存中,在配合db存儲使用的時候需要實現org.springframework.security.core.userdetails.UserDetailsService 接口并作更多配置,此處先使用兩個保存在內存中的模擬角色帳號進行登錄與角色校驗。

package com.walkerlee.example.spring_boot_security_themeleaf.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.web.access.AccessDeniedHandler;

/**
 * SecurityConfig
 * Description:  Spring Security配置
 * Author:walker lee
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;



    // roles admin allow to access /admin/**
    // roles user allow to access /user/**
    // custom 403 access denied handler
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/fonts/**").permitAll()  // 允許訪問資源
                .antMatchers("/", "/home", "/about").permitAll() //允許訪問這三個路由
                .antMatchers("/admin/**").hasAnyRole("ADMIN")   // 滿足該條件下的路由需要ROLE_ADMIN的角色
                .antMatchers("/user/**").hasAnyRole("USER")     // 滿足該條件下的路由需要ROLE_USER的角色
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler);           //自定義異常處理
    }


    // create two users, admin and user
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password("user").roles("USER")
                .and()
                .withUser("admin").password("admin").roles("ADMIN");
    }

}

3.2.1 CustomAccessDeniedHandler

出現權限限制返回HTTP_CODE為403的時候自定義展示頁面以及內容。

package com.walkerlee.example.spring_boot_security_themeleaf.security.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * CustomAccessDeniedHandler
 * Description:  handle 403 page
 * Author:walker lee
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    private static Logger logger = LoggerFactory.getLogger(CustomAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        Authentication auth
                = SecurityContextHolder.getContext().getAuthentication();

        if (auth != null) {
            logger.info("User '" + auth.getName()
                    + "' attempted to access the protected URL: "
                    + httpServletRequest.getRequestURI());
        }

        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/403");
        
        
    }
}

3.3 Thymeleaf + Resources + Static files

3.3.1 thymeleaf的模板文件保存在src/main/resources/templates/文件夾中,具體使用自行google官方文檔,Thymeleaf可以支持前后分離的開發(fā)方式,具體玩法這邊不做過多復述,該demo工程僅使用其中的基礎特性,
3.3.2 Fragment

可參照官方文檔

3.3.3 Demo中fragment需要特別說明的布局--footer.html,觀察sec標簽,這是一個與Spring Security協(xié)作比較有效的方法,具體可以參照Thymeleaf extra Spring Security
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
</head>
<body>
<div th:fragment="footer">

    <div class="container">

        <footer>
        <!-- this is footer -->
            <span sec:authorize="isAuthenticated()">
                | Logged user: <span sec:authentication="name"></span> |
                Roles: <span sec:authentication="principal.authorities"></span> |
                <a th:href="@{/logout}">Sign Out</a>
            </span>
        </footer>
    </div>

</div>
</body>
</html>

Note
關于Spring Boot的靜態(tài)資源協(xié)議配置可以參照此處 Spring Boot Serving static content

4 運行Demo

4.1 運行命令,訪問 http://localhost:8080

$ mvn spring-boot:run

頁面

image.png

點擊1訪問管理員頁面,因為沒有登錄被阻止跳轉到登錄頁:
image.png

輸入帳號admin密碼admin 登錄成功后重定向到http://localhost:8080/admin 。此時返回主頁進入2用戶頁面,提示403沒有對應權限:
image.png

最終點擊登出重定向到:http://localhost:8080/login?logout,到此快速模板算是搭建完畢,如果需要更多深入的詳解和展開這個篇幅肯定是不夠的,先到這里。

Tip:聊下可能會遇到的問題

  1. 無法啟動項目(如果用的是github上的工程項目肯定是不會的),如果是自己搭建的話可能是沒有在pom配置 :
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  2. 登錄成功后重定向到你的css文件或者js文件而不是上一次訪問的路徑? 很有可能是沒有配置允許資源文件被外網訪問的權限,導致登錄成功的回調handler中request的referer是被提示403的資源文件。
  3. 如果需要針對結合數據庫以及更多功能的快速集成的話歡迎留個言,元旦有時間也會一并寫下。

引用:

  1. Securing a Web Application
  2. Spring Security Reference
  3. Spring Boot Security features
  4. Spring Boot Hello World Example – Thymeleaf
  5. Spring Security Hello World Annotation Example
  6. Thymeleaf – Spring Security integration basics
  7. Thymeleaf extra – Spring Security integration basics
  8. Thymeleaf – Standard URL Syntax
  9. Spring Boot + Spring MVC + Spring Security + MySQL
  10. Spring Boot – Static content
  11. Spring Boot Spring security themeleaf example
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容