controller變更
This commit is contained in:
@ -10,9 +10,8 @@ public class CorsConfig implements WebMvcConfigurer {
|
|||||||
@Override
|
@Override
|
||||||
public void addCorsMappings(CorsRegistry registry) {
|
public void addCorsMappings(CorsRegistry registry) {
|
||||||
registry.addMapping("/api/**") // 允许 /api/ 下的所有请求
|
registry.addMapping("/api/**") // 允许 /api/ 下的所有请求
|
||||||
.allowedOrigins("http://192.168.1.50:5173") // 允许来自该域的请求
|
.allowedOrigins("*") // 允许来自该域的请求
|
||||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的 HTTP 方法
|
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的 HTTP 方法
|
||||||
.allowedHeaders("*") // 允许所有头部
|
.allowedHeaders("*"); // 允许所有头部
|
||||||
.allowCredentials(true); // 允许发送 Cookie
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,9 @@
|
|||||||
package co.jp.app.config.security;
|
package co.jp.app.config.security;
|
||||||
|
|
||||||
|
<<<<<<< HEAD
|
||||||
|
=======
|
||||||
|
import co.jp.app.config.security.filter.JwtAuthenticationFilter;
|
||||||
|
>>>>>>> 2aae88278c46cf937380317aae1f9d229bcb3c37
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.context.annotation.Lazy;
|
import org.springframework.context.annotation.Lazy;
|
||||||
@ -19,11 +23,11 @@ import co.jp.app.config.security.filter.JwtAuthenticationFilter;
|
|||||||
@Configuration
|
@Configuration
|
||||||
public class SecurityConfig {
|
public class SecurityConfig {
|
||||||
|
|
||||||
//private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||||
private final UserDetailsService userDetailsService;
|
private final UserDetailsService userDetailsService;
|
||||||
|
|
||||||
public SecurityConfig(@Lazy JwtAuthenticationFilter jwtAuthenticationFilter, @Lazy UserDetailsService userDetailsService) {
|
public SecurityConfig(@Lazy JwtAuthenticationFilter jwtAuthenticationFilter, @Lazy UserDetailsService userDetailsService) {
|
||||||
//this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||||
this.userDetailsService = userDetailsService;
|
this.userDetailsService = userDetailsService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,29 +49,18 @@ public class SecurityConfig {
|
|||||||
return authenticationConfiguration.getAuthenticationManager();
|
return authenticationConfiguration.getAuthenticationManager();
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Bean
|
|
||||||
// public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
|
||||||
// http.csrf(AbstractHttpConfigurer::disable)
|
|
||||||
// .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
|
||||||
// .authorizeHttpRequests(auth -> auth
|
|
||||||
// .requestMatchers("/api/user/login", "/api/user/register").permitAll()
|
|
||||||
// .anyRequest().authenticated()
|
|
||||||
// )
|
|
||||||
// .authenticationProvider(authenticationProvider())
|
|
||||||
// .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
|
||||||
//
|
|
||||||
// return http.build();
|
|
||||||
// }
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
//暂时开放所有权限
|
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
|
|
||||||
http.csrf(AbstractHttpConfigurer::disable)
|
http.csrf(AbstractHttpConfigurer::disable)
|
||||||
|
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
.authorizeHttpRequests(auth -> auth
|
.authorizeHttpRequests(auth -> auth
|
||||||
.anyRequest().permitAll()
|
.requestMatchers("/api/user/login", "/api/user/register", "/api/inuhouse").permitAll()
|
||||||
);
|
.anyRequest().authenticated()
|
||||||
|
)
|
||||||
|
.authenticationProvider(authenticationProvider())
|
||||||
|
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||||
|
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -11,6 +11,7 @@ import org.springframework.security.web.authentication.WebAuthenticationDetailsS
|
|||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.filter.OncePerRequestFilter;
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
<<<<<<< HEAD
|
||||||
import co.jp.app.service.JwtService;
|
import co.jp.app.service.JwtService;
|
||||||
import jakarta.servlet.FilterChain;
|
import jakarta.servlet.FilterChain;
|
||||||
import jakarta.servlet.ServletException;
|
import jakarta.servlet.ServletException;
|
||||||
@ -18,6 +19,8 @@ import jakarta.servlet.http.HttpServletRequest;
|
|||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
|
||||||
|
=======
|
||||||
|
>>>>>>> 2aae88278c46cf937380317aae1f9d229bcb3c37
|
||||||
@Component
|
@Component
|
||||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
@ -4,6 +4,7 @@ import co.jp.app.common.ApiResponse;
|
|||||||
import co.jp.app.common.ResultCode;
|
import co.jp.app.common.ResultCode;
|
||||||
import co.jp.app.dto.LoginDto;
|
import co.jp.app.dto.LoginDto;
|
||||||
import co.jp.app.dto.RegistrationDto;
|
import co.jp.app.dto.RegistrationDto;
|
||||||
|
import co.jp.app.dto.UserDto;
|
||||||
import co.jp.app.service.JwtService;
|
import co.jp.app.service.JwtService;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
@ -37,40 +38,32 @@ public class UserController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/register")
|
@PostMapping("/register")
|
||||||
public ResponseEntity<?> registerUser(@Valid @RequestBody RegistrationDto registrationDto) {
|
public ResponseEntity<ApiResponse<UserDto>> registerUser(@Valid @RequestBody RegistrationDto registrationDto) {
|
||||||
try {
|
|
||||||
|
|
||||||
UserEntity registeredUser = userService.registerNewUser(registrationDto);
|
UserEntity registeredUser = userService.registerNewUser(registrationDto);
|
||||||
|
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(registeredUser.getEmail()));
|
UserDto userDto = new UserDto();
|
||||||
} catch (Exception e) {
|
|
||||||
|
|
||||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.fail(ResultCode.BAD_REQUEST,null));
|
userDto.setEmail(registeredUser.getEmail());
|
||||||
}
|
userDto.setName(registeredUser.getName());
|
||||||
|
|
||||||
|
return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(userDto));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginDto loginDto) {
|
public ResponseEntity<ApiResponse<Map<String, String>>> authenticateUser(@Valid @RequestBody LoginDto loginDto) {
|
||||||
try {
|
|
||||||
Authentication authentication = authenticationManager.authenticate(
|
|
||||||
new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())
|
|
||||||
);
|
|
||||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
|
||||||
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
|
||||||
|
|
||||||
String jwtToken = jwtService.generateToken(userDetails);
|
Authentication authentication = authenticationManager.authenticate(
|
||||||
|
new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())
|
||||||
|
);
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||||
|
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
||||||
|
|
||||||
Map<String, String> tokenResponse = new HashMap<>();
|
String jwtToken = jwtService.generateToken(userDetails);
|
||||||
tokenResponse.put("token", jwtToken);
|
|
||||||
|
|
||||||
return ResponseEntity.ok(ApiResponse.success(tokenResponse));
|
Map<String, String> tokenResponse = new HashMap<>();
|
||||||
|
tokenResponse.put("token", jwtToken);
|
||||||
|
|
||||||
} catch (BadCredentialsException e) {
|
return ResponseEntity.ok(ApiResponse.success(tokenResponse));
|
||||||
|
|
||||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.fail(ResultCode.UNAUTHORIZED,null));
|
|
||||||
} catch (Exception e) {
|
|
||||||
|
|
||||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiResponse.fail(ResultCode.SERVICE_UNAVAILABLE,null));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
24
src/main/java/co/jp/app/dto/UserDto.java
Normal file
24
src/main/java/co/jp/app/dto/UserDto.java
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package co.jp.app.dto;
|
||||||
|
|
||||||
|
public class UserDto {
|
||||||
|
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
@ -3,6 +3,8 @@ package co.jp.app.service;
|
|||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
|
||||||
|
import co.jp.app.common.ResultCode;
|
||||||
|
import co.jp.app.exception.BusinessException;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
@ -30,10 +32,15 @@ public class UserService implements UserDetailsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public UserEntity registerNewUser(@NotNull RegistrationDto registrationDto) throws Exception {
|
public UserEntity registerNewUser(@NotNull RegistrationDto registrationDto) throws BusinessException {
|
||||||
|
|
||||||
if (userRepository.existsByEmail(registrationDto.getEmail())) {
|
if (userRepository.existsByEmail(registrationDto.getEmail())) {
|
||||||
throw new Exception("error: Email" + registrationDto.getEmail() + " had been used");
|
throw new BusinessException(ResultCode.USER_EMAIL_ALREADY_EXISTS,"error: Email" + registrationDto.getEmail() + " had been used");
|
||||||
|
}
|
||||||
|
|
||||||
|
//密码最短6位限制
|
||||||
|
if (registrationDto.getPassword() == null || registrationDto.getPassword().length() < 6) {
|
||||||
|
throw new BusinessException(ResultCode.USER_PASSWORD_TOO_SHORT);
|
||||||
}
|
}
|
||||||
|
|
||||||
UserEntity newUser = new UserEntity();
|
UserEntity newUser = new UserEntity();
|
||||||
|
66
src/test/java/co/jp/app/dogtestbyadmin/UserServiceTest.java
Normal file
66
src/test/java/co/jp/app/dogtestbyadmin/UserServiceTest.java
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
package co.jp.app.dogtestbyadmin;
|
||||||
|
|
||||||
|
import co.jp.app.dto.LoginDto;
|
||||||
|
import co.jp.app.dto.RegistrationDto;
|
||||||
|
import co.jp.app.dto.UserDto;
|
||||||
|
import co.jp.app.entity.UserEntity;
|
||||||
|
import co.jp.app.repository.UserRepository;
|
||||||
|
import co.jp.app.service.UserService;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
public class UserServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private UserRepository userRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private UserService userService;
|
||||||
|
|
||||||
|
private RegistrationDto registrationDto;
|
||||||
|
private LoginDto loginDto;
|
||||||
|
private UserDto userDto;
|
||||||
|
private UserEntity userEntity;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
registrationDto = new RegistrationDto();
|
||||||
|
registrationDto.setEmail("<EMAIL>");
|
||||||
|
registrationDto.setName("test");
|
||||||
|
registrationDto.setPassword("<PASSWORD>");
|
||||||
|
|
||||||
|
loginDto = new LoginDto();
|
||||||
|
loginDto.setEmail("<EMAIL>");
|
||||||
|
loginDto.setPassword("<PASSWORD>");
|
||||||
|
|
||||||
|
userDto = new UserDto();
|
||||||
|
userDto.setEmail("<EMAIL>");
|
||||||
|
userDto.setName("test");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRegisterNewUser () throws Exception{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRegisterNewUser() throws Exception{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void TestLoadUserByUsername() throws Exception{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user