From eb961d4c5c6054f064d1eabb5cb820573da76642 Mon Sep 17 00:00:00 2001 From: Fortune00 Date: Mon, 9 May 2022 20:41:25 +0900 Subject: [PATCH] [feat][#6] Implement reload in UserController MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 클라이언트가 리로드 되면, 유저 정보를 새로 받아간다 --- .../gp/cnusambe/config/WebSecurityConfig.java | 1 + .../cnusambe/controller/UserController.java | 38 +++++++++++++++---- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/src/main/java/gp/cnusambe/config/WebSecurityConfig.java b/src/main/java/gp/cnusambe/config/WebSecurityConfig.java index 9deee29..29ae8aa 100644 --- a/src/main/java/gp/cnusambe/config/WebSecurityConfig.java +++ b/src/main/java/gp/cnusambe/config/WebSecurityConfig.java @@ -67,6 +67,7 @@ protected void configure(HttpSecurity http) throws Exception { .and() .authorizeRequests() + .antMatchers("/reload").authenticated() .antMatchers("/**").permitAll() .anyRequest().authenticated(); http.addFilterBefore(authTokenFilter(), UsernamePasswordAuthenticationFilter.class); diff --git a/src/main/java/gp/cnusambe/controller/UserController.java b/src/main/java/gp/cnusambe/controller/UserController.java index c3fc0d6..73507c4 100644 --- a/src/main/java/gp/cnusambe/controller/UserController.java +++ b/src/main/java/gp/cnusambe/controller/UserController.java @@ -1,18 +1,21 @@ package gp.cnusambe.controller; import gp.cnusambe.domain.User; +import gp.cnusambe.error.AccessTokenException; import gp.cnusambe.error.InvalidPasswordException; import gp.cnusambe.error.RefreshTokenException; import gp.cnusambe.payload.request.LoginRequest; import gp.cnusambe.payload.request.LogoutOrRefreshRequest; import gp.cnusambe.payload.request.SignupRequest; import gp.cnusambe.payload.response.LoginResponse; +import gp.cnusambe.payload.response.UserInfoResponse; import gp.cnusambe.security.JwtTokenProvider; import gp.cnusambe.security.UserDetailsImpl; import gp.cnusambe.service.UserDetailsServiceImpl; import gp.cnusambe.service.UserService; import gp.cnusambe.util.RedisUtil; import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; @@ -20,13 +23,18 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.UUID; +import static gp.cnusambe.security.JwtAuthFilter.AUTHORIZATION_HEADER; +import static gp.cnusambe.security.JwtAuthFilter.BEARER_PREFIX; + @RequiredArgsConstructor @RestController public class UserController { @@ -49,7 +57,7 @@ public ResponseEntity signUp(@RequestBody SignupRequest signUpRequest) thr } @PostMapping("/login") - public ResponseEntity login(@RequestBody LoginRequest loginRequest){ + public ResponseEntity login(@RequestBody LoginRequest loginRequest) { Authentication authentication; try { authentication = authenticationManager.authenticate( @@ -57,10 +65,9 @@ public ResponseEntity login(@RequestBody LoginRequest loginReques } catch (BadCredentialsException e) { throw new InvalidPasswordException(); } - SecurityContextHolder.getContext().setAuthentication(authentication); - UserDetailsImpl userDetailsImpl = (UserDetailsImpl)authentication.getPrincipal(); + UserDetailsImpl userDetailsImpl = (UserDetailsImpl) authentication.getPrincipal(); LoginResponse jwtResponse = generateAndSaveToken(userDetailsImpl); return new ResponseEntity<>(jwtResponse, HttpStatus.OK); @@ -76,11 +83,9 @@ public ResponseEntity refreshToken(@RequestBody LogoutOrRefreshRe if (!jwtTokenProvider.validateJwtToken(oldAccessToken)) { throw new RefreshTokenException(); } - - if(!userId.equals(jwtTokenProvider.getUserIdFromJwtToken(oldRefreshToken)) && !userId.equals(jwtTokenProvider.getUserIdFromJwtToken(oldAccessToken))) { + if (!userId.equals(jwtTokenProvider.getUserIdFromJwtToken(oldRefreshToken)) && !userId.equals(jwtTokenProvider.getUserIdFromJwtToken(oldAccessToken))) { throw new RefreshTokenException(); } - UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userDetailsServiceImp.loadUserByUsername(userId); LoginResponse jwtResponse = generateAndSaveToken(userDetailsImpl); deleteToken(uuid, oldAccessToken); @@ -94,6 +99,15 @@ public ResponseEntity logout(@RequestBody LogoutOrRefreshRequest request) return ResponseEntity.noContent().build(); } + @PostMapping("/reload") + public ResponseEntity reload(@RequestHeader HttpHeaders header) { + String token = parseJwt(header); + String userId = jwtTokenProvider.getUserIdFromJwtToken(token); + UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userDetailsServiceImp.loadUserByUsername(userId); + UserInfoResponse userInfoResponse = new UserInfoResponse(userDetailsImpl.getUserId(), userDetailsImpl.getAuthorities().stream().findFirst().get().toString()); + return new ResponseEntity<>(userInfoResponse, HttpStatus.OK); + } + private LoginResponse generateAndSaveToken(UserDetailsImpl userDetailsImpl) { String userId = userDetailsImpl.getUserId(); String uuid = UUID.randomUUID().toString(); @@ -110,6 +124,16 @@ private void deleteToken(String uuid, String oldAccessToken) { if (redisUtil.getData(uuid).isPresent()) { redisUtil.deleteData(uuid); } - redisUtil.setDataExpire(oldAccessToken, oldAccessToken, (int)JwtTokenProvider.TOKEN_EXPIRATION_SECONDS); + redisUtil.setDataExpire(oldAccessToken, oldAccessToken, (int) JwtTokenProvider.TOKEN_EXPIRATION_SECONDS); + } + + private String parseJwt(HttpHeaders request) { + String headerAuth = request.getFirst(AUTHORIZATION_HEADER); + if (StringUtils.hasText(headerAuth) && headerAuth.startsWith(BEARER_PREFIX)) { + return headerAuth.substring(7); + } + else{ + throw new AccessTokenException(); + } } } \ No newline at end of file