从零开始学Spring Boot系列-集成Spring Security实现用户认证与授权

在Web应用程序中,安全性是一个至关重要的方面。Spring Security是Spring框架的一个子项目,用于提供安全访问控制的功能。通过集成Spring Security,我们可以轻松实现用户认证、授权、加密、会话管理等安全功能。本篇文章将指导大家从零开始,在Spring Boot项目中集成Spring Security,并通过MyBatis-Plus从数据库中获取用户信息,实现用户认证与授权。

环境准备

在开始之前,请确保你的开发环境已经安装了Java、Gradle和IDE(如IntelliJ IDEA或Eclipse)。同时,你也需要在项目中引入Spring Boot、Spring Security、MyBatis-Plus以及数据库的依赖。

创建Spring Boot项目

首先,我们需要创建一个Spring Boot项目。可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。在生成项目时,选择所需的依赖,如Web、Thymeleaf(或JSP)、Spring Security等。

添加Spring Security依赖

在项目的pom.xml(Maven)或build.gradle(Gradle)文件中,添加Spring Security的依赖。 对于Gradle,添加以下依赖:

group = 'cn.daimajiangxin'
version = '0.0.1-SNAPSHOT'
description ='Spring Security'
dependencies {implementation 'org.springframework.boot:spring-boot-starter-web'compileOnly 'org.projectlombok:lombok'annotationProcessor 'org.projectlombok:lombok'runtimeOnly 'mysql:mysql-connector-java:8.0.17'// MyBatis-Plus 依赖implementation 'com.baomidou:mybatis-plus-spring-boot3-starter:3.5.5'implementation 'org.springframework.boot:spring-boot-starter-security'implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

对于Maven,添加以下依赖:

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

创建实体类

创建一个简单的实体类,映射到数据库表。

package cn.daimajiangxin.springboot.learning.model;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;import java.io.Serializable;@TableName(value ="user")
@Data
public class User implements Serializable {/*** 学生ID*/@TableId(type = IdType.AUTO)private Long id;/*** 姓名*/private String name;@TableField(value="user_name")private String userName;private String password;/*** 邮箱*/private String email;/*** 年龄*/private Integer age;/*** 备注*/private String remark;@TableField(exist = false)private static final long serialVersionUID = 1L;
}

创建Mapper接口

创建对应的Mapper接口,通常放在与实体类相同的包下,并继承BaseMapper 接口。例如:

package cn.daimajiangxin.springboot.learning.mapper;import cn.daimajiangxin.springboot.learning.model.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserMapper extends BaseMapper<User> {}

创建Mapper XML文件

在resources的mapper目录下创建对应的XML文件,例如UserMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.daimajiangxin.springboot.learning.mapper.UserMapper"><resultMap id="BaseResultMap" type="cn.daimajiangxin.springboot.learning.model.User"><id property="id" column="id" jdbcType="BIGINT"/><result property="name" column="name" jdbcType="VARCHAR"/><result property="user_name" column="userName" jdbcType="VARCHAR"/><result property="password" column="password" jdbcType="VARCHAR"/><result property="email" column="email" jdbcType="VARCHAR"/><result property="age" column="age" jdbcType="INTEGER"/><result property="remark" column="remark" jdbcType="VARCHAR"/></resultMap><sql id="Base_Column_List">id,name,email,age,remark</sql><select id="findAllUsers"  resultMap="BaseResultMap">select<include refid="Base_Column_List"></include>from user</select>
</mapper>

创建Service 接口

在service目录下服务类接口UserService

package cn.daimajiangxin.springboot.learning.service;import cn.daimajiangxin.springboot.learning.model.User;
import com.baomidou.mybatisplus.extension.service.IService;public interface UserService extends IService<User> {}

创建Service实现类

在service目录下创建一个impl目录,并创建UserService实现类UserServiceImpl

package cn.daimajiangxin.springboot.learning.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.daimajiangxin.springboot.learning.model.User;
import cn.daimajiangxin.springboot.learning.service.UserService;
import cn.daimajiangxin.springboot.learning.mapper.UserMapper;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService{}

创建UserDetailsService实现类

package cn.daimajiangxin.springboot.learning.service.impl;import cn.daimajiangxin.springboot.learning.model.User;
import cn.daimajiangxin.springboot.learning.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.List;@Service
public class UserDetailServiceImpl implements UserDetailsService {@Resourceprivate  UserService userService;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {LambdaQueryWrapper<User>  queryWrapper=new LambdaQueryWrapper<User>();queryWrapper.eq(User::getUserName,username);User user=userService.getOne(queryWrapper);List<GrantedAuthority> authorities = new ArrayList<>();return new org.springframework.security.core.userdetails.User(user.getName(), user.getPassword(),authorities );}
}

Java配置类

创建一个配置类,并创建SecurityFilterChain 的Bean。

package cn.daimajiangxin.springboot.learning.config;import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;@Configuration
@EnableWebSecurity
public class SecurityConfig   {@Resourceprivate UserDetailsService userDetailsService;@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorizeRequests ->authorizeRequests.requestMatchers("/", "/home").permitAll().anyRequest().authenticated() // 其他所有请求都需要认证).formLogin(formLogin ->formLogin.loginPage("/login") // 指定登录页面.permitAll() // 允许所有人访问登录页面).logout(logout ->logout.permitAll() // 允许所有人访问注销URL)    // 注册重写后的UserDetailsService实现.userDetailsService(userDetailsService);return http.build();// 添加自定义过滤器或其他配置}@Beanpublic PasswordEncoder passwordEncoder() {return new StandardPasswordEncoder();}
}

创建登录页面

在src/main/resources/templates目录下创建一个Thymeleaf模板作为登录页面,例如login.html。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>登录</title>
</head>
<body>
<form th:action="@{/doLogin}" method="post"><div><label> User Name : <input type="text" name="username"/> </label></div><div><label> Password: <input type="password" name="password"/> </label></div><div><input type="submit" value="登录"/></div>
</form>
</body>
</html>

创建控制器

创建一个UserController,

package cn.daimajiangxin.springboot.learning.controller;import cn.daimajiangxin.springboot.learning.model.User;
import cn.daimajiangxin.springboot.learning.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;import java.util.List;@RestController
public class UserController {private final UserService userService;@Autowiredpublic UserController(UserService userService) {this.userService = userService;}@GetMapping({"/login",})public ModelAndView login(Model model) {ModelAndView mv = new ModelAndView("login");return mv ;}@PostMapping("/doLogin")public String doLogin(@RequestParam String username,@RequestParam String password) {QueryWrapper<User> queryWrapper=new QueryWrapper<>();queryWrapper.eq("user_name",username);User user=  userService.getOne(queryWrapper);if(user==null){return "登录失败,用户没有找到";}if(! user.getPassword().equals(password)){return "登录失败,密码错误";}return "登录成功";}}

登录页面

运行你的Spring Boot应用程序,用浏览器访问http://localhost:8080/login. 20240601104136


我是代码匠心,和我一起学习更多精彩知识!!!扫描二维码!关注我,实时获取推送。

公众号 源文来自:https://daimajiangxin.cn 源码地址:https://gitee.com/daimajiangxin/springboot-learning

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/37535.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Oracle day15

/*create table f0307 ( id number ,productname varchar2(100) ,parentid number); insert into f0307 values ( 1,汽车,null); insert into f0307 values ( 2,车身,1); insert into f0307 values ( 3,发动机,1); insert into f0307 values ( 4,车门,2); insert into f0307 va…

日期类(java)

文章目录 第一代日期类 Date常用构造方法SimpleDateFormat 日期格式化类日期转字符串&#xff08;String -> Date)字符串转日期 (String->Date) 第二代日期类 Calendar常用字段与如何得到实例对象相关 API 第三代日期类&#xff08;LocalDate\TIme)日期&#xff0c;时间&…

springboot + Vue前后端项目(第二十一记)

项目实战第二十一记 写在前面1. springboot文件默认传输限制2. 安装视频插件包命令3. 前台Video.vue4. 创建视频播放组件videoDetail.vue5. 路由6. 效果图总结写在最后 写在前面 本篇主要讲解系统集成视频播放插件 1. springboot文件默认传输限制 在application.yml文件中添…

pip安装neuralcoref失败ERROR

最终解决的方法如下&#xff1a; git clone https://github.com/huggingface/neuralcoref.git cd neuralcoref pip install -r requirements.txt python setup.py install 原始步骤&#xff1a; 安装 neuralcoref 的依赖&#xff1a; 安装编译 neuralcoref 所需的依赖项&am…

PHP If...Else 语句的深入解析

PHP If...Else 语句的深入解析 在PHP编程语言中&#xff0c;if...else 语句是一种基本且强大的控制结构&#xff0c;它允许根据特定条件执行不同的代码块。这种结构对于决策制定和流程控制至关重要&#xff0c;是每位PHP开发者必须熟练掌握的内容。本文将详细探讨if...else语句…

boost asio异步服务器(4)处理粘包

粘包的产生 当客户端发送多个数据包给服务器时&#xff0c;服务器底层的tcp接收缓冲区收到的数据为粘连在一起的。这种情况的产生通常是服务器端处理数据的速率不如客户端的发送速率的情况。比如&#xff1a;客户端1s内连续发送了两个hello world&#xff01;,服务器过了2s才接…

MCU解决800V电动汽车牵引逆变器的常见设计挑战的3种方式

电动汽车 (EV) 牵引逆变器是电动汽车的。它将高压电池的直流电转换为多相&#xff08;通常为三相&#xff09;交流电以驱动牵引电机&#xff0c;并控制制动产生的能量再生。电动汽车电子产品正在从 400V 转向 800V 架构&#xff0c;这有望实现&#xff1a; 快速充电 – 在相同…

WPF 2024 金九银十 最新 高级 架构 面试题 C#

含入门 初级 中级 高级 不同级别WPF的面试题 相关面试题 redis安装说明书 http://t.csdnimg.cn/iM260 单体并发瓶颈 redis sqlsever mysql多少 http://t.csdnimg.cn/DTXIh Redis高频面试题http://t.csdnimg.cn/FDOnv 数据库SqlServer笔试题 数据库SqlServer笔试题-CSDN博客 SQL…

绝了!Stable Diffusion做AI治愈图片视频,用来做副业简直无敌!10分钟做一个爆款视频保姆教程

一 项目分析 这个治愈类视频的玩法是通过AI生成日常生活场景&#xff0c;制作的vlog&#xff0c;有这样的一个号&#xff0c;发布了几条作品&#xff0c;就涨粉了2000多&#xff0c;点赞7000多&#xff0c;非常的受欢迎。 下面给大家看下这种作品是什么样的&#xff0c;如图所…

探索高效开发神器:Blackbox AI(免费编程助手)

人不走空 &#x1f308;个人主页&#xff1a;人不走空 &#x1f496;系列专栏&#xff1a;算法专题 ⏰诗词歌赋&#xff1a;斯是陋室&#xff0c;惟吾德馨 &#x1f916; 想要代码生成&#xff1f;&#x1f44c; &#x1f4ac; 需要和AI聊天解决难题&#xff1f;&#…

Ubuntu使用c++

Ubuntu使用c 一、安装编译器和开发工具二、创建一个c文件并运行1.创建一个c2.编译运行 一、安装编译器和开发工具 先安装vim sudo apt install vim再安装GUN编译器合集&#xff08;GCC&#xff09; sudo apt install build-essential使用g -v查看版本确定安装成功 二、创建…

Javaweb-初学

1.利用springboot开发一个web应用 简要流程&#xff0c;如下图 2.如何创建一个springboot的项目&#xff0c;下面两张图片是重点关注 第一张图片记得和图片一样改一下路径 第二张就是勾一个选项 3.第一个简单的springboot应用的开发 根据如下步骤进行操作 首先顶部要标识Res…

TensorFlow的学习1.2-基本概念

TensorFlow的学习2-基本概念 1. 张量&#xff08;Tensor&#xff09;2. 变量&#xff08;Variable&#xff09;3. 操作&#xff08;Operation&#xff09;4. 计算图&#xff08;Computational Graph&#xff09;5. 会话&#xff08;Session&#xff09;6. Eager Execution7. 数…

LinkedIn被封原因和解封方法

对于初识领英和对领英生态规则不熟悉的人来说&#xff0c;很容易造成领英账号被封号(被限制登录)的情况&#xff0c;那么如何才能避免和解决领英帐号被封号(被限制登录)的难题呢&#xff1f; 领英帐号被封号或被限制登录主要会有两类情况。 首先要搞清楚&#xff0c; Linkedi…

IP白名单及其作用解析

在网络安全领域&#xff0c;IP白名单是一项至关重要的策略&#xff0c;它允许特定的IP地址或地址范围访问网络资源&#xff0c;从而确保只有受信任的终端能够连接。下面&#xff0c;我们将深入探讨IP白名单的定义、作用以及实施时的关键考虑因素。 一、IP白名单的定义 IP白名单…

HTML与Python生成验证码的对比分析

前言 验证码&#xff08;CAPTCHA&#xff09;是确保用户行为为人类而非机器人自动执行的一种安全机制。通过图形、文字、或其他手段生成复杂的验证码来防止自动化攻击是一种常见的方法。本文将对比分析使用HTML与JavaScript和Python生成验证码的两种方式&#xff0c;探讨各自的…

【scau大数据原理】期末复习——堂测题

一、集群安装知识 启动集群的命令start-all.sh位于 Hadoop安装目录的sbin文件夹 目录下。 bin文件夹下包含常见的Hadoop,yarn命令&#xff1b;sbin命令下包含集群的启动、停止命令。 启动集群的命令start-all.sh包含 同时启动start-dfs.sh和start-yarn.sh 功能。…

AI与Python共舞:如何利用深度学习优化推荐系统?

AI与Python共舞&#xff1a;如何利用深度学习优化推荐系统&#xff1f; 当你在浏览新闻、电影或是购物平台时&#xff0c;那些仿佛读懂你心思的个性化推荐背后&#xff0c;正是AI技术与Python语言的精妙协作。今天&#xff0c;我们将通过一个实际案例&#xff0c;探索如何利用…

Python 面试【中级】

欢迎莅临我的博客 &#x1f49d;&#x1f49d;&#x1f49d;&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:「stormsha的主页」…

已解决javax.xml.bind.MarshalException:在RMI中,参数或返回值无法被编组的正确解决方法,亲测有效!!!

已解决javax.xml.bind.MarshalException&#xff1a;在RMI中&#xff0c;参数或返回值无法被编组的正确解决方法&#xff0c;亲测有效&#xff01;&#xff01;&#xff01; 目录 问题分析 出现问题的场景 服务器端代码 客户端代码 报错原因 解决思路 解决方法 1. 实现…