SpringBoot【五】 Spring Security

Spring Security

安全与权限

安全:虽然属于应用的非功能性需求,但是在 Web 开发中,是非常重要的一个方面,应该在应用开发的初期就考虑进来。

市面上比较有名的安全框架有:Shiro、SpringSecurity

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

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

SpringSecurity 是一个权限框架,对于权限,一般会细分为功能权限,访问权限和菜单权限,比如过滤器、拦截器,原生代码会写的非常繁琐、冗余,所以框架应运而生。

Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分:

  • 用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。
  • 用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

对于用户认证和用户授权,Spring Security 框架都有很好的支持:

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

Spring Security 简介

Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。两个主要目标是 “认证” 和 “授权”(访问控制)。

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

注意这几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

Spring Security 的使用

环境搭建

  1. 新建一个 springboot项目,加入 web 、thymeleaf 依赖

  2. 导入静态资源

  3. controller 跳转

    @Controller
    public class RouteController {
    
        @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

认证和授权

对于当前的测试环境,每个人都可以访问我们提供的资源,现在使用 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#overview

    https://docs.spring.io/spring-security/site/docs/5.4.0-M1/reference/html5/#jc

  3. 编写基础配置类,@Enablexxx 开启某个功能

    @EnableWebSecurity // 开启WebSecurity模式
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            super.configure(http);
        }
    }
    
  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. 测试,发现除了首页都进不去了,这是因为我们目前没有登录的角色,因为请求需要登录的角色拥有对应的权限才可以!

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

    // 开启自动配置的登录功能
    // 没有权限默认会到登录页面 /login,登录失败会重定向到/login?error
    http.formLogin();
    
  7. 测试,发现没有权限的时候,会跳转到登录的页面,这个登录页面是 Spring Security 自带的默认登录页面

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

    // 认证,springboot 2.1.x可以直接使用,定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
        // 这些数据正常应该从数据库中读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan").password("123456").roles("vip2","vip3")
                .and()
                .withUser("root").password("123456").roles("vip1","vip2","vip3")
                .and()
                .withUser("123").password("123456").roles("vip1");
    }
    
  9. 测试,使用这些账号和密码进行登录测试,发现会报错 There is no PasswordEncoder mapped for the id "null"

    报错原因:前端传过来的密码需要进行某种方式加密,否则就无法登录

  10. 修改代码,将密码加密处理,spring security 官方推荐使用 bcrypt 加密方式

    // java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" 密码编码
    // 在 Spring Security 5.0+ 新增了很多的加密方法
    // 要将前端传过来的密码进行某种方式加密,spring security 官方推荐的是使用 bcrypt加密方式
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
        .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
        .and()
        .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
        .and()
        .withUser("123").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
    
  11. 测试,发现,登录成功,并且每个角色只能访问自己认证下的规则

权限控制和注销

  1. 开启自动配置的注销的功能,.logoutSuccessUrl("/") 使注销完毕跳转到首页

    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        // 注销,开启注销功能,跳到首页,如果没有.logoutSuccessUrl("/")会跳转到登录页面
        http.logout().logoutSuccessUrl("/");
    
  2. 在前端 index.html 导航栏中,增加一个注销的按钮

    <a class="item" th:href="@{/logout}">
        <i class="sign-out icon"></i> 注销
    </a>
    
  3. 测试,登录成功后点击注销,注销完毕会跳转到首页

  4. 需求增加:

    • 用户没有登录的时候,导航栏上只显示登录按钮;用户登录之后,导航栏可以显示登录的用户信息及注销按钮;
    • 不同权限的用户看到不同的功能菜单,比如 zhangsan 用户只有 vip2、vip3 功能,那么登录后只显示这两个功能,而 vip1 的功能菜单不显示。
  5. 结合 thymeleaf 实现这些功能,先添加依赖

    <!--thymeleaf 和 security整合包-->
    <dependency>
       <groupId>org.thymeleaf.extras</groupId>
       <artifactId>thymeleaf-extras-springsecurity4</artifactId>
       <version>3.0.4.RELEASE</version>
    </dependency>
    
  6. 实现需求一,修改前端页面,使用 thymeleaf 中的 sec:authorize="isAuthenticated()" 是否认证登录

    首先导入命名空间

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

    修改导航栏,增加认证判断

    <!--登录注销-->
    <div class="right menu">
    
        <!--如果未登录-->
        <div sec:authorize="!isAuthenticated()">
            <a class="item" th:href="@{/login}">
                <i class="address card icon"></i> 登录
            </a>
        </div>
    
        <!--如果已登录:用户名、注销-->
        <div sec:authorize="isAuthenticated()">
            <a class="item">
                用户名:<span sec:authentication="name"></span>
                角色:<span sec:authentication="authorities"></span>
            </a>
        </div>
        <div sec:authorize="isAuthenticated()">
            <a class="item" th:href="@{/logout}">
                <i class="sign-out icon"></i> 注销
            </a>
        </div>
        
    </div>
    
  7. 重启测试,实现了第一个需求:导航栏的效果

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

    http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
    
  9. 实现需求二,不同的用户显示对应的功能模块,修改前端页面,添加:sec:authorize="hasRole('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}"><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('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}"><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>
    
  10. 测试,需求实现了

记住我功能

  1. 开启记住我功能

    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ......
        // 开启记住我功能 cookie 默认保存两周,自定义接收前端的参数
        http.rememberMe().rememberMeParameter("remember");
    }
    
  2. 启动项目测试,发现登录页多了一个记住我功能,登录之后关闭浏览器,然后重新打开浏览器访问,发现用户依旧存在。因为生成了一个名为 remember 的 cookie(默认名称是 remember-me),默认保留两周

  3. 点击注销后 spring security 会帮我们自动删除这个 cookie

定制登录页

前面的登录页面都是 Spring Security 默认的,如果想要使用自己编写的 Login 页面,进行如下操作

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

    // 定制登录页面
    http.formLogin().loginPage("/toLogin");
    
  2. 前端也需要指向我们自己定义的 login 请求

    <a class="item" th:href="@{/toLogin}">
        <i class="address card icon"></i> 登录
    </a>
    
  3. 登录后需要将这些信息发送到哪里也需要配置,login.html 配置提交请求及方式,方式必须为 POST(在 loginPage() 源码中的注释中注明)

    http.formLogin().loginPage("/toLogin")
        .loginProcessingUrl("/login");  //登录表单提交请求
    
    <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>
    
  4. 请求提交上来,我们还需要验证处理,可以配置接收登录的用户名和密码的参数

    http.formLogin()
        .usernameParameter("username") //不写时默认username,不一样时需要根据前端的name属性设置
        .passwordParameter("password") //不写时默认password
        .loginPage("/toLogin").loginProcessingUrl("/login");
    
  5. 测试,点击登录按钮会跳转到我们自己的登录页面,而且登录成功之后会跳转到首页

完整的配置代码

@EnableWebSecurity
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,需要开启登录的页面
        // 定制登录页面
        //.usernameParameter(&quot;username&quot;) 默认 username 不一样时根据前端的name属性设置
       //.passwordParameter(&quot;password&quot;) 默认 password
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");


        // 防止网站攻击 get post
        http.csrf().disable(); // 关闭 csrf功能,登录失败可能存在的原因
        // 注销,开启注销功能,跳到首页
        http.logout().logoutSuccessUrl("/");

        // 开启记住我功能 cookie 默认保存两周,自定义接收前端的参数
        http.rememberMe().rememberMeParameter("remember");
    }

    // 认证,springboot 2.1.x可以直接使用
    // java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" 密码编码
    // 在 Spring Security 5.0+ 新增了很多的加密方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // 这些数据正常应该从数据库中读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("123").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
posted @ 2020-07-12 22:53  Song-zw  阅读(105)  评论(0编辑  收藏  举报