X
X
xxxibgdrgn2019-01-29 15:29:22
JavaScript
xxxibgdrgn, 2019-01-29 15:29:22

How to differentiate the functionality of the site page depending on the role of the user?

When creating a web application on spring framework using spring security, an authentication form is created. There are 2 users - admin and user. How, depending on the user's role, after a successful login, load index.html with different content? That is, there are icons A and B on the page that lead to other pages of the site. It is necessary to make both icons available for the admin, and only icon A for the user.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2019-01-29
@azerphoenix

You can restrict functionality at different levels.
For example, you can restrict functionality at the template level. If you are using the thymeleaf template engine, then you will most likely need to add || maven-
And then insert into the template - sec:authorize="hasAuthority('ADMIN')"
For example,

<div class="dashboard_rules" sec:authorize="hasAuthority('ADMIN')">
<!-- Увидит только админ-->
</div>

You can also restrict access at the controller level:
I usually do the following:
After authorization, I get the current authorized user
. I find the user and check his rights:
Through if () {} else {} I give this or that content.
For example,
@GetMapping("/dashboard")
public String dashboard(
        @AuthenticationPrincipal UserDetails currentUser,
        Model model
) {
    model.addAttribute("pageTitle","Панель управления");
    User user = (User) userService.findUserByEmail(currentUser.getUsername());
    if(user.isAdmin()) {
        model.addAttribute("posts", posts.getAdminPosts());
    }  else {
        model.addAttribute("posts", posts.getUserPosts());
    }

    return "backend/dashboard";
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question