Home > Software design >  How to make one method return different values for user with role ADMIN and USER?
How to make one method return different values for user with role ADMIN and USER?

Time:02-14

I need to make the @Get method, and for users with ROLE_USER it should return other values than for users with ROLE_ADMIN.

The URL have to be the same.

How to do it with Spring Security?

CodePudding user response:

Question is not 100% clear, but what I would do is make an Enum field in the user class (assuming that class exists) for the role and return the value of that field when the URL is called.

CodePudding user response:

If your authentification passed well you could just inject @AuthenticationPrincipal:

@GetMapping("/get-url-here")
public String main(@AuthenticationPrincipal User user) {
    if (user.getRole().equals("ROLE_ADMIN")) {
        // set values for admin
    } else {
        // set for user
    }
    return "view-or-response-body";
}

I assume that you have the User class configured, like:

public class User {
    public String role;
    // other fields, getters, setters
}

Or role could be enum as well.

  • Related