@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class SecurityController {
@GetMapping("/success")
public ResponseEntity returnLoginInfo(Authentication authentication){
if (authentication == null) throw new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND);
// BusinessLogicException 발생
PrincipalDetails userDetails = (PrincipalDetails) authentication.getPrincipal();
Member member = userDetails.getMember();
MemberDto.Response response = memberMapper.memberToMemberResponseDto(member);
return new ResponseEntity(
new SingleResponseDto<>(response), HttpStatus.OK
);
}
}
1번 문제 해결
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.
...
.and().formLogin().loginProcessingUrl("/api/login")
.defaultSuccessUrl("/auth/success", true)
// 로그인 성공시, /auth/success로 이동
...
return http.build();
}
...
}
@Controller
@RequestMapping("/auth")
public class SecurityController {
@GetMapping("/success")
public String successLogin() {
return "redirect:/auth/info"; // 아래 API로 redirect
}
@Secured("ROLE_USER")
@GetMapping("/info")
public ResponseEntity returnLoginInfo(Authentication authentication){
if (authentication == null) throw new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND);
PrincipalDetails userDetails = (PrincipalDetails) authentication.getPrincipal();
Member member = userDetails.getMember();
MemberDto.Response response = memberMapper.memberToMemberResponseDto(member);
return new ResponseEntity(
new SingleResponseDto<>(response), HttpStatus.OK
);
}
}
1번 문제 해결2
@Controller
@RequestMapping("/auth")
@RequiredArgsConstructor
public class SecurityController {
private final MemberMapper memberMapper;
@GetMapping("/success")
public ResponseEntity successLogin() {
return new ResponseEntity<>(
new Response(200, "로그인 되었습니다."), HttpStatus.OK);
}
@Secured("ROLE_USER")
@GetMapping("/info")
public ResponseEntity returnLoginInfo(Authentication authentication){
if (authentication == null) throw new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND);
PrincipalDetails userDetails = (PrincipalDetails) authentication.getPrincipal();
Member member = userDetails.getMember();
MemberDto.Response response = memberMapper.memberToMemberResponseDto(member);
return new ResponseEntity(
new SingleResponseDto<>(response), HttpStatus.OK
);
}
}
2번 문제 해결
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.
...
.and().formLogin().loginProcessingUrl("/api/login")
.defaultSuccessUrl("/auth/success", true)
// true : 항상 같은 url에서 처리하도록 함
...
return http.build();
}
...
}