Skip to content

Support Optional<Principal> argument in @MessageMapping #23612

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@
package org.springframework.messaging.simp.annotation.support;

import java.security.Principal;
import java.util.Optional;

import org.springframework.core.MethodParameter;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;

/**
* {@link HandlerMethodArgumentResolver} to a {@link Principal}.
* {@link HandlerMethodArgumentResolver} to a {@link Principal} or {@link Optional} of {@link Principal}.
*
* @author Rossen Stoyanchev
* @since 4.0
Expand All @@ -33,17 +34,19 @@ public class PrincipalMethodArgumentResolver implements HandlerMethodArgumentRes

@Override
public boolean supportsParameter(MethodParameter parameter) {
Class<?> paramType = parameter.getParameterType();
MethodParameter nestedParameter = parameter.nestedIfOptional();
Class<?> paramType = nestedParameter.getNestedParameterType();
return Principal.class.isAssignableFrom(paramType);
}

@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
public Object resolveArgument(MethodParameter parameter, Message<?> message){
Principal user = SimpMessageHeaderAccessor.getUser(message.getHeaders());
if (user == null) {
throw new MissingSessionUserException(message);
if (parameter.isOptional()) {
return Optional.ofNullable(user);
} else {
return user;
}
return user;
}

}