Skip to content

Commit

Permalink
use single method to resolve authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
koenpunt committed Sep 14, 2023
1 parent 808de81 commit 1f1ac3c
Showing 1 changed file with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package org.springframework.graphql.data.method.annotation.support;

import java.lang.annotation.Annotation;
import java.util.Map;

import graphql.schema.DataFetchingEnvironment;
import org.reactivestreams.Publisher;
Expand Down Expand Up @@ -96,7 +97,7 @@ private static AuthenticationPrincipal findMethodAnnotation(MethodParameter para

@Override
public Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) throws Exception {
return getCurrentAuthentication()
return getCurrentAuthentication(parameter.isOptional())
.flatMap(auth -> Mono.justOrEmpty(resolvePrincipal(parameter, auth.getPrincipal())))
.transform((argument) -> isParameterMonoAssignable(parameter) ? Mono.just(argument) : argument);
}
Expand All @@ -106,9 +107,16 @@ private static boolean isParameterMonoAssignable(MethodParameter parameter) {
return (Publisher.class.equals(type) || Mono.class.equals(type));
}

private Mono<Authentication> getCurrentAuthentication() {
return Mono.justOrEmpty(SecurityContextHolder.getContext().getAuthentication())
.switchIfEmpty(ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication));
@SuppressWarnings("unchecked")
private Mono<Authentication> getCurrentAuthentication(boolean optional) {
Object principal = PrincipalMethodArgumentResolver.doResolve(optional);
if (principal instanceof Authentication) {
return Mono.just((Authentication) principal);
}
else if (principal instanceof Mono) {
return (Mono<Authentication>) principal;
}
return Mono.error(new IllegalStateException("Unexpected return value: " + principal));
}

@Nullable
Expand Down

0 comments on commit 1f1ac3c

Please sign in to comment.