Talha Mir
Talha Mir

Reputation: 1258

JWT Spring - user based access

I'm implementing JWT based authentication in my Spring boot application. I have an Accounts table which contains user's bank account info. Now, the user signs in using Account number and pin from that table. The problem is that after logging in, user can access anything with the token assigned to it by JWT. He can even change someone else's account info. How can I restrict the access only to the user for which the token is created?

Every user should be able to access info associated with that user only, so creating roles is not an option. Does JWT provides any such feature or do i have to check the tokens manually? I can parse the token and retrieve the account number out of it and compare it with the account number passed in controller methods, but it doesn't seem like a neat solution as this will require changing every Controller method.

Upvotes: 0

Views: 610

Answers (1)

Aliaksei Stadnik
Aliaksei Stadnik

Reputation: 1948

As security in your case depends on business logic I guess there is no way to perform such verification on the Auth provider side.

What you can do is to implement it with the help of the Spring in AOP way quite elegant. You could use spring method security with custom securiry resolver

@PreAuthorize("@securityResolver.isOwner(#userId)")
void changeAccount(UUID userId, Request body);

@Component("securityResolver")
public class CustomSecurityResolver {

     public boolean isOwner(final String userId) {
      //TODO business check here
     }

}

You could even pass JWT token to the security resolver method and implement custom check. In this case you can avoid changing business logic of your service and just add couple of annotations with custom resolver.

I've always implemented such checks as user could only change its own info or tenant isolation with the help of custom method security

Upvotes: 2

Related Questions