How to distinguish between the functionality of the page depending on user role?

0 like 0 dislike
36 views
When you create a web application based on spring fraemwork using spring security creates a form of authentication. There are 2 user - admin and user. Depending on the user role, after the successful login to load index.html with different content? So there are page icons A and B, which lead to other pages of the website. You need to make for the administrator was available as both icons and user icon A.
by | 36 views

1 Answer

0 like 0 dislike
You can restrict the functionality at different levels.
For example, you can restrict the functionality on the template level. If you are using the thymeleaf templating engine, it is likely you will need to add to Gradle || Maven
implementation group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity5', version: '3.0.4.RELEASE'

And then in template paste - sec:authorize="hasAuthority('ADMIN')"
For example,
\r<!-- Увидит только админ-->\r


It is also possible at the controller level to limit access:
@PreAuthorize("hasAuthority('ADMIN')")

Depending on the user role, after the successful login to load index.html with different content?

I usually do the following:
After login get the current authenticated user
@AuthenticationPrincipal UserDetails currentUser
Find the user and check his rights:
User user = (User) userService.findUserByEmail(currentUser.getUsername());

Using if() {} else {} give a particular content.
For example,
@GetMapping("/dashboard") public String dashboard( @AuthenticationPrincipal UserDetails currentUser, Model model ) { model.addAttribute("pageTitle","control Panel"); User user = (User) userService.findUserByEmail(currentUser.getUsername()); if(user.isAdmin()) { model.addAttribute("posts", posts.getAdminPosts()); } else { model.addAttribute("posts", posts.getUserPosts()); } return "backend/dashboard"; }
by

Related questions

110,608 questions
257,186 answers
0 comments
32,887 users