国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring Boot安全管理

這篇具有很好參考價(jià)值的文章主要介紹了Spring Boot安全管理。希望對大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

一.Spring Security快速??

1.添加security啟動器

在項(xiàng)?的 pom.xml ?件中引? Spring Security 安全框架的依賴啟動器 spring-boot-starter-security 。
<!-- Spring Security 提供的安全管理依賴啟動器 -->
<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-starter-security </artifactId>
</dependency>
上述引?的依賴 spring-boot-starter-security 就是 Spring Boot 整合 Spring Security 安全框架?提供的依賴啟動器,
其版本號由 Spring Boot 進(jìn)?統(tǒng)?管理。需要說明的是,?旦項(xiàng)?引? spring-boot-starter-security 啟動器, MVC
Security WebFlux Security 負(fù)責(zé)的安全功能都會?即?效( WebFlux Security ?效的另?個(gè)前提是項(xiàng)?屬于
WebFlux Web 項(xiàng)?);對于 OAuth2 安全管理功能來說,則還需要額外引??些其他安全依賴。

項(xiàng)?啟動測試

項(xiàng)?啟動時(shí)會在控制臺?動?成?個(gè)安全密碼( security password 這個(gè)密碼在每次啟動項(xiàng)?時(shí)都是隨機(jī)?成
的)。通過在瀏覽器訪問 http://localhost:8080 查看項(xiàng)???,效果如下圖所示。

spring-boot-starter-security,spring boot,java,spring

?這種默認(rèn)安全管理?式存在諸多問題。例如,只有唯?的默認(rèn)登錄?戶user,密碼隨機(jī)?成且過于暴露、登錄?? 及錯(cuò)誤提示??不是我們想要的等。

1.MVC Security安全配置介紹

1.下?我們通過Spring Security API查看WebSecurityConfigurerAdapter的主要?法,具體如下表

@EnableWebSecurity // 開啟MVC Security安全?持
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//定制基于HTTP請求的?戶訪問控制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
//定制?戶認(rèn)證管理器來實(shí)現(xiàn)?戶認(rèn)證
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }
}

?4 ?定義?戶認(rèn)證

????????1.In-Memory Authentication:內(nèi)存身份認(rèn)證

????????2.JDBC Authentication:JDBC身份認(rèn)證

????????3.UserDetailsService:身份詳情服務(wù)

????????4.LDAP Authentication:LDAP身份認(rèn)證

????????5.AuthenticationProvider:身份認(rèn)證提供商

4.1.2 使?內(nèi)存進(jìn)?身份認(rèn)證? ?寫一個(gè)配置類即可

package com.cy.config;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationMa
nagerBuilder;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerA
dapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* MVC Security管理配置的?定義WebSecurityConfigurerAdapter類
*/
@EnableWebSecurity // 開啟MVC Security安全?持
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 /** ?戶身份認(rèn)證?定義配置 */
 @Override
 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
 // 密碼需要設(shè)置編碼器
 BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
 // 1.使?內(nèi)存?戶信息,作為測試使?(設(shè)置?戶名、密碼和??)
 auth.inMemoryAuthentication().passwordEncoder(encoder)
.withUser("tom").password(encoder.encode("123456")).roles("common")
 .and()
 .withUser("李四").password(encoder.encode("123456")).roles("vip");
 }
}
(1) Spring Security 5 開始,?定義?戶認(rèn)證必須設(shè)置密碼編碼器?于保護(hù)密碼,否則控制臺會出現(xiàn)
“IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"” 異常錯(cuò)誤。
(2) Spring Security 提供了多種密碼編碼器,包括 BCryptPasswordEncoder 、 Pbkdf2PasswordEncoder 、
ScryptPasswordEncoder 等。
(3) ?定義?戶認(rèn)證時(shí),可以定義?戶?? roles ,也可以定義?戶權(quán)限 authorities 。在進(jìn)?賦值時(shí),權(quán)限通常是在
??值的基礎(chǔ)上添加 ROLE_ 前綴。例如, roles("common") authorities("ROLE_common") 是等效的。
(4) ?定義?戶認(rèn)證時(shí),可以為某個(gè)?戶?次指定多個(gè)??或權(quán)限,例如, roles("common", "vip")
authorities("ROLE_common", "ROLE_vip")

4.3?UserDetailsService身份認(rèn)證

1.1.在項(xiàng)?的pom.xml?件中添加Mybaits依賴啟動器和lombok依賴。

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>
<dependency>
<groupId> org.projectlombok </groupId>
<artifactId> lombok </artifactId>
</dependency>
package com.example.demo.service.imp;

import com.example.demo.pojo.Authority;
import com.example.demo.pojo.Customer;
import com.example.demo.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/** ?定義?個(gè)UserDetailsService接?實(shí)現(xiàn)類進(jìn)??戶認(rèn)證信息封裝 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    /* 內(nèi)有提供自定義用戶查詢和權(quán)限查詢的方法
    * getCustomer  根據(jù)名字查詢用戶信息 的方法
    * 
    * getCustomerAuthority  根據(jù)名字查詢用戶權(quán)限 的方法
    * */
    
    private CustomerService customerService;
    @Override
    public UserDetails loadUserByUsername(String username) throws
            UsernameNotFoundException {
        // 通過業(yè)務(wù)?法獲取?戶及權(quán)限信息
        Customer customer = customerService.getCustomer(username);
        List<Authority> authorities = customerService.getCustomerAuthority(username);
        // 對?戶權(quán)限進(jìn)?封裝
        List<SimpleGrantedAuthority> list = authorities.stream().map(authority -> new
                SimpleGrantedAuthority(authority.getAuthority())).collect(Collectors.toList());
        // 返回封裝的UserDetails?戶詳情類
        if (customer != null) {
            UserDetails userDetails = new User(customer.getUsername(),
                    customer.getPassword(), list);
            return userDetails;
        } else {
            // 如果查詢的?戶不存在(?戶名不存在),必須拋出此異常
            throw new UsernameNotFoundException("當(dāng)前?戶不存在!");
        }}}
package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
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.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;
import java.util.Date;
import java.util.HashMap;

//開啟安全管理的支持
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired //Hikari連接池,自動將mysql配置信息加載連接池對象上
    private DataSource dataSource;
    //1.用戶身份認(rèn)證的配置
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() // 開啟基于HttpServletRequest請求訪問的限制
                .antMatchers("/").permitAll() // 開啟Ant?格的路徑匹配。?條件對請求進(jìn)?放?
                .antMatchers("/login/**").permitAll()
                .antMatchers("/detail/common/**").hasRole("common") // 匹配?戶是否有某?個(gè)??
                .antMatchers("/detail/vip/**").hasRole("vip")
                .anyRequest().authenticated()// 匹配任何請求。匹配已經(jīng)登錄認(rèn)證的?戶
                .and() // 功能連接符
                .formLogin(); // 開啟基于表單的?戶登錄
              http.formLogin() // 開啟基于表單的?戶登錄
                // ?戶登錄??跳轉(zhuǎn)路徑,默認(rèn)為get請求的/login。?條件對請求進(jìn)?放?
                .loginPage("/userLogin").permitAll()
                .usernameParameter("name") // 登錄?戶的?戶名參數(shù), 默認(rèn)為username
                .passwordParameter("pwd") // 登錄?戶的密碼參數(shù),默認(rèn)為password
                .defaultSuccessUrl("/") // ?戶直接登錄后默認(rèn)跳轉(zhuǎn)地址
                .failureUrl("/userLogin?error"); // ?戶登錄失敗后的跳轉(zhuǎn)地址,默認(rèn)為/login?erro
        // ?定義?戶退出控制
        http.logout()
                .logoutUrl("/mylogout")
                .logoutSuccessUrl("/");

        // 定制Remember-me記住我功能
        http.rememberMe()
                .rememberMeParameter("rememberme")
                .tokenValiditySeconds(200)
                // 對Cookie信息進(jìn)?持久化管理
                .tokenRepository(tokenRepository());
    }
 
    @Bean
    /** 持久化Token存儲 */
    public JdbcTokenRepositoryImpl tokenRepository() {
        JdbcTokenRepositoryImpl jti = new JdbcTokenRepositoryImpl();
        jti.setDataSource(dataSource);
        //自動創(chuàng)建數(shù)據(jù)庫表字段
        jti.setCreateTableOnStartup(true);
        return jti;
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 密碼需要設(shè)置編碼器
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);

    }
    }

完成以上配置基于內(nèi)存進(jìn)?身份認(rèn)證? 就結(jié)束了

接下來是配置的信息

HttpSecurity類的主要?法及說明:
方法 描述
authorizeRequests() 開啟基于HttpServletRequest請求訪問的限制
formLogin() 開啟基于表單的?戶登錄
httpBasic() 開啟基于HTTP請求的Basic認(rèn)證登錄
logout() 開啟退出登錄的?持
sessionManagement() 開啟Session管理配置
rememberMe() 開啟記住我功能
csrf() 配置CSRF跨站請求偽造防護(hù)功能
?戶請求控制相關(guān)的主要?法及說明
?法
描述
antMatchers(java.lang.String... antPtterns)
開啟 Ant ?格的路徑匹配
mvcMatchers(java.lang.String... patterns)
開啟 MVC ?格的路徑匹配(與 Ant ?格類似)
regexMatchers(java.lang.Sring...
regexPatterns)
開啟正則表達(dá)式的路徑匹配
and()
功能連接符
anyRequest()
匹配任何請求
rememberMe()
開啟記住我功能
access(String attribute)
匹配給定的 SpEL 表達(dá)式計(jì)算結(jié)果是否為 true
hasAnyRole(String... roles)
匹配?戶是否有參數(shù)中的任意??
hasRole(Sring role)
匹配?戶是否有某?個(gè)??
hasAnyAuthority(String... authorities)
匹配?戶是否有參數(shù)中的任意權(quán)限
hasAuthority(String authority)
匹配?戶是否有某?個(gè)權(quán)限
authenticated()
匹配已經(jīng)登錄認(rèn)證的?戶
fullyAuthenticated()
匹配完整登錄認(rèn)證的?戶(? rememberMe 登錄? 戶)
hasIpAddress(String ipAddressExpression)
匹配某 IP 地址的訪問請求
permitAll()
?條件對請求進(jìn)?放?
formLogin()?戶登錄?法中涉及?戶登錄的主要?法及說明如下表所示
?法
描述
loginPage(String loginPage)
?戶登錄??跳轉(zhuǎn)路徑,默認(rèn)為 get 請 求的/login
successForwardUrl(String forwardUrl)
?戶登錄成功后的重定向地址
successHandler(AuthenticationSuccessHandler
authenticationSuccessHandler)
?戶登錄成功后的處理
defaultSuccessUrl(String defaultSuccessUrl)
?戶直接登錄后默認(rèn)跳轉(zhuǎn)地址
failureForwardUrl(String forwardUrl)
?戶登錄失敗后的重定向地址
failureUrl(String authenticationFailureUrl)
?戶登錄失敗后的跳轉(zhuǎn)地址,默認(rèn)
/login?error
failureHandler(AuthenticationFailureHandler
authenticationFailureHandler)
?戶登錄失敗后的錯(cuò)誤處理
usernameParameter(String usernameParameter)
登錄?戶的?戶名參數(shù), 默認(rèn)為
username
passwordParameter(String passwordParameter)
登錄?戶的密碼參數(shù),默認(rèn)為
password
loginProcessingUrl(String loginProcessingUrl)
登錄表單提交的路徑,默認(rèn)為 post
求的 /login
permitAll()
permitAll()
?條件對請求進(jìn)?放?
rememberMe()記住我功能相關(guān)涉及記住我的主要?法及說明如下表所示。
?法
描述
rememberMeParameter(String rememberMeParameter)
指示在登錄時(shí)記住?戶的 HTTP 參數(shù)
key(String key)
記住我認(rèn)證?成的 Token 令牌標(biāo)識
tokenValiditySeconds(int tokenValiditySeconds)
記住我 Token 令牌有效期,單位為秒
tokenRepository(PersistentTokenRepository
tokenRepository)
指定要使?的 PersistentTokenRepository ,?來配置持久化 Token 令牌
alwaysRemember(boolean alwaysRemember)
是否應(yīng)該始終創(chuàng)建記住我 Cookie ,默認(rèn)為 false
clearAuthentication(boolean clearAuthentication)
是否設(shè)置 Cookie 為安全的,如果設(shè)置為 true ,則必須通過 HTTPS 進(jìn)?連接請 求
Spring Security安全框架提供了CSRF防御相關(guān)?法。
?法
描述
disable()
關(guān)閉 Security 默認(rèn)開啟的 CSRF 防御功能
csrfTokenRepository(CsrfTokenRepository
csrfTokenRepository)
指定要使?的 CsrfTokenRepository Token 令牌持久化倉庫)。默認(rèn)是由
LazyCsrfTokenRepository 包裝的 HttpSessionCsrfTokenRepository
requireCsrfProtectionMatcher(RequestMatcher
requireCsrfProtectionMatcher)
指定針對什么類型的請求應(yīng)? CSRF 防護(hù)功能。默認(rèn)設(shè)置是忽略 GET 、 HEAD 、 TRACE OPTIONS
求,?處理并防御其他所有請求

以上就是一些比較常用的配置信息文章來源地址http://www.zghlxwxcb.cn/news/detail-742168.html

到了這里,關(guān)于Spring Boot安全管理的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 安全生產(chǎn)管理系統(tǒng)助力企業(yè)安全細(xì)化管理

    安全生產(chǎn)管理系統(tǒng)助力企業(yè)安全細(xì)化管理

    安全生產(chǎn)管理系統(tǒng)利用完整的安全生產(chǎn)管理體系,結(jié)合信息化、數(shù)字化和智能化等技術(shù)手段,將安全生產(chǎn)過程中的各個(gè)環(huán)節(jié)進(jìn)行有效整合,使安全管理更加科學(xué)、規(guī)范和高效。 安全生產(chǎn)管理系統(tǒng)可以對企業(yè)安全生產(chǎn)進(jìn)行全面、細(xì)致的管理。它能夠?qū)崿F(xiàn)對企業(yè)安全生產(chǎn)活動的全

    2024年02月06日
    瀏覽(88)
  • 安全運(yùn)營之資產(chǎn)安全信息管理

    安全運(yùn)營之資產(chǎn)安全信息管理

    安全風(fēng)險(xiǎn)管理的三要素分別是資產(chǎn)、威脅和脆弱性,脆弱性的存在將會導(dǎo)致風(fēng)險(xiǎn),而威脅主體利用脆弱性產(chǎn)生風(fēng)險(xiǎn)。網(wǎng)絡(luò)攻擊主要利用了系統(tǒng)的脆弱性。由于網(wǎng)絡(luò)管理對象(資產(chǎn))自身的脆弱性,使得威脅的發(fā)生成為可能,從而造成了不同的影響,形成了風(fēng)險(xiǎn)。“摸清家底,

    2024年02月15日
    瀏覽(20)
  • 信息安全管理(CISP)—— 信息安全保障

    信息安全管理(CISP)—— 信息安全保障

    寫在最前面 一、信息安全保障知識框架 二、信息安全保障基礎(chǔ) 1.信息安全的定義 2.信息安全問題 3.信息安全問題的根源與特征 4.信息安全屬性 5.信息安全視角 6.信息安全發(fā)展階段 7.威脅情報(bào)與態(tài)勢感知 三、信息安全保障框架 1.PDR模型 2.PPDR模型 3.IATF模型 4.信息系統(tǒng)安全保障

    2024年02月08日
    瀏覽(29)
  • 網(wǎng)絡(luò)安全——基線管理與安全配置

    網(wǎng)絡(luò)安全——基線管理與安全配置

    一、基線管理概述 1、什么是安全基線 簡單來說,就是安全的最低標(biāo)準(zhǔn)線,滿足安全需求的最低要求 ?2、基線的相關(guān)名詞 ?3、基線核查的對象 必須把所有資產(chǎn)統(tǒng)計(jì)出來,如果漏了的話,可能會成為一個(gè)薄弱點(diǎn),被攻擊 4、基線管理 基線配置不僅僅是一項(xiàng)工作任務(wù),更是一項(xiàng)

    2024年02月11日
    瀏覽(17)
  • 二、安全與風(fēng)險(xiǎn)管理—風(fēng)險(xiǎn)管理

    目錄 一、什么是風(fēng)險(xiǎn)及風(fēng)險(xiǎn)管理過程 二、威脅建模 三、主動攻擊和被動攻擊

    2024年02月03日
    瀏覽(26)
  • 安全狗云原生安全-云甲·云原生容器安全管理系統(tǒng)

    安全狗云原生安全-云甲·云原生容器安全管理系統(tǒng)

    隨著云計(jì)算的快速發(fā)展,容器技術(shù)逐漸成為主流。然而,隨著容器的普及,安全問題也日益突出。為了解決這一問題,安全狗推出了云原生容器安全管理系統(tǒng)——云甲。 云甲是安全狗云原生安全的重要組成部分,它采用了先進(jìn)的云原生技術(shù),為容器提供了全面的安全保障。

    2024年02月04日
    瀏覽(17)
  • K8S應(yīng)用流程安全(鏡像安全 配置管理 訪問安全)

    K8S應(yīng)用流程安全(鏡像安全 配置管理 訪問安全)

    1.1.1 構(gòu)建原則 學(xué)習(xí)目標(biāo) 這一節(jié),我們從 基礎(chǔ)知識、原則解讀、小結(jié) 三個(gè)方面來學(xué)習(xí)。 基礎(chǔ)知識 k8s平臺使用業(yè)務(wù)環(huán)境 需求 鏡像的使用流程 Docker鏡像加載 UnionFS 原則解讀 構(gòu)建樣式 構(gòu)建原則 實(shí)踐原則 分層效果 功能效果 小結(jié) 1.1.2 Dockerfile實(shí)踐 學(xué)習(xí)目標(biāo) 這一節(jié),我們從 基礎(chǔ)

    2024年02月13日
    瀏覽(24)
  • 一文解讀ISO26262安全標(biāo)準(zhǔn):功能安全管理

    下文的表中,一些方法的推薦等級說明: “++”表示對于指定的ASIL等級,高度推薦該方法; “+” 表示對于指定的ASIL等級,推薦該方法; “o” 表示對于指定的ASIL等級,不推薦該方法。 功能安全管理分為幾個(gè)階段:概念階段、產(chǎn)品開發(fā)階段、生產(chǎn)發(fā)布之后的階段。 在概念

    2024年04月16日
    瀏覽(31)
  • 智慧消防管理云平臺 電氣火災(zāi)安全用電管理

    智慧消防管理云平臺 電氣火災(zāi)安全用電管理

    ? 1、概述 ??安科瑞智慧消防綜合管理云平臺基于物聯(lián)網(wǎng)、大數(shù)據(jù)、云計(jì)算等現(xiàn)代信息技術(shù),將分散的火災(zāi)自動報(bào)警設(shè)備、電氣火災(zāi)監(jiān)控設(shè)備、智慧煙感探測器、智慧消防用水等設(shè)備連接形成網(wǎng)絡(luò),并對這些設(shè)備的狀態(tài)進(jìn)行智能化感知、識別、定位,實(shí)時(shí)動態(tài)采集消防信息

    2024年04月28日
    瀏覽(26)
  • 內(nèi)網(wǎng)安全管理系統(tǒng)(保密管理系統(tǒng))

    內(nèi)網(wǎng)安全管理系統(tǒng)(保密管理系統(tǒng))

    在當(dāng)今信息化的時(shí)代,企業(yè)的內(nèi)網(wǎng)已經(jīng)成為其核心資產(chǎn)的重要組成部分。 隨著企業(yè)的快速發(fā)展和信息化程度的提升,內(nèi)網(wǎng)安全問題日益凸顯,如何保障內(nèi)網(wǎng)的安全和機(jī)密信息的保密性,已經(jīng)成為企業(yè)亟待解決的問題。 內(nèi)網(wǎng)安全管理系統(tǒng)(保密管理系統(tǒng))是一種集成了先進(jìn)的

    2024年01月20日
    瀏覽(25)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包