Home > database >  Spring Security: Allow anonymous authentication after user clicks a button
Spring Security: Allow anonymous authentication after user clicks a button

Time:05-11

I try to add a "Login as a guest"-Button to my login page. I would like that anonymous authentication is enabled after the user presses this button.

So if the user navigates to a site that is protected by the WebSecurityConfigurerAdapter the login page should be shown and the user has to click at the "Login as a guest"-Button to get access to the protected site as anonymous user.

But according to the spring documentation, there is not really a difference between an unauthenticated user an an anonymous user. Is there a way to archive such a behavior with the anonymous user concept?

CodePudding user response:

You are overthinking here. Make it simple. You can use the Authentication object to provide an AnonymousAuthenticationToken but be carefull your principal will be null even if you have passed the auth system, because the SecurityContextHolder is not able to provide an identity.

You can use @WithAnonymousUser in your JUnit5 tests to check if you have the expected results.

If it does not work (I doubt about it), you are free to create a new role, and update your Authentification logic to provide a User access with these new role, completely different than the other ones in your webapplication for your users and admins, and update resources accesses for public webpages only with these new role.

  • Related