zoukankan      html  css  js  c++  java
  • SpringBoot学习笔记(十)

    本文主要介绍SpringBoot:集成SpringSecurity

    • SpringSecurity官方介绍

    image

    Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。

    Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求。

    一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。

    • 用户认证:指的是验证某个用户是否为系统中的合法主体
      也就是说用户能否访问该系统,用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。

    • 用户授权:指的是验证某个用户是否有权限执行某个操作
      在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

    对于上面提到的两种应用情景,Spring Security 框架都有很好的支持。在用户认证方面,Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID 和 LDAP 等。在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制。

    • SpringSecurity基本原理(图片来自百度搜索)

    image

    • 入门实战:

    1.介绍项目内容

    image

    2.新建SpringBoot项目:springboot-security,引入thymeleaf引擎

    image

    image

    3.编写静态资源
    (在 templates 下创建,结构如下:)
    image

    注:index.html 文件,在下方会有代码演示,可以拼凑成完整的

    4.编写controller

    image

    package com.zhou.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/toLogin";
        }
    
        @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;
        }
    }
    

    5.运行一下,测试环境是否OK!

    • SpringSecurity 认证和授权

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

    1.引入 Spring Security 模块

    image

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

    2.观察 Spring Security 配置类

    探索一下 WebSecurityConfiguration 类的源码:

    image

    发现其拥有一个过滤功能的方法 springSecurityFilterChain()

    image

    WebSecurityConfigurerAdapter 做了哪些事情

    image

    参考官网:https://docs.spring.io/spring-security/site/docs/5.4.5/reference/html5/

    比如,官方文档提到的在验证Username and Password时,采用一下做法:

    image

    3.开始编写配置类:SecurityConfig

    image

    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
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
        }
    }
    

    4.定制(请求的)授权规则

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

    5.Run 测试:http://localhost:8081
    发现只有首页能进去,访问其他页面,控制台输出:
    org.thymeleaf.exceptions.TemplateInputException: Error resolving template [/login], template might not exist or might not be accessible by any of the configured Template Resolvers

    原因:目前没有登录的角色,因为请求需要登录的角色拥有对应的权限才可以。

    解决:在configure()方法中开启自动配置的登录功能:

    image

    http.formLogin();
    

    6.继续访问:http://localhost:8081/login 弹出页面

    image

    并且,重定向到 http://localhost:8081/login?error 表示登录失败

    image

    7.定义认证规则:重写 configure(AuthenticationManagerBuilder auth)方法

        //定义认证规则
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //在内存中定义,也可以在jdbc中去拿.
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("zhouzhou").password"123").roles("vip2")
                    .and()
                    .withUser("root").password("123").roles("vip1", "vip2")
                    .and()
                    .withUser("guest").password("123").roles("vip1", "vip2","vip3");
        }
    

    8.Run 测试,登录用户名和密码

    报错:
    java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

    image

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

    解决:spring security 官方推荐的是使用bcrypt加密方式

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //在内存中定义,也可以在jdbc中去拿.
            //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
            //要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("zhouzhou").password(new BCryptPasswordEncoder().encode("123")).roles("vip2")
                    .and()
                    .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2")
                    .and()
                    .withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2","vip3");
        }
    
    1. Run 测试,登录成功,并且每个角色只能访问自己认证下的规则
    • 权限控制和注销

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

    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //省略上面重复代码
        //开启自动配置的注销的功能:logout 注销请求
        http.logout();
    }
    

    2.在前端(index.html),增加一个注销的按钮

    <!--前端开启注销功能-->
    <div sec:authorize="isAuthenticated()">
    	<a class="item" th:href="@{/logout}">注销</a>
    </div>
    

    3.Run 测试,登录成功后点击注销(发现注销完毕会跳转到登录页面)

    4.设置注销成功后,依旧可以跳转到首页

    // .logoutSuccessUrl("/"); 注销成功来到首页
    http.logout().logoutSuccessUrl("/");
    

    5.Run 测试跳转成功了

    此时,虽然做到了认证和授权,但是页面显示需要优化,比如,下面的问题:

    image

    注:利用 thymeleaf 中的 sec:authorize="isAuthenticated()"sec:authorize="hasRole('')",完成认证功能

    1.导入依赖

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

    2.修改前端页面

    a.导入命名空间

    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
    

    b.修改 登录和注销(增加认证判断)

    <!--登录注销-->
    <div class="right menu">
        <!--如果未登录-->
        <div sec:authorize="!isAuthenticated()">
            <a class="item" th:href="@{/login}">登录</a>
        </div>
        <!--如果已登录-->
        <div sec:authorize="isAuthenticated()">
            <a class="item">
                <i class="address card icon"></i>
                用户名:<span sec:authentication="principal.username"></span>&nbsp;&nbsp;
                特权:<span sec:authentication="principal.authorities"></span>
                </br>
            </a>
        </div>
        <!--前端开启注销功能-->
        <div sec:authorize="isAuthenticated()">
            <a class="item" th:href="@{/logout}">注销</a>
        </div>
    </div>
    

    3.Run 测试 达到预期效果

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

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

    4.修改 用户和权限(增加认证判断)

    <!-- sec:authorize="hasRole('vip1')" -->
    <div sec:authorize="hasRole('vip1')">
            <div>
                <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 sec:authorize="hasRole('vip2')">
        <div>
            <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 sec:authorize="hasRole('vip3')">
        <div>
            <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>
    

    5.Run 测试OK!权限控制和注销完成。

    • 记住我 功能

    此时,虽然是在登录状态,但是只要关闭浏览器(不是注销),重新访问,就会要求我们重新登录。

    1.开启记住我功能

        //定制请求的授权规则
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //省略上面重复代码
            //记住我
            http.rememberMe();
        }
    

    2.Run 测试

    发现登录页多了一个记住我功能,登录之后关闭浏览器,然后重新打开浏览器访问,发现用户依旧存在。

    image

    • 记住我功能如何实现的?

    查看浏览器的cookie

    image

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

    image

    • 定制登录页

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

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

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

    查看 FormLoginConfigurer 类的源码:(阅读注释部分)

    image

    image

    (login.html 配置提交请求及方式,方式必须为post)

    2.编写一个自定义 登录页

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>My Login</title>
    </head>
    <body>
    <form th:action="@{/toLogin}" method="post">
        <div>
            <label>用户名:</label>
            <div >
                <input type="text" name="username">
            </div>
        </div>
        <div>
            <label>密码:</label>
            <div>
                <input type="password" name="password">
            </div>
        </div>
        <br/>
        <input type="checkbox" name="remember">记住我
        <br/>
        <input type="submit" value="查询特权"/>
    </form>
    </body>
    </html>
    

    3.修改 index.html 的th:href=""

    <!--登录注销-->
    <div class="right menu">
        <!--如果未登录-->
        <div sec:authorize="!isAuthenticated()">
            <a class="item" th:href="@{/toLogin}">登录</a>
        </div>
        <!--如果已登录-->
        <div sec:authorize="isAuthenticated()">
            <a class="item">
                <i class="address card icon"></i>
                用户名:<span sec:authentication="principal.username"></span>&nbsp;&nbsp;
                特权:<span sec:authentication="principal.authorities"></span>
                </br>
            </a>
        </div>
        <!--前端开启注销功能-->
        <div sec:authorize="isAuthenticated()">
            <a class="item" th:href="@{/toLogin}">注销</a>
        </div>
    </div>
    

    4.编写controller

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

    5.提交的请求,怎样做验证处理

            http.formLogin()
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginPage("/toLogin")
                    .loginProcessingUrl("/toLogin");
    
            http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
            http.logout().logoutSuccessUrl("/toLogin");
    

    6.登录页,添加记住我选择框

    <input type="checkbox" name="remember"> 记住我
    

    7.后端验证处理

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

    8.Run 测试 OK!

    image

    个人学习笔记,针对本人在自学中遇到的问题。

  • 相关阅读:
    【ybt金牌导航4-7-3】【luogu P3437】三维俄罗斯方块 / TET-Tetris 3D
    【ybt金牌导航4-6-6】【luogu P2617】【ybt金牌导航4-7-4】动态排名 / Dynamic Rankings
    【ybt金牌导航4-6-4】【luogu P3402】可持久化并查集
    【luogu P5055】【模板】可持久化文艺平衡树
    【ybt金牌导航4-6-2】【luogu P3835】可持久化平衡树
    【luogu P4278】【ybt金牌导航4-5-2】带插入区间K小值(树套树做法)
    【luogu P3369】普通平衡树(fhq Treap 做法)
    【ybt金牌导航4-4-2】【luogu P2042】维护数列(fhq Treap 做法)
    【luogu P3369】普通平衡树(Treap 做法)
    匿名函数
  • 原文地址:https://www.cnblogs.com/1693977889zz/p/14584718.html
Copyright © 2011-2022 走看看