国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

Spring Security的簡(jiǎn)單使用

發(fā)布時(shí)間:2021-07-17 21:51 來(lái)源:腳本之家 閱讀:0 作者:つ九鍵按三下 欄目: 編程語(yǔ)言 歡迎投稿:712375056

目錄

什么是Spring Security

  1. Spring Security是一個(gè)功能強大且高度可定制的身份驗證和訪(fǎng)問(wèn)控制框架。它實(shí)際上是保護基于spring的應用程序的標準。
  2. Spring Security是一個(gè)框架,側重于為Java應用程序提供身份驗證和授權。與所有Spring項目一樣,Spring安全的真正強大之處在于它可以輕松地擴展以滿(mǎn)足定制需求
  3. 在用戶(hù)認證方面,Spring Security 框架支持主流的認證方式,包括 HTTP 基本認證、HTTP 表單驗證、HTTP 摘要認證、OpenID 和 LDAP 等。在用戶(hù)授權方面,Spring Security 提供了基于角色的訪(fǎng)問(wèn)控制和訪(fǎng)問(wèn)控制列表(Access Control List,ACL),可以對應用中的領(lǐng)域對象進(jìn)行細粒度的控制。

Spring Security測試

前期準備

  1. 新建一個(gè)springboot項目,導入web模板和thymeleaf模板
  2. 導入靜態(tài)資源

  1. 關(guān)閉thymeleaf緩存spring.thymeleaf.cache=false
  2. 先創(chuàng )建一個(gè)TestController來(lái)測試一下項目是否搭建成功
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class TestController {

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

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

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id){
        return "views/level1/"+id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id){
        return "views/level2/"+id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id){
        return "views/level3/"+id;
    }

}

SpringSecurity的使用

引入spring-boot-starter-security模塊

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

認識SpringSecurity的幾個(gè)重要的類(lèi)

  • WebSecurityConfigurerAdapter:自定義Security策略
  • AuthenticationManagerBuilder:自定義認證策略
  • @EnableWebSecurity:開(kāi)啟WebSecurity模式

SpringSecurity---授權(認真看代碼和注釋?zhuān)?/p>

//授權
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll() //首頁(yè)所有人可以訪(fǎng)問(wèn)
                .antMatchers("/level1/**").hasRole("vip1")   //level1下的頁(yè)面,VIP1可以訪(fǎng)問(wèn)
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //開(kāi)啟自動(dòng)配置的登錄功能,
        //即,沒(méi)有登錄的時(shí)候,除了首頁(yè),其他頁(yè)面都訪(fǎng)問(wèn)不了,這時(shí)候,你訪(fǎng)問(wèn)其他頁(yè)面的時(shí)候,
        //它直接跳轉到它內置的登陸頁(yè)面,讓你登錄 http.formLogin();
        http.formLogin().loginPage("/toLogin");//自定義登錄頁(yè),將自定義的登錄頁(yè)替換掉內置的登錄頁(yè)

        //用來(lái)處理用戶(hù)登錄提交的表單
        http.formLogin().usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login");


        //開(kāi)啟自動(dòng)配置的注銷(xiāo)的功能
        // /logout 注銷(xiāo)請求  http.logout();
        http.csrf().disable();//關(guān)閉csrf功能:跨站請求偽造,默認只能通過(guò)post方式提交logout請求
        http.logout().logoutSuccessUrl("/");//注銷(xiāo)成功就返回首頁(yè)

        //開(kāi)啟記住我功能 http.rememberMe();
        http.rememberMe().rememberMeParameter("remember");//在自定義登錄頁(yè)添加 記住我
    }

SpringSecurity---認證(認真看代碼和注釋?zhuān)?/p>

    //認證
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*
            auth.inMemoryAuthentication().withUser("xiaomi").password("123").roles("vip1")
            這樣寫(xiě)是不行的,會(huì )出現500錯誤。
                原因:密碼沒(méi)有加密
            Spring security 5.0中新增了多種加密方式,也改變了密碼的格式。
            要想我們的項目還能夠正常登陸,需要修改一下configure中的代碼。我們要將前端傳過(guò)來(lái)的密碼進(jìn)行某種方式加密
            spring security 官方推薦的是使用bcrypt加密方式。
            這里通過(guò) passwordEncoder(new BCryptPasswordEncoder())  的方式進(jìn)行加密
       */
        // 在內存中定義認證的規則
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("xiaolong").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("xiaomi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("xiaohu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");

        //在jdbc中定義認證的規則
        //auth.jdbcAuthentication()

    }

啟動(dòng)測試

靜態(tài)資源

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>登錄</title>
    <!--semantic-ui-->
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="external nofollow"  rel="external nofollow"  rel="stylesheet">
</head>
<body>

<!--主容器-->
<div class="ui container">

    <div class="ui segment">

        <div style="text-align: center">
            <h1 class="header">登錄</h1>
        </div>

        <div class="ui placeholder segment">
            <div class="ui column very relaxed stackable grid">
                <div class="column">
                    <div class="ui form">
                        <form th:action="@{/login}" method="post">
                            <div class="field">
                                <label>Username</label>
                                <div class="ui left icon input">
                                    <input type="text" placeholder="Username" name="username">
                                    <i class="user icon"></i>
                                </div>
                            </div>
                            <div class="field">
                                <label>Password</label>
                                <div class="ui left icon input">
                                    <input type="password" name="password">
                                    <i class="lock icon"></i>
                                </div>
                            </div>
                            <div class="field">
                                <input type="checkbox" name="remember">記住我
                            </div>
                            <input type="submit" class="ui blue submit button"/>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div style="text-align: center">
            <div class="ui label">
                </i>注冊
            </div>
            <br><br>
        </div>
        <div class="ui segment" style="text-align: center">
            <h3>Spring Security</h3>
        </div>
    </div>


</div>

<script th:src="@{/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/js/semantic.min.js}"></script>

</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首頁(yè)</title>
    <!--semantic-ui-->
    <link  rel="external nofollow"  rel="external nofollow"  rel="stylesheet">
    <link th:href="@{/css/mystyle.css}" rel="external nofollow"  rel="stylesheet">
</head>
<body>

<!--主容器-->
<div class="ui container">

    <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
        <div class="ui secondary menu">
            <a class="item"  th:href="@{/index}" rel="external nofollow" >首頁(yè)</a>

            <!--登錄注銷(xiāo)-->
            <div class="right menu">
                <!--未登錄-->
                <!--sec:authorize="!isAuthenticated() 未認證即未登錄-->
                <div sec:authorize="!isAuthenticated()">
                    <a class="item" th:href="@{/toLogin}" rel="external nofollow" >
                        <i class="address card icon"></i> 登錄
                    </a>
                </div>

                <!--已登錄-->
                <!--sec:authorize="!isAuthenticated() 已認證即已經(jīng)有用戶(hù)登錄-->
                <div sec:authorize="isAuthenticated()">
                    <a class="item">
                        <i class="address card icon"></i>
                        用戶(hù)名:<span sec:authentication="principal.username"></span>
                        角色:<span sec:authentication="principal.authorities"></span>
                    </a>
                </div>
                <!--注銷(xiāo)-->
                <div sec:authorize="isAuthenticated()">
                    <a class="item" th:href="@{/logout}" rel="external nofollow" >
                        <i class="sign-out icon"></i> 注銷(xiāo)
                    </a>
                </div>


            </div>
        </div>
    </div>

    <div class="ui segment" style="text-align: center">
        <h3>Spring Security</h3>
    </div>

    <div>
        <br>
        <div class="ui three column stackable grid">
            <!-- sec:authorize="hasRole('vip1') 永擁有vip1權限的人才能看到 -->
            <div class="column" sec:authorize="hasRole('vip1')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 1</h5>
                            <hr>
                            <div><a th:href="@{/level1/1}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-1-1</a></div>
                            <div><a th:href="@{/level1/2}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-1-2</a></div>
                            <div><a th:href="@{/level1/3}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-1-3</a></div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- sec:authorize="hasRole('vip2') 永擁有vip2權限的人才能看到 -->
            <div class="column" sec:authorize="hasRole('vip2')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 2</h5>
                            <hr>
                            <div><a th:href="@{/level2/1}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-2-1</a></div>
                            <div><a th:href="@{/level2/2}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-2-2</a></div>
                            <div><a th:href="@{/level2/3}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-2-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- sec:authorize="hasRole('vip3') 永擁有vip3權限的人才能看到 -->
            <div class="column" sec:authorize="hasRole('vip3')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 3</h5>
                            <hr>
                            <div><a th:href="@{/level3/1}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-3-1</a></div>
                            <div><a th:href="@{/level3/2}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-3-2</a></div>
                            <div><a th:href="@{/level3/3}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-3-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    
</div>


<script th:src="@{/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/js/semantic.min.js}"></script>

</body>
</html>

一些其他的小東西

  1. 如果你在測試TestController之前已經(jīng)提前把spring-boot-starter-security這個(gè)依賴(lài)導入,那么你請求首頁(yè)的時(shí)候,程序會(huì )自動(dòng)跳轉到登錄頁(yè)面,任何請求都會(huì )被攔截,停留在登錄頁(yè)面
  2. 如果用戶(hù)還沒(méi)有登錄,你只能看到首頁(yè),你點(diǎn)擊首頁(yè)的任何界面的請求都會(huì )跳轉到默認的登錄頁(yè)面。然后,你通過(guò)你認證過(guò)的用戶(hù)進(jìn)行登錄,登錄成功后會(huì )返回你之前點(diǎn)擊的那個(gè)界面的請求。也就是說(shuō),本來(lái)界面有一個(gè)/level1/1.html你點(diǎn)擊它,沒(méi)登錄,會(huì )直接跳轉到默認的登錄界面,登陸成功后,會(huì )返回/level1/1.html,而不是返回首頁(yè),這是默認的
  3. 分析一下自定義登錄頁(yè)的實(shí)現

以上就是Spring Security的簡(jiǎn)單使用的詳細內容,更多關(guān)于Spring Security的使用的資料請關(guān)注腳本之家其它相關(guān)文章!

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。

免费看黄app软件下载最新| 午夜福利理论片在线观看播放| 少妇高潮喷水惨叫久久久久电影| 丰满少妇被猛男猛烈进入久久| 黑巨人与欧美精品一区| 精品欧美h无遮挡在线看中文|