feat: 开发中...

This commit is contained in:
2023-03-31 15:22:02 +08:00
parent 0675cdc58a
commit eaf234d062
14 changed files with 123 additions and 39 deletions

View File

@@ -0,0 +1,49 @@
package cn.hamster3.application.blog.config;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.cache.Cache;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Slf4j
@Component
public class AuthTokenFilter extends OncePerRequestFilter {
@Resource(name = "userCache")
private Cache userCache;
public AuthTokenFilter() {
}
@Override
protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
String token = request.getHeader("token");
log.info("request token: {}", token);
if (token == null || token.isBlank()) {
filterChain.doFilter(request, response);
return;
}
UserDetails user = userCache.get(token, UserDetails.class);
if (user == null) {
filterChain.doFilter(request, response);
return;
}
SecurityContext context = SecurityContextHolder.getContext();
UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken.authenticated(
user, "", user.getAuthorities()
);
context.setAuthentication(authentication);
filterChain.doFilter(request, response);
}
}

View File

@@ -1,13 +1,10 @@
package cn.hamster3.application.blog.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
@@ -21,6 +18,11 @@ public class WebConfig {
@Resource
private UserDetailsService userDetailsService;
@Bean(name = "userCache")
public Cache getUserCache() {
return new ConcurrentMapCache("user-cache");
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder(5);
@@ -35,12 +37,12 @@ public class WebConfig {
return new ProviderManager(provider);
}
@Bean
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
// @Bean
// @ConditionalOnMissingBean(ObjectMapper.class)
// public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
// ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// return objectMapper;
// }
}

View File

@@ -2,23 +2,20 @@ package cn.hamster3.application.blog.config.security;
import cn.hamster3.application.blog.entity.repo.UserRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.Collections;
@Slf4j
@Component
@Service
public class BlogUserDetailService implements UserDetailsService {
@Resource
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("find user by email: {}", username);
return userRepo.findByEmailIgnoreCase(username)
.map(user -> new BlogUser(
user.getEmail(),

View File

@@ -21,7 +21,6 @@ public class SecurityConfig {
.anyRequest().authenticated())
.cors().and()
.csrf().disable()
.formLogin().and()
.httpBasic().and()
.build();
}

View File

@@ -13,6 +13,7 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
@@ -29,8 +30,8 @@ public class UserController {
@PostMapping("/login")
@Operation(summary = "登录用户")
public ResponseVO<Void> loginUser(@RequestBody @Valid UserLoginRequireVO requireVO) {
return userService.loginUser(requireVO);
public ResponseVO<Void> loginUser(@RequestBody @Valid UserLoginRequireVO requireVO, HttpServletResponse response) {
return userService.loginUser(requireVO, response);
}
@GetMapping("/current")

View File

@@ -8,13 +8,14 @@ import cn.hamster3.application.blog.vo.user.UserCreateRequireVO;
import cn.hamster3.application.blog.vo.user.UserInfoResponseVO;
import cn.hamster3.application.blog.vo.user.UserLoginRequireVO;
import cn.hamster3.application.blog.vo.user.UserUpdateRequireVO;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.domain.Pageable;
import java.util.UUID;
public interface IUserService {
@NotNull ResponseVO<Void> loginUser(@NotNull UserLoginRequireVO requireVO);
@NotNull ResponseVO<Void> loginUser(@NotNull UserLoginRequireVO requireVO, @NotNull HttpServletResponse response);
@NotNull ResponseVO<UserInfoResponseVO> getCurrentUserInfo();

View File

@@ -20,9 +20,14 @@ import cn.hamster3.application.blog.vo.user.UserInfoResponseVO;
import cn.hamster3.application.blog.vo.user.UserLoginRequireVO;
import cn.hamster3.application.blog.vo.user.UserUpdateRequireVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.cache.Cache;
import org.springframework.data.domain.Pageable;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@@ -48,8 +53,23 @@ public class UserService implements IUserService {
@Resource
private AttachRepository attachRepo;
@Resource(name = "userCache")
private Cache userCache;
@Resource
private AuthenticationManager authenticationManager;
@Override
public @NotNull ResponseVO<Void> loginUser(@NotNull UserLoginRequireVO requireVO) {
public @NotNull ResponseVO<Void> loginUser(@NotNull UserLoginRequireVO requireVO, @NotNull HttpServletResponse response) {
Authentication authenticate = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(requireVO.getEmail(), requireVO.getPassword())
);
log.info("authenticate: {}", authenticate);
if (!authenticate.isAuthenticated()) {
return ResponseVO.failed("login failed.");
}
UUID uuid = UUID.randomUUID();
userCache.put(uuid.toString(), authenticate.getPrincipal());
response.addHeader("token", uuid.toString());
return ResponseVO.success();
}

View File

@@ -14,7 +14,7 @@ import java.util.UUID;
@Slf4j
public class BlogUtils {
@NotNull
@Nullable
public static Authentication getCurrentAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
@@ -23,6 +23,10 @@ public class BlogUtils {
public static Optional<BlogUser> getCurrentUser() {
Authentication authentication = getCurrentAuthentication();
log.info("==============================");
if (authentication == null) {
log.info("current user authentication: null");
return Optional.empty();
}
log.info("current user authentication: {}", authentication);
log.info("current user authentication getPrincipal: {}", authentication.getPrincipal());
log.info("current user authentication getCredentials: {}", authentication.getCredentials());

View File

@@ -1,5 +1,6 @@
package cn.hamster3.application.blog.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.jetbrains.annotations.NotNull;
@@ -7,6 +8,7 @@ import org.jetbrains.annotations.Nullable;
@Data
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseVO<T> {
@NotNull
private Integer code;