使用SpringSecurity

2023-11-20

前几天写了一个SpringBoot对拦截器的使用,在实际项目中,对一些情况需要做一些安全验证,比如在没有登录的情况下访问特定的页面应该解释的拦截处理。这一篇介绍使用SpringSecurity来做简单的安全控制,由于SpringSecurity比较复杂,如果有不对的地方可以大家一起学习。

新建项目,前端页面使用thymeleaf,加入security依赖,pom文件如下:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dalaoyang</groupId>
    <artifactId>springboot_security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_security</name>
    <description>springboot_security</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.15</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

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


</project>
复制代码

配置文件本文就是将之前整合thymeleaf的配置拿了过来,代码如下:

##端口号
server.port=8888


##去除thymeleaf的html严格校验
spring.thymeleaf.mode=LEGACYHTML5

#设定thymeleaf文件路径 默认为src/main/resources/templates
spring.freemarker.template-loader-path=classpath:/templates
#设定静态文件路径,js,css等
spring.mvc.static-path-pattern=/static/**
# 是否开启模板缓存,默认true
# 建议在开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
# 模板编码
spring.freemarker.charset=UTF-8
复制代码

接下来是这篇文章重要的地方,新建一个SecurityConfig类,继承WebSecurityConfigurerAdapter类,重写configure(HttpSecurity httpSecurity)方法,其中/css/**和/index的资源不需要验证,直接可以请求,/user/**的资源需要验证,权限是USER,/admin/**的资源需要验证,权限是ADMIN,登录地址是/login,登录失败地址是/login_error,异常重定向到 /401,注销跳转到/logout。 注入AuthenticationManagerBuilder,在内存中创建一个用户dalaoyang,密码123的用户,权限是USER,代码如下:

package com.dalaoyang.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.config
 * @email yangyang@dalaoyang.cn
 * @date 2018/4/28
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // /css/**和/index的资源不需要验证,直接可以请求
    // /user/**的资源需要验证,权限是USER /admin/**的资源需要验证,权限是ADMIN
    // 登录地址是/login 登录失败地址是 /login_error
    // 异常重定向到 /401
    // 注销跳转到 /logout
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity
                .authorizeRequests()
                .antMatchers("/css/**","/index").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/admin/**").hasRole("ADMIN")
                .and()
                .formLogin().loginPage("/login").failureUrl("/login_error")
                .and()
                .exceptionHandling().accessDeniedPage("/401");

        httpSecurity.logout().logoutSuccessUrl("/logout");
    }


    //内存中创建用户,用户名为dalaoyang,密码123,权限是USER
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("dalaoyang").password("123").roles("USER");
    }
}

复制代码

创建一个TestController负责跳转,代码如下:

package com.dalaoyang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.controller
 * @email yangyang@dalaoyang.cn
 * @date 2018/4/28
 */
@Controller
public class TestController {

    @RequestMapping("/")
    public String index(){
        return "index";
    }

    @RequestMapping("/index")
    public String index2(){
        return "index";
    }

    @RequestMapping("/user")
    public String user(){
        return "user/index";
    }

    @RequestMapping("/admin")
    public String admin(){
        return "admin/index";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/login_error")
    public String login_error(Model model){
        model.addAttribute("login_error", "用户名或密码错误");
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(Model model){
        model.addAttribute("login_error", "注销成功");
        return "login";
    }

    @RequestMapping("/401")
    public String error(){
        return "401";
    }
}

复制代码

创建一个user/index.html,用于校验USER权限,没有登录的话不能直接访问,代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>user/index</title>
</head>
<body>
user/index

<form th:action="@{/logout}" method="post">
    <input type="submit" value="注销"/>
</form>
</body>
</html>
复制代码

创建一个admin/index.html,只允许ADMIN权限访问,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>admin</title>
</head>
<body>
admin/index
</body>
</html>
复制代码

401页面,用于没有权限跳转:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>401</title>
</head>
<body>
401
</body>
</html>
复制代码

index页面,任何权限都能访问

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
index
</body>
</html>
复制代码

login页面,用于登录

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<h1>login</h1>
<form th:action="@{/login}" method="post">
    <span th:text="${login_error}"></span>
<br/>
    <input type="text" name="username">用户名<br/>
<input type="password" name="password">密码<br/>
    <input type="submit" value="登录">
</form>
</body>
</html>
复制代码

到这里就全部创建完成了,启动项目,访问http://localhost:8888/,如图,可以直接访问。

访问http://localhost:8888/user被拦截到http://localhost:8888/login,如图

先输入错误的密码,如图

然后输入用户名dalaoyang密码123,点击登录结果如图

访问http://localhost:8888/admin,如图,没有权限

我们在回到http://localhost:8888/user点击注销,如图

源码下载 :大老杨码云

个人网站:dalaoyang.cn

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用SpringSecurity 的相关文章

随机推荐

  • 百度会员租赁地址

    http xinjipin com 转载于 https www cnblogs com byfboke p 11602017 html
  • 10:00面试,10:04就出来了 ,问的实在是太...

    从外包出来 没想到竟然死在了另一家厂子 自从加入这家公司 每天都在加班 钱倒是给的不少 所以我也就忍了 没想到12月一纸通知 所有人都不许加班 薪资直降30 顿时有吃不起饭的赶脚 好在有个兄弟内推我去了一家互联网公司 兴冲冲见面试官 没想到
  • Maven搭建私有仓库(私服)

    Nexus简介 作为一个非常优秀且我找不到合适的替代品的二进制包储存库 功能也是非常强大 不单纯只能设置Maven私有仓库 包括我们常见的Yum Docker npm NuGel等等 专业版需要付费 个人用免费版就可以 专业版更加强大 专业
  • Communications link failure官网解释

    官网给的解释 https dev mysql com doc connector j 8 0 en connector j usagenotes troubleshooting html qandaitem 15 1 8 15 8 What
  • Ubuntu下QT程序打包(直接拷贝动态库和可执行文件)

    系统为Ubuntu16 04LTS QT版本为5 12 9 QT默认为动态编译 生成的可执行文件需要有依赖库才能运行 因此在打包的时候需要把程序的依赖库一块打包 这样子做会导致打包的程序非常大 因为依赖库也都一块拷贝了 这种方法好处是快捷
  • TS的类型转换

    TS的类型转换 元组类型转联合类型 元组类型转联合类型2 联合类型转交叉类型 将这个方法拆成两部分来看 U extends any k U gt void never 是第一部分 extends k infer I gt void I ne
  • 数据库——数据库备份与恢复

    目录 原因 数据库的备份与恢复 1 使用MySQLdump命令备份 2 恢复数据库 表的导入和导出 1 表的导出 2 表的导入 原因 尽管采取了一些管理措施来保证数据库的安全 但是不确定的意外情况总是有可能造成数据的损失 例 如意外的停电
  • GooglePlay提审警告(com.google.android.gms:play-services-safetynet:17.0.0)

    1 Goole在今年6月份出的新政策 不在使用safetynet 而使用Play Integrity API 2 项目本身没有使用过safetynet 3 使用了firebase 查阅资料 解决方案如下 implementation pla
  • [python]bokeh学习总结——QuickStart

    bokeh是python中一款基于网页的画图工具库 画出的图像以html格式保存 一个简单的例子 from bokeh plotting import figure output file show output file patch ht
  • 电子信息工程电子信息毕设分享100例(一)

    单片机毕业设计项目分享系列 这里是DD学长 单片机毕业设计及享100例系列的第一篇 目的是分享高质量的毕设作品给大家 包含全面内容 源码 原理图 PCB 实物演示 论文 这两年开始毕业设计和毕业答辩的要求和难度不断提升 传统的单片机项目缺少
  • STM32之音频数据的Flash读取与DAC播放

    文章目录 一 STM32103之内部Flash原理 1 Flash介绍 2 Flash的组成 3 STM32内部框架图 二 SD卡的读写 1 实验过程 2 查看hello txt 3 从SD卡里读出数据 三 Flash地址空间的数据读取 1
  • 说说ERP软件的系统设计--开源软件诞生8

    赤龙ERP系统设计篇 第8篇 用日志记录 开源软件 的诞生 赤龙 ERP 开源地址 点亮星标 感谢支持 与开发者交流 kzca2000 码云 https gitee com redragon redragon erp GitHub http
  • 4、pytest -- fixtures:明确的、模块化的和可扩展的

    pytest fixtures的目的是提供一个固定的基线 使测试可以在此基础上可靠地 重复地执行 对比xUnit经典的setup teardown形式 它在以下方面有了明显的改进 fixture拥有一个明确的名称 通过声明使其能够在函数 类
  • IntelliJ IDEA启动项目端口号被占用怎么解决!

    前言 在使用IDEA开发的时候 经常能碰到端口号被占用的报错 我就经常遇到因为我不知道为啥我IDEA他会在我没用的情况下会闪掉 然后等我发现再打开 运行项目的时候就经常报这个错 不过还有的同学是因为启动多个项目 导致端口号用的一样的所有才出
  • 计算机视觉中的深度学习6: 反向传播

    Slides 百度云 提取码 gs3n 神经网络的梯度下降 我们之前在学习线性分类器的时候 使用Loss函数以及梯度下降法来更新权重 那么对于神经网络 我们该如何计算每层神经元的权重呢 对每层W直接求导 愚蠢的方法 如上公式所示 Loss函
  • IDEA-设置VM启动参数

    点击配置 OK 使用方式 System out println System getProperty parm
  • Mysql5.7安装3306端口报错问题解决方法

    自己尝试重装Mysql 但是过程中遇到端口报错 Mysql5 7下载及安装大家可以去参考其他博客 有很详细的过程 我在安装过程中遇到了3306报错 就是在端口号的旁边会有一个感叹号 由于我是重装 我大概猜到原因是之前的Mysql没有卸载干净
  • MySQL安装之yum安装

    在CentOS7中默认安装有MariaDB 这个是MySQL的分支 但为了需要 还是要在系统中安装MySQL 而且安装完成之后可以直接覆盖掉MariaDB 1 下载并安装MySQL官方的 Yum Repository 1 root Bria
  • Linux基础之SQLite数据库

    嵌入式数据库篇 一 SQLite数据库 二 SQLite数据库安装 三 SQLite的命令用法 四 打开 创建数据库的C接口 五 C代码执行sql语句 六 C代码建表和插入数据 七 总结 一 SQLite数据库 1 简介 轻量化 易用的嵌入
  • 使用SpringSecurity

    前几天写了一个SpringBoot对拦截器的使用 在实际项目中 对一些情况需要做一些安全验证 比如在没有登录的情况下访问特定的页面应该解释的拦截处理 这一篇介绍使用SpringSecurity来做简单的安全控制 由于SpringSecuri