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

1 前言

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

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

2 目的

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

3 項目

image.png

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

3.1 Spring Boot 配置

3.1.1 DefaultController

返回對應(yīng)路由請求所要訪問的模板文件舷嗡。

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ū)別可以查閱對應(yīng)文檔轴猎。

3.1.2 SpringBootSecurityThemeleafApplication

應(yīng)用啟動入口。

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进萄,目前配置用戶帳號密碼角色于內(nèi)存中捻脖,在配合db存儲使用的時候需要實現(xiàn)org.springframework.security.core.userdetails.UserDetailsService 接口并作更多配置,此處先使用兩個保存在內(nèi)存中的模擬角色帳號進行登錄與角色校驗中鼠。

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

出現(xiàn)權(quán)限限制返回HTTP_CODE為403的時候自定義展示頁面以及內(nèi)容可婶。

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/文件夾中,具體使用自行g(shù)oogle官方文檔援雇,Thymeleaf可以支持前后分離的開發(fā)方式矛渴,具體玩法這邊不做過多復(fù)述,該demo工程僅使用其中的基礎(chǔ)特性惫搏,
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
關(guān)于Spring Boot的靜態(tài)資源協(xié)議配置可以參照此處 Spring Boot Serving static content

4 運行Demo

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

$ mvn spring-boot:run

頁面

image.png

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

輸入帳號admin密碼admin 登錄成功后重定向到http://localhost:8080/admin 川陆。此時返回主頁進入2用戶頁面剂习,提示403沒有對應(yīng)權(quán)限:
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文件而不是上一次訪問的路徑们何? 很有可能是沒有配置允許資源文件被外網(wǎng)訪問的權(quán)限萄焦,導(dǎo)致登錄成功的回調(diào)handler中request的referer是被提示403的資源文件。
  3. 如果需要針對結(jié)合數(shù)據(jù)庫以及更多功能的快速集成的話歡迎留個言冤竹,元旦有時間也會一并寫下拂封。

引用:

  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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末丁溅,一起剝皮案震驚了整個濱河市剪况,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌笔诵,老刑警劉巖钟病,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件萧恕,死亡現(xiàn)場離奇詭異,居然都是意外死亡肠阱,警方通過查閱死者的電腦和手機票唆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來屹徘,“玉大人走趋,你說我怎么就攤上這事≡祷兀” “怎么了吆视?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長酥宴。 經(jīng)常有香客問我啦吧,道長,這世上最難降的妖魔是什么拙寡? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任授滓,我火速辦了婚禮,結(jié)果婚禮上肆糕,老公的妹妹穿的比我還像新娘般堆。我一直安慰自己,他們只是感情好诚啃,可當(dāng)我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布淮摔。 她就那樣靜靜地躺著,像睡著了一般始赎。 火紅的嫁衣襯著肌膚如雪和橙。 梳的紋絲不亂的頭發(fā)上仔燕,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天,我揣著相機與錄音魔招,去河邊找鬼晰搀。 笑死,一個胖子當(dāng)著我的面吹牛办斑,可吹牛的內(nèi)容都是我干的外恕。 我是一名探鬼主播,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼乡翅,長吁一口氣:“原來是場噩夢啊……” “哼鳞疲!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起峦朗,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤建丧,失蹤者是張志新(化名)和其女友劉穎排龄,沒想到半個月后波势,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡橄维,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年尺铣,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片争舞。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡凛忿,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出竞川,到底是詐尸還是另有隱情店溢,我是刑警寧澤,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布委乌,位于F島的核電站床牧,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏遭贸。R本人自食惡果不足惜戈咳,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望壕吹。 院中可真熱鬧著蛙,春花似錦、人聲如沸耳贬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽咒劲。三九已至顷蟆,卻和暖如春胖秒,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背慕的。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工阎肝, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人肮街。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓风题,卻偏偏與公主長得像,于是被迫代替她去往敵國和親嫉父。 傳聞我的和親對象是個殘疾皇子沛硅,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,781評論 2 354