Removing the ROLE_ Prefix in Spring Security

I’m working on a Spring project from scratch, since I haven’t done that in a long time, it was time to brush up my skills. I’ve read Spring in Action, Sixth Edition by Craig Walls, and in the meantime implemented some stuff, but I haven’t figured out much about Spring Security related to JWT, so I started reading some posts and blogs. A lot of things did work, like /login and I get the tokens back, but for other paths, I get 403 Access Denied. I couldn’t figure out why, and then I googled, got this from stackoverflow stating that we should use ROLE_ in code, but in Springs roles we should use it without that prefix. That’s a bit confusing to me, since I want to use the same thing everywhere, not thinking where I should put ROLE_ prefix and where not. So googling a bit more, I found this.

The proposed solution is to create a bean that returns GrantedAuthorityDefaults, like this in Kotlin:

fun grantedAuthorityDefaults(): GrantedAuthorityDefaults = GrantedAuthorityDefaults("")

Using only USER instead of ROLE_USER everywhere now works as expected. There is a nice explanation from Spring docs that you can read here.