Spring Security(一):介紹以及項(xiàng)目搭建

一、介紹

Spring Security是一個(gè)專注于為Java應(yīng)用程序提供身份驗(yàn)證、授權(quán)和訪問控制的功能強(qiáng)大且可高度自定義的框架。與所有Spring項(xiàng)目一樣,Spring Security的真正強(qiáng)大之處在于它可以輕松擴(kuò)展以滿足自定義要求。
Spring Security具有如下幾個(gè)特征:

  • 對(duì)身份驗(yàn)證和授權(quán)的全面和可擴(kuò)展的支持
  • 防止會(huì)話固定,點(diǎn)擊劫持,跨站點(diǎn)請(qǐng)求偽造等攻擊
  • Servlet API 集成
  • 可選的與Spring Web MVC的集成
  • 等等

二、項(xiàng)目搭建及配置

使用IDEA新建項(xiàng)目



點(diǎn)擊Next,隨便配置group和artifact等



下一步,引入需要的依賴
spring security

spring boot開發(fā)插件

thymeleaf模板引擎

Spring MVC

下一步,點(diǎn)擊finish



完整目錄結(jié)構(gòu)及maven依賴

新建home頁(yè)面:src/main/resources/templates/home.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-springsecurity">
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
        <h1>Welcome!</h1>
        <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
    </body>
</html>

home頁(yè)面中有一個(gè)/hello鏈接指向hello.html:
src/main/resources/templates/hello.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-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>

配置Spring MVC:
com.hermes.security.config.MvcConfig

package com.hermes.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author: lzb
 * @create: 2019/07/19 21:33
 * @description:
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder encoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
             .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
             .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(encoder)
                .withUser("username")
                .password(encoder.encode("password"))
                .roles("USER");
    }

    /**
     * 此處需要配置密碼編碼器,否則可能產(chǎn)生
     * {@code There is no PasswordEncoder mapped for the id "null"}的錯(cuò)誤
     *
     * @return 密碼編碼器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

WebSecurityConfig類使用@EnableWebSecurity注解以啟用spring security的web安全支持,并提供了spring mvc集成,此外它擴(kuò)展了WebSecurityConfigurerAdapter,重寫了一些方法來(lái)進(jìn)行web安全配置。

configure(HttpSecurity)方法定義了哪些URL路徑應(yīng)該被保護(hù),哪些不應(yīng)該。具體來(lái)說,“/”和“/ home”路徑被配置為不需要任何身份驗(yàn)證。所有其他路徑必須經(jīng)過身份驗(yàn)證。

當(dāng)用戶成功登錄時(shí),它們將被重定向到先前請(qǐng)求的需要身份認(rèn)證的頁(yè)面。有一個(gè)由 loginPage()指定的自定義“/登錄”頁(yè)面,每個(gè)人都可以查看它。

對(duì)于configureGlobal(AuthenticationManagerBuilder) 方法,它將單個(gè)用戶設(shè)置在內(nèi)存中。該用戶的用戶名為“username”,密碼為“password”,角色為“USER”。

創(chuàng)建登錄頁(yè)面:
templates/login.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-springsecurity3">
    <head>
        <title>Spring Security Example </title>
    </head>
    <body>
        <div th:if="${param.error}">
            Invalid username and password.
        </div>
        <div th:if="${param.logout}">
            You have been logged out.
        </div>
        <form th:action="@{/login}" method="post">
            <div><label> User Name : <input type="text" name="username"/> </label></div>
            <div><label> Password: <input type="password" name="password"/> </label></div>
            <div><input type="submit" value="Sign In"/></div>
        </form>
    </body>
</html>

此頁(yè)面提供了一個(gè)表單用于接收用戶名和密碼,spring security提供了一個(gè)攔截該請(qǐng)求并驗(yàn)證用戶的過濾器,如果驗(yàn)證失敗,該頁(yè)面將重定向到/login?error,并顯示相應(yīng)錯(cuò)誤信息。用戶注銷后,頁(yè)面將重定向到/login?logout,頁(yè)面顯示登出成功消息。

最后,提供一個(gè)顯示當(dāng)前用戶名和登出的方法,更新hello.html,向當(dāng)前用戶打印一句hello,并包含一個(gè)注銷表單:
/templates/hello.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-springsecurity3">
<head>
    <title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
    <input type="submit" value="Sign Out"/>
</form>
</body>
</html>

啟動(dòng)應(yīng)用

啟動(dòng)com.hermes.security.SecurityApplication
應(yīng)用啟動(dòng)后, 在瀏覽器中訪問 http://localhost:8080. 你可以訪問到首頁(yè):

首頁(yè)

點(diǎn)擊click后跳轉(zhuǎn)到hello頁(yè)面,該頁(yè)面是受保護(hù)的:
hello頁(yè)面

輸入用戶名密碼登錄:
登錄成功

點(diǎn)擊sign out:
登出成功

至此,一個(gè)簡(jiǎn)單的基于spring security的web就搭建完成了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。