반응형
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
반응형
'itsource' 카테고리의 다른 글
고온 및 저온 관측 가능: '열온' 및 '냉온' 연산자가 있습니까? (0) | 2023.07.26 |
---|---|
장고에서 OR 쿼리 필터를 동적으로 구성하는 방법은 무엇입니까? (0) | 2023.07.21 |
H2 스키마 초기화.SQL 문에 구문 오류가 있습니다. (0) | 2023.07.21 |
플라스크-sqlalchemy 또는 sqlalchemy (0) | 2023.07.21 |
순수 JPA에서 네이티브 쿼리에 대한 기본 데이터베이스 스키마를 구성하는 방법은 무엇입니까? (0) | 2023.07.21 |