#Spring Boot Security with JWT - authenticate customer

1 messages · Page 1 of 1 (latest)

steel isle
#

I have a spring boot project for an e-commerce website. I have implemented Role Based auth for some endpoints but others need extra protection.
For instance this endpoint returns the customer's profile.

    @GetMapping("customers/{customerId}")```
I don't want any user with a token to pe able to retrieve any other user's profile. So I need to authenticate that the user requesting this information is the owner of the profile. So in my JWTService i've built this function which verifies that the info extracted from the token matches the info of the requested resource's owner.
```    public boolean isUserAuthorized(Long resourceId, String token) {
        String claimedUserName = jwtService.extractUserName(token);
        String resourceEmail = userRepository.findById(resourceId)
                .orElseThrow(() -> new AuthentificationException("Forbidden"))
                .getEmail();

        return claimedUserName.equals(resourceEmail);
    }```
The question is how can I use this function in an elegant way? I don't think its good practice to insert jwtService in other resource services or stick this function in a controller. Is there an annotation that can help?
mortal yachtBOT
#

<@&1004656351647117403> please have a look, thanks.

steel isle
#

@mortal yacht not what i was looking for. ty

elfin bear
#

Man that sucks

#

no there is no annotation that does authorization

#

there is a way of plugging in to authorization with spring security though

#

here ya go

steel isle
#

thanks. That looks so complicated

#

😄

elfin bear
#

🤷‍♂️ copy pasting is fine honestly

#

and auth is something we copy paste all the time

steel isle
#

the art is in the what and where 🙂 trying to find that now

#

what about something like this @PostAuthorize("returnObject.username == authentication.principal.nickName") ?

stone drum
#

I'm relatively new to Spring Security, but i believe you can make a Custom filter that takes in the request and does whatever you want to it can very well block or pass it ahead up the chain. After that you would need a bean that returns FilterChain it takes in HttpSecurity type object and you can basically set certain URL mappings there, and insert your filter in the filterchain where ever you think it fits. You might need to do your own research around this though, im still myself experimenting with this.

steel isle
#

yes, but that would be after the jwt filter and only for certain endpoints