Fleshing out the HandlerMethodArgumentResolver
option a bit more. In order to support the following:
@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
}
We'll need the HandlerMethodArgumentResolver
registered with our Application Context (for me this was inside a WebMvcConfigurerAdapter
). My HandlerMethodArgumentResolver
looks like this:
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;
}
}
And the @interface
definition:
@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CurrentClientId {
}