Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat:默认使用内存不连接redis #38

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import github.javaguide.springsecurityjwtguide.security.exception.JwtAccessDeniedHandler;
import github.javaguide.springsecurityjwtguide.security.exception.JwtAuthenticationEntryPoint;
import github.javaguide.springsecurityjwtguide.security.filter.JwtAuthorizationFilter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
Expand All @@ -18,6 +20,7 @@
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Map;

import static java.util.Collections.singletonList;
import static org.springframework.security.config.Customizer.withDefaults;
Expand All @@ -34,8 +37,13 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

private final StringRedisTemplate stringRedisTemplate;

public SecurityConfiguration(StringRedisTemplate stringRedisTemplate) {
private final Map<String, String> cacheMap;

private Boolean redisCacheSwitch;
public SecurityConfiguration(StringRedisTemplate stringRedisTemplate, @Qualifier(value = "cacheMap") Map<String, String> cacheMap, @Value("${redis.cache-switch}") Boolean redisCacheSwitch) {
this.stringRedisTemplate = stringRedisTemplate;
this.cacheMap = cacheMap;
this.redisCacheSwitch = redisCacheSwitch;
}

/**
Expand All @@ -62,7 +70,7 @@ protected void configure(HttpSecurity http) throws Exception {
.anyRequest().authenticated()
.and()
//添加自定义Filter
.addFilter(new JwtAuthorizationFilter(authenticationManager(), stringRedisTemplate))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), stringRedisTemplate, cacheMap, redisCacheSwitch))
// 不需要session(不创建会话)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 授权异常处理
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import github.javaguide.springsecurityjwtguide.security.common.utils.JwtTokenUtils;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand All @@ -15,6 +17,7 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
* @author shuang.kou
Expand All @@ -25,9 +28,17 @@ public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

private final StringRedisTemplate stringRedisTemplate;

public JwtAuthorizationFilter(AuthenticationManager authenticationManager, StringRedisTemplate stringRedisTemplate) {
private final Map<String, String> cacheMap;

private Boolean redisCacheSwitch;
public JwtAuthorizationFilter(AuthenticationManager authenticationManager,
StringRedisTemplate stringRedisTemplate,
Map<String, String> cacheMap,
Boolean redisCacheSwitch) {
super(authenticationManager);
this.stringRedisTemplate = stringRedisTemplate;
this.cacheMap = cacheMap;
this.redisCacheSwitch = redisCacheSwitch;
}

@Override
Expand All @@ -44,7 +55,13 @@ protected void doFilterInternal(HttpServletRequest request,
String tokenValue = token.replace(SecurityConstants.TOKEN_PREFIX, "");
UsernamePasswordAuthenticationToken authentication = null;
try {
String previousToken = stringRedisTemplate.opsForValue().get(JwtTokenUtils.getId(tokenValue));
String previousToken = "";
if (redisCacheSwitch) {
previousToken = stringRedisTemplate.opsForValue().get(JwtTokenUtils.getId(tokenValue));
}else {
previousToken = cacheMap.get(JwtTokenUtils.getId(tokenValue));
}

if (!token.equals(previousToken)) {
SecurityContextHolder.clearContext();
chain.doFilter(request, response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,16 @@
import github.javaguide.springsecurityjwtguide.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
Expand All @@ -25,6 +29,11 @@ public class AuthService {
private final UserService userService;
private final StringRedisTemplate stringRedisTemplate;
private final CurrentUserUtils currentUserUtils;
@Qualifier(value = "cacheMap")
private final Map<String, String> cacheMap ;

@Value("${redis.cache-switch}")
private Boolean redisCacheSwitch;

public String createToken(LoginRequest loginRequest) {
User user = userService.find(loginRequest.getUsername());
Expand All @@ -40,11 +49,20 @@ public String createToken(LoginRequest loginRequest) {
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
String token = JwtTokenUtils.createToken(user.getUserName(), user.getId().toString(), authorities, loginRequest.getRememberMe());
stringRedisTemplate.opsForValue().set(user.getId().toString(), token);
if (redisCacheSwitch) {
stringRedisTemplate.opsForValue().set(user.getId().toString(), token);
}else {
cacheMap.put(user.getId().toString(), token);
}

return token;
}

public void removeToken() {
stringRedisTemplate.delete(currentUserUtils.getCurrentUser().getId().toString());
if (redisCacheSwitch) {
stringRedisTemplate.delete(currentUserUtils.getCurrentUser().getId().toString());
}else {
cacheMap.remove(currentUserUtils.getCurrentUser().getId().toString());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package github.javaguide.springsecurityjwtguide.system.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Configuration
public class MemoryConfig {

@Bean(name = "cacheMap")
public Map<String, String> cacheMap(){
return new HashMap<>();
}
}
3 changes: 3 additions & 0 deletions src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,6 @@ spring:
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0

redis:
cache-switch: false