当前位置: 首页 > news >正文

Java Spring Boot 应用集成 Spring Security 使用 Redis 存储用户信息

目录

    • 一、项目依赖
    • 二、配置 Redis
    • 三、配置 Spring Security
    • 四、配置 Redis 存储用户信息
    • 五、创建用户详情服务
    • 六、创建控制器
    • 七、创建登录页面
    • 八、总结

在现代 Web 开发中,使用 Redis 存储用户信息不仅可以提高系统的性能,还能有效降低数据库的访问压力。本文将介绍如何在 Spring Boot 应用中集成 Spring Security,并使用 Redis 存储用户信息,实现高效的用户认证和授权。

一、项目依赖

pom.xml 中添加以下依赖:

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

二、配置 Redis

application.properties 文件中添加 Redis 配置:

# Redis 配置
spring.redis.host=localhost
spring.redis.port=6379

三、配置 Spring Security

创建一个配置类 SecurityConfig.java

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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/", "/home", "/login").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").defaultSuccessUrl("/home", true).and().logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout");}@Beanpublic BCryptPasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

四、配置 Redis 存储用户信息

创建一个 RedisConfig.java 配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());return template;}
}

五、创建用户详情服务

创建一个 CustomUserDetailsService.java 类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;import java.util.Collections;
import java.util.concurrent.TimeUnit;@Service
public class CustomUserDetailsService implements UserDetailsService {private final RedisTemplate<String, Object> redisTemplate;private final PasswordEncoder passwordEncoder;@Autowiredpublic CustomUserDetailsService(RedisTemplate<String, Object> redisTemplate, PasswordEncoder passwordEncoder) {this.redisTemplate = redisTemplate;this.passwordEncoder = passwordEncoder;}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 尝试从 Redis 中获取用户信息Object user = redisTemplate.opsForValue().get("user:" + username);if (user != null) {return new org.springframework.security.core.userdetails.User(username,passwordEncoder.encode("123456"),Collections.emptyList());}// 如果 Redis 中没有用户信息,可以从数据库加载(此处简化为直接返回)return new org.springframework.security.core.userdetails.User(username,passwordEncoder.encode("123456"),Collections.emptyList());}// 可以添加方法将用户信息存储到 Redispublic void saveUserToRedis(String username, Object user, long expirationInMinutes) {redisTemplate.opsForValue().set("user:" + username, user, expirationInMinutes, TimeUnit.MINUTES);}
}

六、创建控制器

创建一个 LoginController.java 类:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class LoginController {@GetMapping("/login")public String login() {return "login";}@GetMapping("/home")public String home() {return "home";}
}

七、创建登录页面

src/main/resources/templates 目录下创建 login.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Login</title>
</head>
<body><h2>Login</h2><form action="/login" method="post"><div><label for="username">Username:</label><input type="text" id="username" name="username"></div><div><label for="password">Password:</label><input type="password" id="password" name="password"></div><div><button type="submit">Login</button></div></form>
</body>
</html>

八、总结

通过本文的介绍,你已经掌握了如何在 Spring Boot 应用中集成 Spring Security,并使用 Redis 存储用户信息。使用 Redis 存储用户信息可以提高系统的性能和响应速度,特别是在用户数量较多的情况下。希望本文的内容能够帮助你更好地应用 Spring Security 和 Redis,构建高效、安全的 Web 应用。

相关文章:

  • 小白的进阶之路-人工智能从初步到精通pytorch的基本流程详解-1
  • 深入解析Spring Boot与Spring Cloud在微服务架构中的最佳实践
  • nginx日志
  • 人员管理2302版本
  • CVE-2022-22963源码分析与漏洞复现
  • 类autosar的os系统实现
  • 说一下响应状态码有哪些?
  • 语言幻觉测试用例及相关策略总结
  • SAP学习笔记 - 开发13 - CAP 之 添加数据库支持(Sqlite)
  • plc基础知识整理(三菱)
  • SVN与蓝盾流水线
  • 依赖错误终结者:AI 项目管理中的故障排查指南
  • python训练营day29
  • C++类与对象--5 运算符重载
  • 【Canvas与图标】圆角方块蓝星CSS图标
  • 纯前端实现图文识别 OCR
  • 异步委托执行管理器:更新
  • 嵌入式培训之数据结构学习(六)树(二叉树)、哈希表、内核链表
  • 理解 Swift 逃逸闭包与 implicit `self`
  • virtual下Ubuntu24.04版本上配置网络与外网和宿主机之间互通
  • 南皮县网站建设价格/seo建站优化推广
  • 卫浴网站设计/新手如何自己做网站
  • java 做网站/抖音seo排名
  • 公安局网站备案流程/爱站seo查询
  • 珠海市网站建设企业/百度搜索关键词优化
  • 云一网站建设/宁波seo排名优化价格