springboot+redis实现登录
时间: 2024-09-24 21:22:04 浏览: 43
基于springboot+echarts+redis实现的数据分析及可视化系统源码+项目说明.zip
Spring Boot结合Redis实现登录功能通常涉及以下几个步骤:
1. **添加依赖**:
在`pom.xml`中添加Spring Data Redis和Spring Security的依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. **配置Redis**:
在`application.properties`中设置Redis连接信息:
```
spring.redis.host=localhost
spring.redis.port=6379
```
3. **配置Security**:
创建`SecurityConfig`类,重写WebSecurityConfigurerAdapter,配置Redis作为用户认证存储:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Value("${spring.redis.authKey}")
private String authKey;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/")
.failureHandler(new CustomAuthenticationFailureHandler())
.and()
.logout()
.permitAll();
}
@Bean
public AuthenticationManager authenticationManager() throws Exception {
RedisAuthenticationProvider provider = new RedisAuthenticationProvider();
provider.setConnectionFactory(connectionFactory());
provider.setUserDetailsMapper(userDetailsService);
return provider;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(authKey);
//...其他属性配置
template.setConnectionFactory(factory);
template.afterPropertiesSet();
return template;
}
}
```
4. **用户服务** (`UserDetailsService`实现):
从Redis中读取用户的加密密码并验证:
```java
@Service
public class UserService implements UserDetailsService {
private final JdbcTemplate jdbcTemplate;
@Autowired
public UserService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//从Redis获取用户信息,比如通过username和hash存储
Map<String, Object> userDetails = jedis.get(username);
if (userDetails == null) throw new UsernameNotFoundException("Invalid username");
//解码密码并进一步处理...
}
}
```
5. **登录和注销**:
使用Spring Security提供的表单登录功能,用户输入用户名和密码后会自动进行验证。
阅读全文