itsource

Spring Boot Rest 컨트롤러에서 JWT 토큰 액세스

mycopycode 2023. 7. 21. 21:37
반응형

Spring Boot Rest 컨트롤러에서 JWT 토큰 액세스

Spring Boot로 REST API를 구현하고 있으며 JWT와 Oauth 2로 보안하고 있습니다.

인증 및 액세스 토큰 생성에 문제가 없습니다.

사용자가 요청할 때 컨트롤러에서 JWT 토큰에 액세스하고 싶습니다.

@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<AppUser> getUsers(OAuth2Authentication auth) {
    logger.info("CREDENTIALS:" + auth.getCredentials().toString());
    logger.info("PRINCIPAL:" + auth.getPrincipal().toString());
    logger.info("OAuth2Request:" + auth.getOAuth2Request());
    logger.info("UserAuthentication:" + auth.getUserAuthentication());
    return userService.findAllUsers();
}

위와 같은 방법을 시도했지만 토큰에 도달할 수 없었고 사용자 이름만 나옵니다.스프링 부트에서 이를 달성할 수 있는 방법이 있습니까?

어떤 도움이라도 주시면 감사하겠습니다.

타르타르,

UI가 요청에서 토큰을 헤더로 전송합니까? 그렇다면 다음을 사용하여 해당 값을 얻을 수 있습니다.@RequestHeader메소드의 주석

@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<AppUser> getUsers(OAuth2Authentication auth, @RequestHeader (name="Authorization") String token) 

참고: 이 예에서는Authorization토큰을 포함하는 헤더 이름입니다. 사용자 지정 헤더 이름일 수 있습니다.

건배!

칼이 제공한 답변이 당신의 문제를 해결해 줄 것입니다.

이 답변 외에도 다음 방법을 사용하여 코드의 모든 위치에서 토큰에 액세스할 수 있습니다.

public static String getToken() {
    String token = null;
    var authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
      token = ((OAuth2AuthenticationDetails) authentication.getDetails()).getTokenValue();
    }
    return token;
  }

Spring Security 6에 대해 다음과 같은 접근 방식을 사용했습니다.

@RestController
@RequestMapping(path = "/api/v1/")
public class ApiController {

  public ApiResponse search(final JwtAuthenticationToken auth, @RequestBody final ApiRequest request) throws Exception {
    // ...
  }

}

언급URL : https://stackoverflow.com/questions/54909509/accessing-jwt-token-from-a-spring-boot-rest-controller

반응형