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

铁佛  金牌会员 | 2024-6-29 11:38:47 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 884|帖子 884|积分 2652

在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,添加以下依赖:
  1. group = 'cn.daimajiangxin'
  2. version = '0.0.1-SNAPSHOT'
  3. description ='Spring Security'
  4. dependencies {
  5.     implementation 'org.springframework.boot:spring-boot-starter-web'
  6.     compileOnly 'org.projectlombok:lombok'
  7.     annotationProcessor 'org.projectlombok:lombok'
  8.     runtimeOnly 'mysql:mysql-connector-java:8.0.17'
  9.     // MyBatis-Plus 依赖
  10.     implementation 'com.baomidou:mybatis-plus-spring-boot3-starter:3.5.5'
  11.     implementation 'org.springframework.boot:spring-boot-starter-security'
  12.     implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
  13. }
复制代码
对于Maven,添加以下依赖:
  1. <dependency>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-security</artifactId>  
  4. </dependency>
复制代码
创建实体类

创建一个简单的实体类,映射到数据库表。
  1. package cn.daimajiangxin.springboot.learning.model;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import lombok.Data;
  7. import java.io.Serializable;
  8. @TableName(value ="user")
  9. @Data
  10. public class User implements Serializable {
  11.     /**
  12.      * 学生ID
  13.      */
  14.     @TableId(type = IdType.AUTO)
  15.     private Long id;
  16.     /**
  17.      * 姓名
  18.      */
  19.     private String name;
  20.     @TableField(value="user_name")
  21.     private String userName;
  22.     private String password;
  23.     /**
  24.      * 邮箱
  25.      */
  26.     private String email;
  27.     /**
  28.      * 年龄
  29.      */
  30.     private Integer age;
  31.     /**
  32.      * 备注
  33.      */
  34.     private String remark;
  35.     @TableField(exist = false)
  36.     private static final long serialVersionUID = 1L;
  37. }
复制代码
创建Mapper接口

创建对应的Mapper接口,通常放在与实体类类似的包下,并继承BaseMapper 接口。例如:
  1. package cn.daimajiangxin.springboot.learning.mapper;
  2. import cn.daimajiangxin.springboot.learning.model.User;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. public interface UserMapper extends BaseMapper<User> {
  5. }
复制代码
创建Mapper XML文件

在resources的mapper目录下创建对应的XML文件,例如UserMapper.xml:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="cn.daimajiangxin.springboot.learning.mapper.UserMapper">
  6.     <resultMap id="BaseResultMap" type="cn.daimajiangxin.springboot.learning.model.User">
  7.             <id property="id" column="id" jdbcType="BIGINT"/>
  8.             <result property="name" column="name" jdbcType="VARCHAR"/>
  9.             <result property="user_name" column="userName" jdbcType="VARCHAR"/>
  10.             <result property="password" column="password" jdbcType="VARCHAR"/>
  11.             <result property="email" column="email" jdbcType="VARCHAR"/>
  12.             <result property="age" column="age" jdbcType="INTEGER"/>
  13.             <result property="remark" column="remark" jdbcType="VARCHAR"/>
  14.     </resultMap>
  15.     <sql id="Base_Column_List">
  16.         id,name,email,age,remark
  17.     </sql>
  18.   
  19.     <select id="findAllUsers"  resultMap="BaseResultMap">
  20.      select
  21.        <include refid="Base_Column_List"></include>
  22.      from user
  23.     </select>
  24. </mapper>
复制代码
创建Service 接口

在service目录下服务类接口UserService
  1. package cn.daimajiangxin.springboot.learning.service;
  2. import cn.daimajiangxin.springboot.learning.model.User;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. public interface UserService extends IService<User> {
  5. }
复制代码
创建Service实现类

在service目录下创建一个impl目录,并创建UserService实现类UserServiceImpl
  1. package cn.daimajiangxin.springboot.learning.service.impl;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import cn.daimajiangxin.springboot.learning.model.User;
  4. import cn.daimajiangxin.springboot.learning.service.UserService;
  5. import cn.daimajiangxin.springboot.learning.mapper.UserMapper;
  6. import org.springframework.stereotype.Service;
  7. @Service
  8. public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService{
  9. }
复制代码
创建UserDetailsService实现类
  1. package cn.daimajiangxin.springboot.learning.service.impl;
  2. import cn.daimajiangxin.springboot.learning.model.User;
  3. import cn.daimajiangxin.springboot.learning.service.UserService;
  4. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  5. import jakarta.annotation.Resource;
  6. import org.springframework.security.core.GrantedAuthority;
  7. import org.springframework.security.core.userdetails.UserDetails;
  8. import org.springframework.security.core.userdetails.UserDetailsService;
  9. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  10. import org.springframework.stereotype.Service;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. @Service
  14. public class UserDetailServiceImpl implements UserDetailsService {
  15.     @Resource
  16.     private  UserService userService;
  17.     @Override
  18.     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  19.         LambdaQueryWrapper<User>  queryWrapper=new LambdaQueryWrapper<User>();
  20.         queryWrapper.eq(User::getUserName,username);
  21.         User user=userService.getOne(queryWrapper);
  22.         List<GrantedAuthority> authorities = new ArrayList<>();
  23.         return new org.springframework.security.core.userdetails.User(user.getName(), user.getPassword(),authorities );
  24.     }
  25. }
复制代码
Java设置类

创建一个设置类,并创建SecurityFilterChain 的Bean。
  1. package cn.daimajiangxin.springboot.learning.config;
  2. import jakarta.annotation.Resource;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  6. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  7. import org.springframework.security.core.userdetails.UserDetailsService;
  8. import org.springframework.security.crypto.password.PasswordEncoder;
  9. import org.springframework.security.crypto.password.StandardPasswordEncoder;
  10. import org.springframework.security.web.SecurityFilterChain;
  11. @Configuration
  12. @EnableWebSecurity
  13. public class SecurityConfig   {
  14.     @Resource
  15.     private UserDetailsService userDetailsService;
  16.     @Bean
  17.     public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  18.         http.authorizeHttpRequests(authorizeRequests ->
  19.                         authorizeRequests
  20.                                 .requestMatchers("/", "/home")
  21.                                 .permitAll()
  22.                                 .anyRequest().authenticated() // 其他所有请求都需要认证
  23.                 )
  24.                 .formLogin(formLogin ->
  25.                         formLogin
  26.                                 .loginPage("/login") // 指定登录页面
  27.                                 .permitAll() // 允许所有人访问登录页面
  28.                 )
  29.                 .logout(logout ->
  30.                         logout
  31.                                 .permitAll() // 允许所有人访问注销URL
  32.                 )    // 注册重写后的UserDetailsService实现
  33.                 .userDetailsService(userDetailsService);
  34.         return http.build();
  35.         // 添加自定义过滤器或其他配置
  36.     }
  37.     @Bean
  38.     public PasswordEncoder passwordEncoder() {
  39.         return new StandardPasswordEncoder();
  40.     }
  41. }
复制代码
创建登录页面

在src/main/resources/templates目录下创建一个Thymeleaf模板作为登录页面,例如login.html。
  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4.     <title>登录</title>
  5. </head>
  6. <body>
  7. <form th:action="@{/doLogin}" method="post">
  8.     <label> User Name : <input type="text" name="username"/> </label>
  9.     <label> Password: <input type="password" name="password"/> </label>
  10.     <input type="submit" value="登录"/>
  11. </form>
  12. </body>
  13. </html>
复制代码
创建控制器

创建一个UserController,
  1. package cn.daimajiangxin.springboot.learning.controller;
  2. import cn.daimajiangxin.springboot.learning.model.User;
  3. import cn.daimajiangxin.springboot.learning.service.UserService;
  4. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestParam;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import org.springframework.web.servlet.ModelAndView;
  13. import java.util.List;
  14. @RestController
  15. public class UserController {
  16.     private final UserService userService;
  17.     @Autowired
  18.     public UserController(UserService userService) {
  19.         this.userService = userService;
  20.     }
  21.     @GetMapping({"/login",})
  22.     public ModelAndView login(Model model) {
  23.         ModelAndView mv = new ModelAndView("login");
  24.         return mv ;
  25.     }
  26.     @PostMapping("/doLogin")
  27.     public String doLogin(@RequestParam String username,@RequestParam String password) {
  28.         QueryWrapper<User> queryWrapper=new QueryWrapper<>();
  29.         queryWrapper.eq("user_name",username);
  30.         User user=  userService.getOne(queryWrapper);
  31.         if(user==null){
  32.             return "登录失败,用户没有找到";
  33.         }
  34.         if(! user.getPassword().equals(password)){
  35.             return "登录失败,密码错误";
  36.         }
  37.         return "登录成功";
  38.     }
  39. }
复制代码
登录页面

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

和我一起学习更多出色知识!!!关注我公众号:代码匠心,实时获取推送。
源文来自:https://daimajiangxin.cn
源码地址:https://gitee.com/daimajiangxin/springboot-learning

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

铁佛

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表