文章目录

  • SpringSecurity
  • 一、 概述
  • 二、SpringSecurity环境搭建
  • 1.配置template文件
  • 2.导入Pom.xml依赖
  • 3.配置RouterController层
  • 4.配置完测试
  • 三、 权限认证
  • 1.在pom.xml加入下面依赖
  • 2.配置config中 SecurityConfig
  • 四、用户注销和控制权限
  • 1.配置pom.xml
  • 2.配置RouteController
  • 3.权限控制
  • 四、remeberme和主页定制

SpringSecurity

一、 概述

我学习SpringSecurity大概分为四部分:

  • 配置SpringSecurity环境,
  • SpringSecurity认证
  • 用户注销和控制权限
  • RememberMe功能的实现

二、SpringSecurity环境搭建

最终目录大概如下

spring security如何塞入cookie spring security 教程_spring

我们需要配置如下: template和static文件会在后面发

1.配置template文件

2.导入Pom.xml依赖

这里只需要导入web依赖和thymeleaf依赖就可以了

<!--        thymeleaf模板-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
<!--      web-->
        <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>

3.配置RouterController层

package com.kuang.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;
    }
//    这个level是随便写的只不过需要网页中的和这个对应
    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id){
        return "views/level3/"+id;
    }
}

4.配置完测试

输入网址: http://localhost:8080/ 可以跳转到正确页面,并且图各种vip1可以点击进去就可以了

spring security如何塞入cookie spring security 教程_css_02

三、 权限认证

1.在pom.xml加入下面依赖

<!--        配置SpringSecurity依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

2.配置config中 SecurityConfig

首先先继承WebSecurityConfigurereAdapter,源码什么的太麻烦了我就不拔了。
然后重写configure中有httpconfigure中有AuthenticationManagerBuilder方法

package com.kuang.config;
//继承了WebSecuritiyConfigurer并且实现了@EnableWebSecurity注解
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;
//这里是配置EnableSecurtiy适配器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //我这里要定制首页所有人可以访问
        //authorize是授权的意思
        //添加相对应的匹配者有相对应的功能
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

         //这些都是SpringSecurity中jar需要的
        //如果认证失败了就返回tologin页面
        http.formLogin();
    }

    //有授权就有认证
    //通过auth.inMemoryAuthentication认证
    //然后是账号密码等级
    //注意 需要and()拼接
    //在SpringSecurity5新增了加密方式
    //需要加密
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据正常情况是在数据库里面存
        //需要在后面跟上passwordEncoder(new BCryptPasswordEncoder())
        //在密码框里面输入password(new BCryptPasswordEncoder().encode("123456"))
        //当然编码方式有很多种 我只是挑选了其中的一个
          auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                  .withUser("clearlove").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3")
                  .and()
                  .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                  .and()
                  .withUser("ylsl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

四、用户注销和控制权限

1.配置pom.xml

pom.xml中新增springsecurity-thymeleaf整合包

<!--        thymeleaf和springsecurity整合包-->
<!--        作用:主要是将对应的等级匹配相对应的板块-->
        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
<!--       使用spring5的jar包可以解决显示不了sec:authorization的问题-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

2.配置RouteController

这里因为导入了thymeleaf-springsecurity的缘故,
所以我们可以使用RouteController的方法进行登录和注册

package com.kuang.config;
//继承了WebSecuritiyConfigurer并且实现了@EnableWebSecurity注解
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;
//这里是配置EnableSecurtiy适配器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //我这里要定制首页所有人可以访问
        //authorize是授权的意思
        //添加相对应的匹配者有相对应的功能
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
                
//这里是新增的部分        

//定制自动登录页
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");

        //如果认证失败了就返回tologin页面
//        http.formLogin();
        //开启注销功能
        http.logout().logoutSuccessUrl("/");

  
    }

    //有授权就有认证
    //通过auth.inMemoryAuthentication认证
    //然后是账号密码等级
    //注意 需要and()拼接
    //在SpringSecurity5新增了加密方式
    //需要加密
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据正常情况是在数据库里面存
        //需要在后面跟上passwordEncoder(new BCryptPasswordEncoder())
        //在密码框里面输入password(new BCryptPasswordEncoder().encode("123456"))
        //当然编码方式有很多种 我只是挑选了其中的一个
          auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                  .withUser("clearlove").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3")
                  .and()
                  .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                  .and()
                  .withUser("ylsl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

3.权限控制

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
>
<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="stylesheet">
    <link th:href="@{/qinjiang/css/qinstyle.css}" 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}">首页</a>

            <!--登录注销-->
            <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">
                        用户名:<span sec:authentication="name"></span>
<!--                        这里是principal.authorities认证-->
                        权限: <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>
                <!--已登录
                <a th:href="@{/usr/toUserCenter}">
                    <i class="address card icon"></i> admin
                </a>
                -->
            </div>
        </div>
    </div>

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

    <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('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>
    </div>
    
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>

</body>
</html>
  • 首先配置th:sec的环境
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
>
  • 然后,通过sec:authorize来控制属性
<div class="column" sec:authorize="hasRole('vip3')">
  • 这个是显示相对应的用户名和权限
<div sec:authorize="isAuthenticated()">
                    <a class="item">
                        用户名:<span sec:authentication="name"></span>
<!--                        这里是principal.authorities认证-->
                        权限: <span sec:authentication="principal.authorities"></span>
                    </a>
                </div>

四、remeberme和主页定制

package com.kuang.config;
//继承了WebSecuritiyConfigurer并且实现了@EnableWebSecurity注解
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;
//这里是配置EnableSecurtiy适配器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //我这里要定制首页所有人可以访问
        //authorize是授权的意思
        //添加相对应的匹配者有相对应的功能
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //定制自动登录页
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");

        //如果认证失败了就返回tologin页面
//        http.formLogin();
        //开启注销功能
        http.logout().logoutSuccessUrl("/");

        http.csrf().disable();  //关闭跨站请求攻击的功能

        //勾选rememberme登录的时候,向cookie注入了的值
        http.rememberMe().rememberMeParameter("remember");  //记住我功能的实现
    }

    //有授权就有认证
    //通过auth.inMemoryAuthentication认证
    //然后是账号密码等级
    //注意 需要and()拼接
    //在SpringSecurity5新增了加密方式
    //需要加密
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据正常情况是在数据库里面存
        //需要在后面跟上passwordEncoder(new BCryptPasswordEncoder())
        //在密码框里面输入password(new BCryptPasswordEncoder().encode("123456"))
        //当然编码方式有很多种 我只是挑选了其中的一个
          auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                  .withUser("clearlove").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3")
                  .and()
                  .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                  .and()
                  .withUser("ylsl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}