Repository navigation
Description
Describe the bug
Problem is a possible NullPointerException (NPE) in DefaultOAuth2User.getName.
To Reproduce
Get null value on the name attribute during after OAuth authentaction.
Or simply create attributes for DefaultOAuth2User as show in the Sample.
Expected behavior
NPE shouldn't be going around Spring Security. It should maybe use throw new UsernameNotFoundException(.), not sure.
Sample
This is a minimal example to reproduce (without setting up an oauth2 server):
Collection<GrantedAuthority> authorities = Arrays.asList(
new SimpleGrantedAuthority("ROLE_USER")
);
var attributes = new HashMap<String, Object>();
var nameAttributeKey = "Email";
attributes.put("UserName", "");
// notice this is in the attributes, but is null
attributes.put(nameAttributeKey, null);
var test = new DefaultOAuth2User(authorities, attributes, nameAttributeKey);
test.getName();
This code is a problem:
@Override
public String getName() {
return this.getAttribute(this.nameAttributeKey).toString();
}
Real code
In a real use case this was the attributes of the DefaultOAuth2User:
User Attributes: [{UserName=, Email=null, Authenticated=false, Claims=null}]
The name field was "Email", but I guess it could be anything that just so happens to be null. Note that attributes are from an external service. The service is defined by userInfoUri from FactoryBean<T>. So the attributes are essentially attributes of a user profile as returned by the identity provider (idP).
This is how getName was originally called:
public class OAuth2UserServiceImpl extends DefaultOAuth2UserService {
private static final Logger LOG = LoggerFactory.getLogger(OAuth2UserServiceImpl.class);
// ...
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oauth2user = super.loadUser(userRequest);
final String providerId = userRequest.getClientRegistration().getRegistrationId();
// this results in NPE
final String username = oauth2user.getName();
// ...
}
Activity
jzheaux commentedon Jul 1, 2024
Thanks, @Eccenux, for the report. It sounds like the reason there is an NPE is because the application is placing a
nullvalue into the map for thenameAttributeKey. Does that sound right?If so, I think it's reasonable to check for the
DefaultOAuth2Userconstructor to, instead of doing this:do this:
Are you able to create a pull request to make this change?
Eccenux commentedon Jul 1, 2024
Would that
Assert.notNullbe caught by Spring Security though?I mean it's safe to assume this is true:
It's something that should be true for valid implementation.
On the other hand, what is in
attributes.get(nameAttributeKey)depends on idP, so an external entity.jzheaux commentedon Jul 2, 2024
No, it would not be caught by Spring Security.
My suggested change means that passing a map that has a key with a null value is an illegal usage of the class. I wouldn't want business logic to continue in that case. Instead, I'd want the application to address the illegal usage.
AuthenticationPrincipal#getNameshould not returnnullas can be seen in the JavaDoc:Because of that, if the value is
null, there is nothing reasonable to return fromgetName(). This means that the constructor should fail in that circumstance.Only you know what a key with a null value means in your arrangement, so it would be up to you to check for that condition and then throw a
UserNotFoundExceptionor whatever is the correct interpretation.Eccenux commentedon Jul 3, 2024
So if that happens it's a bug in a different place of Spring Security. My code is not parsing attributes. Spring Security is parsing them.
Eccenux commentedon Jul 3, 2024
For those that stumble upon this I can offer this solution:
I guess that works too.
HyoJongPark commentedon Jul 10, 2024
@jzheaux, @Eccenux I'm interested in doing this issue.
May I handle this issue? I will open PR if possible.
I think this is a good way to delegate null check to the user and I agree that the subject of the error is Spring Security, not my code, but I think the user should be able to get a response for giving the wrong value.
Because users will not know the need for the
null check codeuntil the NPE occurs inDefaultOauth2User#getName, and only then will they feel the need for the code and handle the error in some form.I think this is a code that can generate unnecessary resources, and as long as we are aware of this issue, i would like to give users a response to the wrong value through exception.
Suggestion:
If the issue is oriented in the direction of delegating null check to the user, I think we can consider modifying it like the format below, but as mentioned in JavaDoc, this is not a good way to do it.
As @jzheaux said, I think it would be a good way to cause an error to the user by null checking in the
constructororgetter.I think I'll probably work on it by null checking through the
constructor, what do you think?Eccenux commentedon Jul 11, 2024
Correct me if I'm wrong but if the check is done in a constructor this will actually fail work:
AFAIK that 500 error with NPE skips all your configuration within the application and will display full stack even when you disable presenting it within your application (which can be considered a security problem as it display implementation details). Not sure what happens when the assertion fails.
Eccenux commentedon Jul 11, 2024
For me a good solution would be to throw an error that can be caught. So not a RuntimeException like NPE. I mean NPE can technically be caught, but NPE doesn't have a meaning and is typically not something that is declared in documentation.
HyoJongPark commentedon Jul 11, 2024
I also thought if the return value for 'getName()' is null, then the constructor of 'DefaultOauth2User' would do null check and throw exception. and then the user handle the result (exception) instead of the null check.
If the return value for 'getName()' is null, I thought of doing a null check in the constructor of 'DefaultOuth2User' and throw an exception.
Therefore, Our code performs the handle of the results (exceptions) instead of null checks(
validateProfile).do this in constructor:
check this in user code:
So, do you mean that instead of NPE or RuntimeException, we should handle null value using more meaningful exceptions such as 'UserNotFoundException'?
Eccenux commentedon Jul 11, 2024
Yes, any meaningful Exception extending an
AuthenticationExceptionor more specificallyOAuth2AuthenticationException.Fix NPE when nameAttributeValue is null spring-projects#15338
HyoJongPark commentedon Jul 12, 2024
@jzheaux I have made a PR, can you check and merge please?
I wanted to treat it as a more meaningful exception, but I thought the preferred method in Spring Security was a check using
assertion, so I handled it the same way.If you think it is necessary to deal with a more meaningful exception, i will supplement the work later.
Check for null Name Attribute Value
Eccenux commentedon Jul 15, 2024
I hope you know that using

Assert.notNullthrowsIllegalArgumentExceptionwhich in turn will cause 500:I think it's not well documented that one should do:
DefaultOAuth2UserService.loadUser(.)is only document to throw OAuth2AuthenticationException, see:https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserService.html#loadUser(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest)
injae-kim commentedon Jul 15, 2024
On
DefaultOAuth2User, it already can throwIllegalArgumentExceptionwhen attribute is empty or null nameAttributeKey, which is not documeneted.IllegalArgumentExceptionis common exception on java and usually can be thrown on other class's constructor too, so it's okay to not add it on document?I understand your point but not sure we need to add
IllegalArgumentExceptionon document in this case 🤔Let's wait maintainer's opinion too~!
Update Formatting
Update Formatting
Check for null Name Attribute Value
jzheaux commentedon Jul 19, 2024
Thanks, no, I think
IllegalArgumentExceptionis the most meaningful exception for when an application gives invalid input to a component.These would be less meaningful because they would intimate that there is some problem with authentication, which there isn't, at least not in the constructor. The problem is that an application is handing an invalid value to a component. The additional meaning that you are deriving here is usage-specific.
For example, consider that
DefaultOAuth2Usercan be constructed without it being in the context of an authentication. IOW, an authentication might not be happening at the time. It would be a misleading assumption to throw an authentication exception fromDefaultOAuth2User.This is a result of how you are using the class. It should throw a 500 because that indicates that it is the server's responsibility to address the issue. It ensures that you address the issue quickly by making sure that your application does not hand null values to
DefaultOAuth2User.The way I would recommend an application address the fact that the IdP gave a null value for the user name would be handle things before they reach
DefaultOAuth2User. While I don't know the meaning of an IdP sending an invalid response instead of returning an error code, it seems that this is equivalent to an error code. So, I'd probably create a customHttpMessageConverterthat adapts the null-username response into an error response and then do: