1. SpringSecurity

1. 介绍:SpringSecurity基于Spring框架,提供了一套Web应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作

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

3. 搭建实验环境
(1)创建初始的springboot项目,导入web以及thymeleaf
(2)导入静态资源
(3)Controller

@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)测试跳转

4. 集成SpringBoot
(1)重要的类

1. WebSecurityConfigurerAdapter:自定义Security策略
2. AuthenticationManagerBuilder:自定义认证策略
3. @EnableWebSecurity:开启WebSecurity模式

SpringSecurity的两个目标是“认证”,“授权”

(2)导入SpringSecurity依赖

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

(3)编写基础的配置类:package com.nelws.config;

@EnableWebSecurity  //开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
    }
}

5. 认证和授权
(1)定制请求的授权规则

@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");
    }
}

springboot actuator 认证 springboot 用户认证_java

(2)测试,发现除了首页都进不去了,因为我们目前没有登陆的角色,因为请求需要登录的角色拥有对应的权限才可以
(3)在configure()方法中开启自动配置的登录功能

@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();
    }
}

springboot actuator 认证 springboot 用户认证_ide_02

(4)测试,发现没有权限的时候,会自动跳到登录页面

springboot actuator 认证 springboot 用户认证_重定向_03


(5)定义访问权限:重写configure(AuthenticationManagerBuilder auth)方法

@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();
    }

    //定义访问权限
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义,也可以从jdbc拿
        auth.inMemoryAuthentication()
                .withUser("wang").password("123456").roles("vip2","vip3")
                .and()
                .withUser("root").password("123456").roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password("123456").roles("vip1");
    }
}

springboot actuator 认证 springboot 用户认证_ide_04


(6)使用账号进行登录测试,发现会报错,原因是没有对用户的密码进行加密

springboot actuator 认证 springboot 用户认证_ide_05


(7)对用户密码进行加密

@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();
    }

    //定义访问权限
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义,也可以从jdbc拿
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("wang").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

springboot actuator 认证 springboot 用户认证_ide_06


(8)再次测试,发现每个角色只能访问认证规则下的页面

6. 控制权限和注销
(1)开启自动配置的注销功能

@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();

        //注销请求
        http.logout();
    }

    //定义访问权限
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义,也可以从jdbc拿
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("wang").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

springboot actuator 认证 springboot 用户认证_spring_07

(2)在前端增加注销按钮

springboot actuator 认证 springboot 用户认证_java_08

(3)进行测试,登陆成功后点击注销,返回到登录页面
(4)想让他注销成功后返回首页

@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();

        //注销请求
        http.logout().logoutSuccessUrl("/");
    }

    //定义访问权限
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义,也可以从jdbc拿
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("wang").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

springboot actuator 认证 springboot 用户认证_重定向_09


(5)新加一个需求:用户没有登陆的时候,导航栏只有登录按钮,用户登录之后,导航栏显示用户的信息以及注销按钮。还有,比如guest用户,只有vip1的功能,那么在登陆后只显示vip1的功能

结合thymeleaf中的功能
sec:authorize="isAuthenticated()":是否认证登录!来显示不同的页面
添加maven依赖
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>
  • 修改前端页面
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<!--登录注销-->
            <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="address card icon"></i> 注销
                    </a>
                </div>

            </div>

springboot actuator 认证 springboot 用户认证_重定向_10


(6)测试

springboot actuator 认证 springboot 用户认证_ide_11


(7)如果注销出现404页面,在springsecurity中关闭csrf功能

springboot actuator 认证 springboot 用户认证_spring_12

(7)继续修改前端页面,显示角色功能块

<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('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>

        </div>

springboot actuator 认证 springboot 用户认证_java_13


(8)测试:例如我现在登录wang这个角色,只有vip2,vip3的权限

springboot actuator 认证 springboot 用户认证_ide_14

7. 记住我与定制登录页

(1)记住我:原理:登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以免登录了。如果点击注销,则会删除这个cookie

springboot actuator 认证 springboot 用户认证_spring_15


(2)定制登录页

  • 在登陆配置设定
  • springboot actuator 认证 springboot 用户认证_重定向_16

  • 前端也要指向自己定义的login请求
  • springboot actuator 认证 springboot 用户认证_spring_17

  • 在login页面,提交方式必须是post
  • springboot actuator 认证 springboot 用户认证_java_18

  • 在登录页加上记住我选项
  • springboot actuator 认证 springboot 用户认证_重定向_19

  • 后端验证处理
  • springboot actuator 认证 springboot 用户认证_java_20