2012-09-17 4 views
13

:Spring OAuth (OAuth2) : Spring MVC 컨트롤러에서 클라이언트 자격증 명을 얻으려면 어떻게해야합니까? 이 조각에서

@RequestMapping(method = GET) 
public List<Place> read(Principal principal) { 
    principal.getName(); 
} 

principal.getName() 것은 나에게 사용자 식별을 제공하지만 클라이언트 자격 증명 (내 API를 사용하는 클라이언트 => 응용 프로그램)을받을 수있는 방법이 필요합니다. 어떻게해야합니까?

답변

12

@ luke-taylor 답을 기반으로 합리적인 해결책을 찾았습니다.

@RequestMapping(method = GET) 
public List<Place> read(OAuth2Authentication auth) { 
    auth.getOAuth2Request().getClientId() 
} 
+0

그러면 클라이언트 ID 애플리케이션이 아닌 Principal 사용자가 리턴되었습니다. – BigDong

+1

업데이트 된 버전 :'auth.getOAuth2Request(). getClientId()' – Cataclysm

15

클라이언트 ID는 Authentication 개체에서 사용할 수 있습니다.이 개체는 주체를 캐스팅하거나 스레드 로컬 보안 컨텍스트에서 직접 얻을 수 있습니다. 당신이 컨트롤러에 직접 그 코드를 삽입하지 않으려면

Authentication a = SecurityContextHolder.getContext().getAuthentication(); 

String clientId = ((OAuth2Authentication) a).getAuthorizationRequest().getClientId(); 

같은 것을, 당신은 this answer에 설명 된대로 별도의 상황에 맞는 접근을 구현하고 대신에 그를 주입 할 수 있습니다.

+0

좋은 대답을, 포스트 날짜가 조금 오래 제외. 스프링 부트 1.3.3은 getAuthorizationRequest() 대신에 getOAuth2Request()를 사용합니다. – tao

3

HandlerMethodArgumentResolver 옵션을 조금 더 플러스합니다. 다음 지원하기 위해 :

@RequestMapping(
    value = WEB_HOOKS, 
    method = RequestMethod.GET, 
    produces = MediaType.APPLICATION_JSON_VALUE) 
@ResponseStatus(HttpStatus.OK) 
public List<SomeDTO> getThoseDTOs(@CurrentClientId String clientId) 
{ 
    // Do something with clientId - it will be null if there was no authentication 
} 

우리는 우리의 응용 프로그램 컨텍스트에 등록 된 HandlerMethodArgumentResolver가 필요합니다을 (나를 위해이는 WebMvcConfigurerAdapter 내부이었다). 내 HandlerMethodArgumentResolver은 다음과 같습니다

public class OAuth2ClientIdArgumentResolver implements HandlerMethodArgumentResolver { 

    @Override 
    public boolean supportsParameter(MethodParameter parameter) { 
     return parameter.getParameterAnnotation(CurrentClientId.class) != null 
       && parameter.getParameterType().equals(String.class); 
    } 

    @Override 
    public Object resolveArgument(
      MethodParameter parameter, 
      ModelAndViewContainer mavContainer, 
      NativeWebRequest webRequest, 
      WebDataBinderFactory binderFactory) 
     throws Exception 
    { 
     Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
     if(authentication == null) { 
      return null; 
     } 
     String clientId = null; 

     if (authentication.getClass().isAssignableFrom(OAuth2Authentication.class)) { 
      clientId = ((OAuth2Authentication) authentication).getOAuth2Request().getClientId(); 
     } 

     return clientId; 
    } 

} 

그리고 @interface 정의 :

@Target({ElementType.PARAMETER, ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
@Documented 
public @interface CurrentClientId { 

} 
관련 문제