在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 mapper
PUBLIC "-//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 {
@Resource
private UserService userService;
@Override
public 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 {
@Resource
private UserDetailsService userDetailsService;
@Bean
public 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();
// 添加自定义过滤器或其他配置
} @Bean
public 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; @Autowired
public 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.


和我一起学习更多精彩知识!!!关注我公众号:代码匠心,实时获取推送。

源文来自:https://daimajiangxin.cn

源码地址:https://gitee.com/daimajiangxin/springboot-learning

从零开始学Spring Boot系列-集成Spring Security实现用户认证与授权的更多相关文章

  1. 【spring boot 系列】spring data jpa 全面解析(实践 + 源码分析)

    前言 本文将从示例.原理.应用3个方面介绍spring data jpa. 以下分析基于spring boot 2.0 + spring 5.0.4版本源码 概述 JPA是什么? JPA (Java ...

  2. spring boot 2 集成JWT实现api接口认证

    JSON Web Token(JWT)是目前流行的跨域身份验证解决方案.官网:https://jwt.io/本文使用spring boot 2 集成JWT实现api接口验证. 一.JWT的数据结构 J ...

  3. Spring Boot中集成Spring Security 专题

    check to see if spring security is applied that the appropriate resources are permitted: @Configurat ...

  4. [Spring Boot 系列] 集成maven和Spring boot的profile功能

    由于项目的需要, 今天给spirng boot项目添加了profile功能.再网上搜索了一圈,也没有找到满意的参考资料,其实配置并不难,就是没有一个one stop(一站式)讲解的地方,所以有了写这篇 ...

  5. [Spring Boot 系列] 集成maven和Spring boot的profile 专题

    maven中配置profile节点: <project> .... <profiles> <profile> <!-- 生产环境 --> <id& ...

  6. Spring Boot系列(一) Spring Boot准备知识

    本文是学习 Spring Boot 的一些准备知识. Spring Web MVC Spring Web MVC 的两个Context 如下图所示, 基于 Servlet 的 Spring Web M ...

  7. Spring Boot系列(四) Spring Cloud 之 Config Client

    Config 是通过 PropertySource 提供. 这节的内容主要是探讨配置, 特别是 PropertySource 的加载机制. Spring Cloud 技术体系 分布式配置 服务注册/发 ...

  8. Spring Boot系列(四) Spring Boot 之验证

    这节没有高深的东西, 但有一些学习思路值得借鉴. JSR 303 (Bean Validation) Maven依赖 <dependency> <groupId>org.spr ...

  9. Spring Boot系列(三) Spring Boot 之 JDBC

    数据源 类型 javax.sql.DataSource javax.sql.XADataSource org.springframework.jdbc.datasource.embedded,Enbe ...

  10. Spring Boot系列二 Spring @Async异步线程池用法总结

    1. TaskExecutor Spring异步线程池的接口类,其实质是java.util.concurrent.Executor Spring 已经实现的异常线程池: 1. SimpleAsyncT ...

随机推荐

  1. js部分数组方法

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. [Python急救站]基于Transformer Models模型完成GPT2的学生AIGC学习训练模型

    为了AIGC的学习,我做了一个基于Transformer Models模型完成GPT2的学生AIGC学习训练模型,指在训练模型中学习编程AI. 在编程之前需要准备一些文件: 首先,先win+R打开运行 ...

  3. 【爬虫+情感判定+Top10高频词+词云图】"乌克兰"油管热评python舆情分析

    目录 一.分析背景 二.整体思路 三.代码讲解 3.1 爬虫采集 3.2 情感判定 3.3 Top10高频词 3.4 词云图 四.得出结论 五.同步视频演示 六.附完整源码 一.分析背景 乌克兰局势这 ...

  4. 教你用Perl实现Smgp协议

    本文分享自华为云社区<华为云短信服务教你用Perl实现Smgp协议>,作者:张俭. 引言&协议概述 中国电信短消息网关协议(SMGP)是中国网通为实现短信业务而制定的一种通信协议, ...

  5. GDB 中内存打印命令

    GDB 中使用 "x" 命令来打印内存的值,格式为 "x/nfu addr".含义为以 f 格式打印从 addr 开始的 n 个长度单元为 u 的内存值.参数具 ...

  6. 获取list集合中最大值、最小值及索引值

    一.获取最大最小值的同时,获取到最大/小值在list中的索引值 public static void main(String[] args) { List<Integer> numList ...

  7. Linux部署Apache 网站服务器(httpd服务)

    一.项目导入: 某学院组建了校园网,建设了学院网站.现需要架设Web服务器来为学院网站安家,同时在网站上传和更新时,需要用到文件上传和下载,因此还要架设FTP服务器,为学院内部和互联网用户提供WWW. ...

  8. tarjan板子整理

    缩点 stack<int>q; void tarjan(int u) { pre[u]=low[u]=++cnt; q.push(u); vis[u]=1; for(int i=head[ ...

  9. angular 获取DOM元素 多种方式

    第一种方式 ---ViewChild <div #box>我是div----添加在html页面中</div> @ViewChild('box') box: ElementRef ...

  10. vmware迁移虚拟机

    迁移 1.打开"VMware",点击"虚拟机详细信息"可以看到虚拟机的储存路径. 2. 按照储存路径找到虚拟机文件位置,将整个虚拟机文件复制,粘贴到需要转移的路 ...