SpringSecurity安全权限实战测试(认证授权,权限控制、注销,记住我,定制首页)

1、实验环境搭建

1. 新建一个初始的springboot项目 web模块 , thymeleaf模块

在这里插入图片描述

2. 导入静态资源

在这里插入图片描述

3. controller跳转

package com.loey.controller;

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

@Controller
public class RouterController {

    @RequestMapping({"/","/index"})
    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;
    }
}

4. 测试实验环境是否OK!

在这里插入图片描述

2、认识SpringSecurity

Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可 以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模 块,进行少量的配置,即可实现强大的安全管理!

记住几个类:
WebSecurityConfigurerAdapter: 自定义Security策略 AuthenticationManagerBuilder:自定义认证策略 @EnableWebSecurity: 开启WebSecurity模式

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)

  • “认证”(Authentication)
    身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。
    身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。
  • “授权” (Authorization)
    授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置, 几乎任何内容)的完全权限。

这个概念是通用的,而不是只在Spring Security 中存在。

3、认证和授权

目前,我们的测试环境,是谁都可以访问的,我们使用 Spring Security 增加上认证和授权的功能

1、引入 Spring Security 模块

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

2、编写 Spring Security 配置类

参考官网:https://spring.io/projects/spring-security

查看我们自己项目中的版本,找到对应的帮助文档:
https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/html5
在这里插入图片描述

3、编写基础配置类

package com.loey.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @ClassName SecurityConfig
 * @Author loey
 * @Date Create in 2021/2/2 12:42
 * @Version 1.0
 **/
@EnableWebSecurity // 开启WebSecurity模式 
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }
}

4、定制请求的授权规则

package com.loey.config;

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;

@EnableWebSecurity // 开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //首页所有人可以访问,功能页只有对应有权限的人才能访问
    //请求授权的规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");


        //没有权限默认会到登录页面
        // 开启自动配置的登录功能
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败
        http.formLogin();
    }

}

5、测试一下:发现除了首页都进自动跳到了登录页面!因为我们目前没有登录的角色,因为请求需要登录的角色拥有 对应的权限才可以!

在这里插入图片描述

6、在 configure() 方法中加入以下配置,开启自动配置的登录功能!

//定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //在内存中定义,也可以在jdbc中去拿....
        auth.inMemoryAuthentication()
                .withUser("guest").password("111").roles("vip1")
                .and()
                .withUser("xixi").password("111").roles("vip1","vip2")
                .and()
                .withUser("root").password("111").roles("vip1","vip2","vip3");
    }

7、测试,我们可以使用这些账号登录进行测试!发现会报错

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id “null”
在这里插入图片描述

8、原因,我们要将前端传过来的密码进行某种方式加密,否则就无法登录,修改代码

//定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //在内存中定义,也可以在jdbc中去拿....
        //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。    
        // 要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密 码进行某种方式加密    
        // spring security 官方推荐的是使用bcrypt加密方式
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("guest").password(new BCryptPasswordEncoder().encode("111")).roles("vip1")
                .and()
                .withUser("xixi").password(new BCryptPasswordEncoder().encode("111")).roles("vip1","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("111")).roles("vip1","vip2","vip3");
 } 

9、测试,发现,登录成功,并且每个角色只能访问自己认证下的规则!搞定4

4、权限控制和注销

1. 开启自动配置的注销的功能

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");


        //没有权限默认会到登录页面
        // 开启自动配置的登录功能
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败
        http.formLogin();

        //开启自动配置的注销的功能      
        // /logout 注销请求
        http.logout();
    }

2. 我们在前端,增加一个注销的按钮, index.html 导航栏中

 <a class="item" th:href="@{/logout}">
     <i class="sign-out icon"></i> 注销
 </a>

3. 我们可以去测试一下,登录成功后点击注销,发现注销完毕会跳转到登录页面!

4. 但是,我们想让他注销成功后,依旧可以跳转到首页,该怎么处理呢?


//开启自动配置的注销的功能      
    // /logout 注销请求
    // .logoutSuccessUrl("/"); 注销成功来到首页
    http.logout().logoutSuccessUrl("/");

5. 测试,注销完毕后,发现跳转到首页OK

在这里插入图片描述

6. 我们现在又来一个需求:用户没有登录的时候,导航栏上只显示登录按钮,用户登录之后,导航栏 可以显示登录的用户信息及注销按钮!还有就是,比如xixi这个用户,它只有 vip2,vip3功 能,那么登录则只显示这两个功能,而vip1的功能菜单不显示!这个就是真实的网站情况了!该如 何做呢?

我们需要结合thymeleaf中的一些功能 sec:
authorize=“isAuthenticated()”:是否认证登录! 来显示不同的页面

Maven依赖:

<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleafextras-springsecurity4 -->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

7. 修改我们的 前端页面

  1. 导入命名空间
    index.html
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<!--登录注销-->
<div class="right menu">
   <!--未登录-->
   <div sec:authorize="!isAuthenticated()">
       <a class="item" th:href="@{/toLogin}">
           <i class="address card icon"></i> 登录
       </a>
   </div>

   <!--已登录-->
   <div sec:authorize="isAuthenticated()">
       <a class="item">
           <i class="address card icon"></i>
           用户名: <span sec:authentication="principal.username"></span>
           角色名: <span sec:authentication="principal.authorities"></span>
       </a>
   </div>

   <div sec:authorize="isAuthenticated()">
       <a class="item" th:href="@{/logout}">
           <i class="sign-out icon"></i> 注销
       </a>
   </div>

启动测试发现无效
原因:
在这里插入图片描述

8. 重启测试,我们可以登录试试看,登录成功后确实,显示了我们想要的页面;

在这里插入图片描述
在这里插入图片描述

9. 如果注销404了,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求 改为post表单提交,或者在spring security中关闭csrf功能;我们试试:在 配置中增加

 http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout 请求

        //开启自动配置的注销的功能      
        // /logout 注销请求
        // .logoutSuccessUrl("/"); 注销成功来到首页
        http.logout().logoutSuccessUrl("/");

10. 我们继续将下面的角色功能块认证完成!

 <div>
        <br>
        <div class="ui three column stackable grid">
            <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}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                            <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                            <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="column" sec:authorize="hasRole('vip12')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 2</h5>
                            <hr>
                            <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
                            <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
                            <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

            <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}"><i class="bullhorn icon"></i> Level-3-1</a></div>
                            <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
                            <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

11. 测试一下!

在这里插入图片描述

12. 权限控制和注销搞定!

5、记住我

现在的情况,我们只要登录之后,关闭浏览器,再登录,就会让我们重新登录,但是很多网站的情况, 就是有一个记住密码的功能,这个该如何实现呢?很简单

1. 开启记住我功能

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");


        //没有权限默认会到登录页面
        // 开启自动配置的登录功能
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败
        http.formLogin();

        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout 请求

        //开启自动配置的注销的功能      
        // /logout 注销请求
        // .logoutSuccessUrl("/"); 注销成功来到首页
        http.logout().logoutSuccessUrl("/");

        //记住我
        http.rememberMe();


    }

2. 我们再次启动项目测试一下,

发现登录页多了一个记住我功能,我们登录之后关闭 浏览器,然后重 新打开浏览器访问,发现用户依旧存在!
在这里插入图片描述

思考:如何实现的呢?其实非常简单 我们可以查看浏览器的cookie
在这里插入图片描述

3. 我们点击注销的时候,可以发现,spring security 帮我们自动删除了这个 cookie

在这里插入图片描述

4. 结论:

登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以 免登录了。如果点击注销,则会删除这个cookie,具体的原理我们在JavaWeb阶段都讲过了,这里 就不在多说了!

6、定制登录页

现在这个登录页面都是spring security 默认的,怎么样可以使用我们自己写的Login界面呢?

1. 在刚才的登录页配置后面指定 loginpage

http.formLogin().loginPage("/toLogin");

2. 然后前端也需要指向我们自己定义的 login请求

<div sec:authorize="isAuthenticated()">
	<a class="item" th:href="@{/toLogin}">
       <i class="sign-out icon"></i> 注销
   </a>
</div>

3. 我们登录,需要将这些信息发送到哪里,我们也需要配置,login.html 配置提交请求及方式,方式 必须为post: 在 loginPage()源码中的注释上有写明:

在这里插入图片描述

4. 这个请求提交上来,我们还需要验证处理,怎么做呢?我们可以查看 formLogin() 方法的源 码!我们配置接收登录的用户名和密码的参数!

  //没有权限默认会到登录页面
        // 开启自动配置的登录功能
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login");//登陆表单提交请求

5. 在登录页增加记住我的多选框

<div class="field">
  <input type="checkbox" class="ui" name="remeber">记住我
</div>

6. 后端验证处理!

 //定制记住我的参数
        http.rememberMe().rememberMeParameter("remember");

7. 测试,OK

7、完整配置代码SecurityConfig.java

package com.loey.config;

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.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity // 开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //首页所有人可以访问,功能页只有对应有权限的人才能访问
    //请求授权的规则
    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");


        //没有权限默认会到登录页面
        // 开启自动配置的登录功能
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login");//登陆表单提交请求

        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout 请求

        //开启自动配置的注销的功能      
        // /logout 注销请求
        // .logoutSuccessUrl("/"); 注销成功来到首页
        http.logout().logoutSuccessUrl("/");

    //定制记住我的参数
        http.rememberMe().rememberMeParameter("remember");

    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //在内存中定义,也可以在jdbc中去拿....
        //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。    
        // 要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密 码进行某种方式加密    
        // spring security 官方推荐的是使用bcrypt加密方式
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("guest").password(new BCryptPasswordEncoder().encode("111")).roles("vip1")
                .and()
                .withUser("xixi").password(new BCryptPasswordEncoder().encode("111")).roles("vip1","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("111")).roles("vip1","vip2","vip3");
    }


}

8、完整的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.loey</groupId>
    <artifactId>springboot-07-security</artifactId>
    <version>1.0.0</version>
    <name>springboot-07-security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleafextras-springsecurity4 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>


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

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

       <!-- <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>-->

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值