经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
从零开始学Spring Boot系列-集成Spring Security实现用户认证与授权
来源:cnblogs  作者:代码匠心  时间:2024/7/1 11:29:02  对本文有异议

在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. <select id="findAllUsers" resultMap="BaseResultMap">
  19. select
  20. <include refid="Base_Column_List"></include>
  21. from user
  22. </select>
  23. </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. <div><label> User Name : <input type="text" name="username"/> </label></div>
  9. <div><label> Password: <input type="password" name="password"/> </label></div>
  10. <div><input type="submit" value="登录"/></div>
  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.
20240601104136


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

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

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

原文链接:https://www.cnblogs.com/daimajiangxin/p/18274933

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号