宅男在线永久免费观看网直播,亚洲欧洲日产国码无码久久99,野花社区在线观看视频,亚洲人交乣女bbw,一本一本久久a久久精品综合不卡

全部
常見問題
產(chǎn)品動(dòng)態(tài)
精選推薦

Spring Boot中使用Spring Security進(jìn)行安全控制

管理 管理 編輯 刪除

準(zhǔn)備工作

首先,構(gòu)建一個(gè)簡(jiǎn)單的Web工程,以用于后續(xù)添加安全控制,也可以用之前Chapter3-1-2做為基礎(chǔ)工程。若對(duì)如何使用Spring Boot構(gòu)建Web應(yīng)用,可以先閱讀《整合Thymeleaf開發(fā)web應(yīng)用》一文。

#Web層實(shí)現(xiàn)請(qǐng)求映射

@Controller
public class HelloController {

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }

}
  • /:映射到index.html
  • /hello:映射到hello.html

#實(shí)現(xiàn)映射的頁面

  • src/main/resources/templates/index.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入門</title>
    </head>
    <body>
        <h1>歡迎使用Spring Security!</h1>
        <p>點(diǎn)擊 <a th:href="@{/hello}">這里</a> 打個(gè)招呼吧</p>
    </body>
</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>

可以看到在index.html中提供到/hello的鏈接,顯然在這里沒有任何安全控制,所以點(diǎn)擊鏈接后就可以直接跳轉(zhuǎn)到hello.html頁面。

#整合Spring Security

在這一節(jié),我們將對(duì)/hello頁面進(jìn)行權(quán)限控制,必須是授權(quán)用戶才能訪問。當(dāng)沒有權(quán)限的用戶訪問后,跳轉(zhuǎn)到登錄頁面。

#添加依賴

在pom.xml中添加如下配置,引入對(duì)Spring Security的依賴。

<dependencies>
    ...
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    ...
</dependencies>

#Spring Security配置

創(chuàng)建Spring Security的配置類WebSecurityConfig,具體如下:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @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()
                .withUser("user").password("password").roles("USER");
    }

}

  • 通過@EnableWebSecurity注解開啟Spring Security的功能
  • 繼承WebSecurityConfigurerAdapter,并重寫它的方法來設(shè)置一些web安全的細(xì)節(jié)
  • configure(HttpSecurity http)方法
  • 通過authorizeRequests()定義哪些URL需要被保護(hù)、哪些不需要被保護(hù)。例如以上代碼指定了//home不需要任何認(rèn)證就可以訪問,其他的路徑都必須通過身份驗(yàn)證。
  • 通過formLogin()定義當(dāng)需要用戶登錄時(shí)候,轉(zhuǎn)到的登錄頁面。
  • configureGlobal(AuthenticationManagerBuilder auth)方法,在內(nèi)存中創(chuàng)建了一個(gè)用戶,該用戶的名稱為user,密碼為password,用戶角色為USER。

#新增登錄請(qǐng)求與頁面

在完成了Spring Security配置之后,我們還缺少登錄的相關(guān)內(nèi)容。

HelloController中新增/login請(qǐng)求映射至login.html

@Controller
public class HelloController {

    // 省略之前的內(nèi)容...

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

}

新增登錄頁面:src/main/resources/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}">
            用戶名或密碼錯(cuò)
        </div>
        <div th:if="${param.logout}">
            您已注銷成功
        </div>
        <form th:action="@{/login}" method="post">
            <div><label> 用戶名 : <input type="text" name="username"/> </label></div>
            <div><label> 密  碼 : <input type="password" name="password"/> </label></div>
            <div><input type="submit" value="登錄"/></div>
        </form>
    </body>
</html>

可以看到,實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的通過用戶名和密碼提交到/login的登錄方式。

根據(jù)配置,Spring Security提供了一個(gè)過濾器來攔截請(qǐng)求并驗(yàn)證用戶身份。如果用戶身份認(rèn)證失敗,頁面就重定向到/login?error,并且頁面中會(huì)展現(xiàn)相應(yīng)的錯(cuò)誤信息。若用戶想要注銷登錄,可以通過訪問/login?logout請(qǐng)求,在完成注銷之后,頁面展現(xiàn)相應(yīng)的成功消息。

到這里,我們啟用應(yīng)用,并訪問http://localhost:8080/,可以正常訪問。但是訪問http://localhost:8080/hello的時(shí)候被重定向到了http://localhost:8080/login頁面,因?yàn)闆]有登錄,用戶沒有訪問權(quán)限,通過輸入用戶名user和密碼password進(jìn)行登錄后,跳轉(zhuǎn)到了Hello World頁面,再也通過訪問http://localhost:8080/login?logout,就可以完成注銷操作。

為了讓整個(gè)過程更完成,我們可以修改hello.html,讓它輸出一些內(nèi)容,并提供“注銷”的鏈接。


<!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="注銷"/>
        </form>
    </body>
</html>

本文通過一個(gè)最簡(jiǎn)單的示例完成了對(duì)Web應(yīng)用的安全控制,Spring Security提供的功能還遠(yuǎn)不止于此,更多Spring Security的使用可參見Spring Security Reference


請(qǐng)登錄后查看

CRMEB 最后編輯于2025-01-16 10:26:21

快捷回復(fù)
回復(fù)
回復(fù)
回復(fù)({{post_count}}) {{!is_user ? '我的回復(fù)' :'全部回復(fù)'}}
排序 默認(rèn)正序 回復(fù)倒序 點(diǎn)贊倒序

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}} LV.{{ item.user_info.bbs_level || item.bbs_level }}

作者 管理員 企業(yè)

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest == 1? '取消推薦': '推薦'}}
{{item.is_suggest == 1? '取消推薦': '推薦'}}
沙發(fā) 板凳 地板 {{item.floor}}#
{{item.user_info.title || '暫無簡(jiǎn)介'}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
打賞
已打賞¥{{item.reward_price}}
{{item.like_count}}
{{item.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)

{{itemc.user_info.nickname}}

{{itemc.user_name}}

回復(fù) {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}
打賞
已打賞¥{{itemc.reward_price}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)
查看更多
打賞
已打賞¥{{reward_price}}
999
{{like_count}}
{{collect_count}}
添加回復(fù) ({{post_count}})

相關(guān)推薦

快速安全登錄

使用微信掃碼登錄
{{item.label}} 加精
{{item.label}} {{item.label}} 板塊推薦 常見問題 產(chǎn)品動(dòng)態(tài) 精選推薦 首頁頭條 首頁動(dòng)態(tài) 首頁推薦
取 消 確 定
回復(fù)
回復(fù)
問題:
問題自動(dòng)獲取的帖子內(nèi)容,不準(zhǔn)確時(shí)需要手動(dòng)修改. [獲取答案]
答案:
提交
bug 需求 取 消 確 定
打賞金額
當(dāng)前余額:¥{{rewardUserInfo.reward_price}}
{{item.price}}元
請(qǐng)輸入 0.1-{{reward_max_price}} 范圍內(nèi)的數(shù)值
打賞成功
¥{{price}}
完成 確認(rèn)打賞

微信登錄/注冊(cè)

切換手機(jī)號(hào)登錄

{{ bind_phone ? '綁定手機(jī)' : '手機(jī)登錄'}}

{{codeText}}
切換微信登錄/注冊(cè)
暫不綁定
CRMEB客服

CRMEB咨詢熱線 咨詢熱線

400-8888-794

微信掃碼咨詢

CRMEB開源商城下載 源碼下載 CRMEB幫助文檔 幫助文檔
返回頂部 返回頂部
CRMEB客服