Skip to content

Commit

Permalink
登陆认证把原来用session存储登陆用户信息改为redis
Browse files Browse the repository at this point in the history
  • Loading branch information
YaoLilin committed Nov 9, 2024
1 parent 0bea691 commit 08fbe8f
Show file tree
Hide file tree
Showing 30 changed files with 221 additions and 72 deletions.
6 changes: 6 additions & 0 deletions .idea/google-java-format.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/jsLibraryMappings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const InfoCard = ({data,title,onClick,bottomFlag,style}) => {
cursor: "pointer",
marginRight:'40px',
position:"relative",
overflow:"hidden",
...style
}} onClick={()=>onClick(id)}>
<div>
Expand Down Expand Up @@ -72,11 +73,15 @@ const InfoCard = ({data,title,onClick,bottomFlag,style}) => {
<div style={{paddingTop: "10px"}}>
总结:
</div>
<div>
<div style={{
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis"
}}>
{summary}
</div>
{bottomFlag}
</div>
);
}
export default InfoCard;
export default InfoCard;
9 changes: 9 additions & 0 deletions work-platform-server/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@
<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>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
Expand Down Expand Up @@ -130,6 +134,11 @@
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.8.25</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.personalwork.config;

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 {

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);

// 设置键的序列化方式
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());

// 设置值的序列化方式
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

return template;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.personalwork.constants;

/**
* @author yaolilin
* @desc Redis 键名称
* @date 2024/11/5
**/
public class RedisKeyNames {
private RedisKeyNames() {

}
public static final String PREFIX_LOGIN_USER = "login:user:";
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.personalwork.modal.dto;

import com.personalwork.constants.LoginResultType;
import com.personalwork.modal.entity.UserDo;
import com.personalwork.security.bean.UserDetail;
import lombok.AllArgsConstructor;
import lombok.Data;

Expand All @@ -10,5 +10,5 @@
public class LoginResultDto {
private LoginResultType type;
private String token;
private UserDo user;
private UserDetail user;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.personalwork.modal.vo;

import com.personalwork.constants.Mark;
import lombok.Data;

import java.util.List;
Expand All @@ -15,7 +16,7 @@ public class MonthVo {
private Integer id;
private Integer month;
private Integer year;
private Integer mark;
private Mark mark;
/**
* 工作总结
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package com.personalwork.security;

import com.personalwork.constants.SessionAttrNames;
import com.personalwork.constants.RedisKeyNames;
import com.personalwork.security.bean.UserDetail;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
Expand All @@ -17,6 +18,7 @@
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Map;

/**
* @author yaolilin
Expand All @@ -28,10 +30,11 @@
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
private final UserDetailsService userDetailsService;
private final JwtTokenManager jwtTokenManager;
private final StringRedisTemplate stringRedisTemplate;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException{
throws ServletException, IOException {
//获取token
String token = request.getHeader("token");
if (!StringUtils.hasText(token)) {
Expand All @@ -44,7 +47,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
unauthorizedError(response);
return;
}
if (request.getSession().getAttribute(SessionAttrNames.LOGIN_USER) == null) {
if (!existUserInRedis(token)) {
unauthorizedError(response);
return;
}
Expand All @@ -60,6 +63,13 @@ private void unauthorizedError(HttpServletResponse response) throws IOException
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized");
}

private boolean existUserInRedis(String token) {
String userId = jwtTokenManager.getUserId(token);
Map<Object, Object> userCache = stringRedisTemplate.opsForHash()
.entries(RedisKeyNames.PREFIX_LOGIN_USER + userId);
return !userCache.isEmpty();
}

private void setUserContext(HttpServletRequest request, String username) {
Object loginUser = request.getSession().getAttribute("loginUser");
if (loginUser == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,12 @@
@Slf4j
public class JwtTokenManager {
private static final long THREE_DAY_EXPIRE_TIME = 1000L * 24 * 60 * 60 * 3;
private final SecretProperties secretProperties;

@Autowired
private SecretProperties secretProperties;
public JwtTokenManager(SecretProperties secretProperties) {
this.secretProperties = secretProperties;
}

/**
* 签名生成
Expand Down Expand Up @@ -65,7 +69,7 @@ public String getUserId(String token) {
public String getUserName(String token) {
JWTVerifier verifier = getJwtVerifier();
DecodedJWT jwt = verifier.verify(token);
return jwt.getClaim("username").asString();
return jwt.getClaim("loginName").asString();
}

private JWTVerifier getJwtVerifier() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.personalwork.security.bean;

import lombok.Data;

/**
* @author yaolilin
* @desc 存入 redis 的 user 对象
* @date 2024/11/5
**/
@Data
public class AuthUser {
private String loginName;
private String name;
private Integer id;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.personalwork.security.bean;

import com.personalwork.modal.entity.UserDo;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
Expand All @@ -17,21 +16,20 @@
@Data
@AllArgsConstructor
public class UserDetail implements UserDetails {
private final UserDo user;
private String loginName;
private String name;
private String email;
private String password;
private Integer id;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of();
}

@Override
public String getPassword() {
return user.getPassword();
}

@Override
public String getUsername() {
return user.getName();
return name;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
Expand Down Expand Up @@ -57,7 +58,8 @@ public CustomAuthenticationEntryPoint customAuthenticationEntryPoint() {
* 获取AuthenticationManager(认证管理器),登录时认证使用
*/
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}

Expand All @@ -75,13 +77,15 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// 指定某些接口不需要通过验证即可访问。登录接口肯定是不需要认证的
.requestMatchers(unAuthRequireUrls.toArray(new String[0])).permitAll()
// 静态资源,可匿名访问
.requestMatchers(HttpMethod.GET, "/", "/*.html", "/*/*.html", "/*/*.css", "/*/*.js", "/profile/**").permitAll()
.requestMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**", "/doc.html").permitAll()
.requestMatchers(HttpMethod.GET, "/", "/*.html", "/*/*.html",
"/*/*.css", "/*/*.js", "/profile/**").permitAll()
.requestMatchers("/swagger-ui.html", "/swagger-resources/**",
"/webjars/**", "/*/api-docs", "/druid/**", "/doc.html").permitAll()
.anyRequest().authenticated()
)
// 基于 token,不需要 session
// .sessionManagement(session -> session
// .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(e ->
// 自定义未认证处理
e.authenticationEntryPoint(customAuthenticationEntryPoint())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public String getPublicKey(){
@NoAuthRequired
@PostMapping("/login")
public ResponseEntity<LoginResultVo> login(@Validated @RequestBody UserParam param, HttpServletRequest request) {
LoginResultDto resultDto = authService.login(param,request);
LoginResultDto resultDto = authService.login(param);
LoginResultVo result = getLoginResultVo(resultDto);
if (resultDto.getType() != LoginResultType.SUCCESS) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
Expand All @@ -48,14 +48,14 @@ public ResponseEntity<LoginResultVo> login(@Validated @RequestBody UserParam par
@NoAuthRequired
@PostMapping("/register")
public ResponseEntity<LoginResultVo> register(@Validated @RequestBody RegisterParam param,HttpServletRequest request) {
LoginResultDto resultDto = authService.register(param, request);
LoginResultDto resultDto = authService.register(param);
LoginResultVo result = getLoginResultVo(resultDto);
return ResponseEntity.ok(result);
}

@PostMapping("/logout")
public void logout(HttpServletRequest request) {
authService.logout(request);
public void logout() {
authService.logout();
}

private LoginResultVo getLoginResultVo(LoginResultDto resultDto) {
Expand Down
Loading

0 comments on commit 08fbe8f

Please sign in to comment.