Spring Security框架的快速開始

2021-10-19 06:43:44 字數 2245 閱讀 1059

1、導包

採用spring boot + spring security的方式

org.springframework.boot<

/groupid>

spring-boot-starter-security<

/artifactid>

<

/dependency>

2、編寫controlller

@restcontroller

public

class

testcontroller

}

3、啟動專案

當完成前兩步驟的時候,已經是乙個使用springsecurity的簡單demo了。

在訪問localhost:8080/hello前,會跳轉到/login,介面如下,不過我這是css檔案沒載入出來的情況

預設使用者名為:user,密碼在專案啟動時會輸出到螢幕上,如下:

using generated security password: 66a2da20-bcc8-4314-89e9-56c346577fee

驗證通過後會跳轉到/hello路徑。

我們使用spring security框架的目的是為了:

(1)認證

(2)授權

1、資料**

在認證使用者之前,我們需要配置使用者資料,我們有以下三種方式來進行使用者資料配置

第一種:配置檔案

spring:

security:

user:

name: user

password: user

第二種:配置類

@configuration

public

class

securityconfig

extends

websecurityconfigureradapter

@bean

passwordencoder passwordencoder()

}

第三種:自定義配置類

兩步:配置類+資料查詢類

@configuration

public

class

securityconfigtest

extends

websecurityconfigureradapter

@bean

passwordencoder passwordencoder()

}

資料查詢類:

@service

("userdetailsservice"

)public

class

userservice

implements

userdetailsservice

}

2、認證與授權

我們主要是在我們自定義的類繼承websecurityconfigureradapter類中,重寫configure()方法中可以進行定義。

在configure()方法中,我們主要會定義四個方面:formlogin、authorizerequests、exceptionhandling、logout

// .and().exceptionhandling().accessdeniedpage("/loginfail") //定製登入成功,許可權/角色驗證失敗後的情況

.and()

.logout()

.logouturl

("/logout").

logoutsuccessurl

("/登出成功").

logoutsuccesshandler

("登出成功後的處理器").

permitall()

.and()

.csrf()

.disable()

;}注意點:

spring security 安全框架

本文 http itblood.com spring security security framework.html 安全常識 acegi介紹 以宣告式方式為基於spring的web應用新增認證和授權控制 acegi體系結構 認證管理器 訪問控制管理器。認證 authenticationproce...

SpringSecurity認證流程

在之前的文章 springboot spring security 基本使用及個性化登入配置 中對springsecurity進行了簡單的使用介紹,基本上都是對於介面的介紹以及功能的實現。這一篇文章嘗試從原始碼的角度來上對使用者認證流程做乙個簡單的分析。在具體分析之前,我們可以先看看springse...

SpringSecurity使用技巧

1 鑑權處理頁通常包括四個方面的設定,分別是鑑權失敗 鑑權成功 未鑑權訪問 已鑑權但訪問了受保護許可權。如何自 定義這四類處理。鑑權失敗的預設處理頁面是 spring security login?login error 其預設處理類為 urlauthenticationfailurehandler...