Problem with Remember Me feature in Spring Security

I am trying to implement the remember me function on my website using Spring. Cookies and the persistent_logins table entry are created correctly. In addition, I see that the correct user is restored when the username is displayed at the top of the page.

However, as soon as I try to access any information for this user, when they return after their "remembering", I get a NullPointerException. It looks like the user is not set again in the session.

My applicationContext-security.xml contains the following:

<remember-me data-source-ref="dataSource" user-service-ref="userService"/> ... <authentication-provider user-service-ref="userService" /> <jdbc-user-service id="userService" data-source-ref="dataSource" role-prefix="ROLE_" users-by-username-query="select email as username, password, 1 as ENABLED from user where email=?" authorities-by-username-query="select user.id as id, upper(role.name) as authority from user, role, users_roles where users_roles.user_fk=id and users_roles.role_fk=role.name and user.email=?"/> 

I thought this might be due to user requests by name, but of course the login will not work correctly if this request was incorrect?

Any help on this would be greatly appreciated.

Thanks, Gearoid.

+4
source share
1 answer

Can you include the entire trace of the exception stack? I suspect that since you did not set the key configuration attribute remembering me that you indicated above, the token is not set in the SecurityContextHolder.

To learn more about remembering me, you should take a look at the source for RememberMeAuthenticationFilter. You can find this source here (directly):

http://grepcode.com/file/repo1.maven.org/maven2/org.springframework.security/spring-security-web/3.0.2.RELEASE/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilter. java

RememberMeAuthenticationFilter will call in RememberMeAuthenticationProvider as a result:

 rememberMeAuth = authenticationManager.authenticate(rememberMeAuth); 

Inside the authentication method, you can see that it will throw an exception if you do not specify a key:

  if (this.key.hashCode() != ((RememberMeAuthenticationToken) authentication).getKeyHash()) { throw new BadCredentialsException(messages.getMessage("RememberMeAuthenticationProvider.incorrectKey", "The presented RememberMeAuthenticationToken does not contain the expected key")); } 

The key can literally be any string "your-company-name- {GUID}" or something like that. So then you remember - I would be more like this:

 <remember-me key="your-company-name-rmkey-aWeFFTgxcv9u1XlkswUUiPolizxcwsqUmml" token-validity-seconds="3600" data-source-ref="dataSource"/> 

Setting the correct marker is a really good idea that you should do.

Grant

+4
source

Source: https://habr.com/ru/post/1304247/


All Articles