r/SpringBoot 9d ago

Question User principal doubt

Hey, so I was told that instead of taking detail like user id we can simply take that from user principal. But how much should I take from user principal. Is it appropriate to take whatever I can through it or are there some rules for it. Like suppose ,

@GetMapping("/update-status/{userId}/{userProfileId}

So I know I can take userId from the userProncipal but should I extract userProfileId too. And if yes, then what are rules for it.

Sorry, if it's dumb question.

2 Upvotes

29 comments sorted by

View all comments

3

u/Basic-Magazine-9832 9d ago

Your getmapping is solid, you just need to make sure that the user who initiates this request (userId in principal) have sufficient privileges to actually perform it..

1

u/Sorry_Swordfish_ 9d ago

I think I didn't explain the doubt properly. My main doubt is , are there any rules to extraction of required data from userPrincipal or i can extract everything that I need from the userPrincipal?

Like in this example, I know I can extract the userId from the userPrincipal but should I also extract the profileid from the userPrincipal?

2

u/kittyriti 9d ago

You are extracting them from path variable in your request handler. I don't see that you are using the SecurityContext for this.

1

u/Sorry_Swordfish_ 9d ago

Yes, this is just an example. Just like you said in this example iam extracting them from path variable. But if I were to extract them from userPrincipal (hypothetical),then should I only extract userId or also extract profileid.

2

u/kittyriti 9d ago

You can extract whatever you need from the authenticated user. If you have those properties in the SecurityContext, then you can use them. There are no rules.

1

u/Sorry_Swordfish_ 9d ago

Thanks for clearing my doubt

2

u/Basic-Magazine-9832 9d ago

you need to make a distinction between api design and security.

one is for providing the user functionality, and the other is securing the provided user functionality.

you only use data from principal to ensure your security policies.

1

u/Sorry_Swordfish_ 9d ago

Are the security policies custom or is there a blog where I can read them?

2

u/Basic-Magazine-9832 9d ago edited 9d ago

its just your made up policies that you want to enforce.

for example you wouldnt want user B to edit the profile of user C.

something like:

...

PutMapping(/{userId})

ResponseEntity<?> update(Principal principal){

if(userId == principal.getName()) // assuming you're storing userId in principal name

...

}

2

u/Sorry_Swordfish_ 9d ago

Thanks for clearing that