Hi, how can I implement spring security with jwt i...
# spring
r
Hi, how can I implement spring security with jwt in rest api without using role (only user)? Passing authories as
null
in
UsernamePasswordAuthenticationToken(userDetails, "", userDetails.authorities)
gives error as authorities can not be null . Any tutorial or help is appreciated.
fun getAuthentication(token: String):Authentication {
val userDetails = myUserDetails.loadUserByUsername(getUsernameFromToken(token))
return UsernamePasswordAuthenticationToken(userDetails, "", userDetails.authorities)
}
j
Presumably you tried empty set in place of null too?
a
If you pass an empty authorities to
UsernamePasswordAuthenticationToken
,
setAuthenticated(true)
is not called, and so your
Authrorizarion
object will return
false
for
isAuthenticated
. This will give you 403 exceptions in several places in spring security. You need to pass at least one authority, you can create a fake one with
SimpleGrantedAuthority
.
j
hmm. Are you using SpringBoot?
in the old days you it was easier to set up Spring Security with any set of authentication providers, and any set of authorization strategies.
Sounds like you want just authentication, but not authorization? So a strategy that always returns true?
r
Correct, authentication only, not authorisation.
a
I've just used one role,
ROLE_USER
and granted it to everyone. Worked well in my scenarios
j
👍 Sounds like a pragmatic approach.
r
@ashmelev were you inserting role to database or something else? Can you provide link to source?
a
Back when I was using SpringSecurity this way we'd create 3 Entities -
sec_user
,
sec_role
and
sec_user_role
(this last was a cross-reference table so that User could have many Role). So, yes,
sec_role
would have one row in which the
authority
field contained
ROLE_USER
. We've long since switched to using Keycloak as our OAuth2/OIDC provider so I don't have any source to link you to. That said, what I described above used to be fairly standard SpringSecurity layout for many years, so there would be plenty of doc/examples in Google.
r
Yes I've used the same. Single role. Thanks