-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOAuth2AuthenticationSuccessHandler.java
More file actions
59 lines (45 loc) · 2.34 KB
/
OAuth2AuthenticationSuccessHandler.java
File metadata and controls
59 lines (45 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.gpt.geumpumtabackend.global.oauth.handler;
import com.gpt.geumpumtabackend.global.jwt.JwtHandler;
import com.gpt.geumpumtabackend.global.jwt.JwtUserClaim;
import com.gpt.geumpumtabackend.global.oauth.service.OAuth2UserPrincipal;
import com.gpt.geumpumtabackend.global.oauth.util.RedirectUrlValidator;
import com.gpt.geumpumtabackend.global.oauth.util.StateUtil;
import com.gpt.geumpumtabackend.user.domain.UserRole;
import com.gpt.geumpumtabackend.token.domain.Token;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.IOException;
@Component
@RequiredArgsConstructor
@Slf4j
public class OAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final JwtHandler jwtHandler;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
String encodedState = request.getParameter("state");
String redirectUri = StateUtil.decode(encodedState);
// 2) 화이트리스트 검증
RedirectUrlValidator.validate(redirectUri);
OAuth2UserPrincipal principal = (OAuth2UserPrincipal) authentication.getPrincipal();
Long userId = principal.getUser().getId();
UserRole role = principal.getUser().getRole();
Boolean isWithdrawn = principal.getUser().getDeletedAt() != null;
JwtUserClaim jwtUserClaim = new JwtUserClaim(userId, role, isWithdrawn);
Token token = jwtHandler.createTokens(jwtUserClaim);
// 토큰 붙여서 리다이렉트
String redirectUrl = UriComponentsBuilder.fromUriString(redirectUri)
.queryParam("accessToken", token.getAccessToken())
.queryParam("refreshToken", token.getRefreshToken())
.build().toUriString();
System.out.println(redirectUrl);
response.sendRedirect(redirectUrl);
}
}