{"id":422,"date":"2021-10-18T13:16:28","date_gmt":"2021-10-18T13:16:28","guid":{"rendered":"https:\/\/www.kindsonthegenius.com\/spring-boot\/?p=422"},"modified":"2022-02-15T11:35:11","modified_gmt":"2022-02-15T11:35:11","slug":"complete-application-with-spring-boot-part-8-role-based-authorization-2","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/spring-boot\/complete-application-with-spring-boot-part-8-role-based-authorization-2\/","title":{"rendered":"Complete Application with Spring Boot \u2013 Part 8 (Role-Based Authorization &#8211; 2)"},"content":{"rendered":"<p>The is Role-Based Authorization 2 and Part 8 of out complete spring boot application. In <a href=\"https:\/\/kindsonthegenius.com\/spring-boot\/complete-application-with-spring-boot-role-based-authorization\/\" target=\"_blank\" rel=\"noopener\">Part 1<\/a>, we setup the Role model, repository and service.<\/p>\n<p>In this part, we would set up the controller and then create the pages. Let&#8217;s get to work!<\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li><a href=\"#t1\">Create the RoleController<\/a><\/li>\n<li><a href=\"#t2\">Create the UserEdit Page<\/a><\/li>\n<li><a href=\"#t3\">Write the Controller Method to Show the userEdit page<\/a><\/li>\n<li><a href=\"#t4\">Write the AssignRole\/UnassignRole Controller Methods<\/a><\/li>\n<li><a href=\"#t5\">Restrict Access to\u00a0 Page<\/a><\/li>\n<li><a href=\"#t6\">Update the Authorities Collection<\/a><\/li>\n<li><a href=\"#t7\">Configure Access Denied Page<\/a><\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p>Watch the video tutorial\u00a0<a href=\"https:\/\/youtu.be\/HsCfNMiURCY\" target=\"_blank\" rel=\"noopener\">Watch the video tutorial\u00a0<\/a><\/p>\n<h5><strong>1. Create the RoleController<\/strong><\/h5>\n<p>So we would have to create the RoleController as well as a roles page for LIST\/ADD\/EDIT\/DELETE role. Follow the steps:<\/p>\n<p><strong>Step 1<\/strong> &#8211; Create the RoleController based on existing controllers<\/p>\n<p><strong>Step 2<\/strong> &#8211; Create the roles.html page inside the templates folder. Write the markup to display list of roles or just copy, paste and modify from existing page.<\/p>\n<p><strong>Step 3<\/strong> &#8211; Create the js file<\/p>\n<p><strong>Step 5(Optional)<\/strong> &#8211; You could also add a navigation link to the roles page.<\/p>\n<p><strong>Step 5<\/strong>\u00a0&#8211; Test the page. Add a few roles: USER, ADMIN and SUPER-ADMIN<\/p>\n<p>&nbsp;<\/p>\n<h5><strong>2. Create the UserEdit Page<\/strong><\/h5>\n<p>This is a page that would be used for assigning and unassigning roles to users. So follow the steps below:<\/p>\n<p><strong>Step 1<\/strong> &#8211; Create a page called userEdit in the templates folder<\/p>\n<p>This page would contain three sections:<\/p>\n<ul>\n<li>User data<\/li>\n<li>Roles currently assigned to the user<\/li>\n<li>Roles not assigned to user (assignable roles)<\/li>\n<\/ul>\n<p>The layout of this page is given below:<\/p>\n<figure id=\"attachment_424\" aria-describedby=\"caption-attachment-424\" style=\"width: 300px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/kindsonthegenius.com\/spring-boot\/wp-content\/uploads\/2021\/10\/UserEdit-Layout-Page.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-424 size-medium\" src=\"https:\/\/kindsonthegenius.com\/spring-boot\/wp-content\/uploads\/2021\/10\/UserEdit-Layout-Page-300x154.jpg\" alt=\"UserEdit Page Layout\" width=\"300\" height=\"154\" srcset=\"https:\/\/kindsonthegenius.com\/spring-boot\/wp-content\/uploads\/2021\/10\/UserEdit-Layout-Page-300x154.jpg 300w, https:\/\/kindsonthegenius.com\/spring-boot\/wp-content\/uploads\/2021\/10\/UserEdit-Layout-Page-1024x525.jpg 1024w, https:\/\/kindsonthegenius.com\/spring-boot\/wp-content\/uploads\/2021\/10\/UserEdit-Layout-Page-768x394.jpg 768w, https:\/\/kindsonthegenius.com\/spring-boot\/wp-content\/uploads\/2021\/10\/UserEdit-Layout-Page-1536x788.jpg 1536w, https:\/\/kindsonthegenius.com\/spring-boot\/wp-content\/uploads\/2021\/10\/UserEdit-Layout-Page.jpg 1938w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><figcaption id=\"caption-attachment-424\" class=\"wp-caption-text\">UserEdit Page Layout<\/figcaption><\/figure>\n<p>See the video for\u00a0 the actual markup of this page.<\/p>\n<p><strong>Step 2<\/strong> &#8211; You need to link this page. So open the existing user.html page and add one more column to the users table. The markup for this column is given below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007700;\">&lt;a<\/span>  <span style=\"color: #0000cc;\">th:href=<\/span><span style=\"background-color: #fff0f0;\">\"@{'\/security\/user\/Edit\/'+${user.id}}\"<\/span>\r\n   <span style=\"color: #0000cc;\">class=<\/span><span style=\"background-color: #fff0f0;\">\"btn btn-primary\"<\/span><span style=\"color: #007700;\">&gt;&lt;i<\/span> <span style=\"color: #0000cc;\">class=<\/span><span style=\"background-color: #fff0f0;\">\"icon_pencil-edit\"<\/span><span style=\"color: #007700;\">&gt;&lt;\/i&gt;<\/span>Manage Roles<span style=\"color: #007700;\">&lt;\/a&gt;<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h5><strong>3. Write the Controller Methods to Load the Edit Page<\/strong><\/h5>\n<p>You now need to write the controller method to show the Edit page. I would be written in the RoleController file. This is given below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #555555; font-weight: bold;\">@GetMapping<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"\/security\/user\/Edit\/{id}\"<\/span><span style=\"color: #333333;\">)<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">public<\/span> String <span style=\"color: #0066bb; font-weight: bold;\">editEmployee<\/span><span style=\"color: #333333;\">(<\/span><span style=\"color: #555555; font-weight: bold;\">@PathVariable<\/span> Integer id<span style=\"color: #333333;\">,<\/span> Model model<span style=\"color: #333333;\">){<\/span>\r\n    User user <span style=\"color: #333333;\">=<\/span> userService<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">findById<\/span><span style=\"color: #333333;\">(<\/span>id<span style=\"color: #333333;\">);<\/span>\r\n    model<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">addAttribute<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"user\"<\/span><span style=\"color: #333333;\">,<\/span> user<span style=\"color: #333333;\">);<\/span>\r\n    model<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">addAttribute<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"userRoles\"<\/span><span style=\"color: #333333;\">,<\/span> roleService<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">getUserRoles<\/span><span style=\"color: #333333;\">(<\/span>user<span style=\"color: #333333;\">));<\/span>\r\n    model<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">addAttribute<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"userNotRoles\"<\/span><span style=\"color: #333333;\">,<\/span> roleService<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">getUserNotRoles<\/span><span style=\"color: #333333;\">(<\/span>user<span style=\"color: #333333;\">));<\/span>\r\n    <span style=\"color: #008800; font-weight: bold;\">return<\/span> <span style=\"background-color: #fff0f0;\">\"\/userEdit\"<\/span><span style=\"color: #333333;\">;<\/span>\r\n<span style=\"color: #333333;\">}<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h5><strong>4. Write the Controller Methods for (Assign\/Unassign) Roles<\/strong><\/h5>\n<p>In the RoleController, we need to write two more methods for assigning and unassigning roles to users.<\/p>\n<p>The assignRole() method is given below<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #555555; font-weight: bold;\">@RequestMapping<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"\/security\/role\/assign\/{userId}\/{roleId}\"<\/span><span style=\"color: #333333;\">)<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">public<\/span> String <span style=\"color: #0066bb; font-weight: bold;\">assignRole<\/span><span style=\"color: #333333;\">(<\/span><span style=\"color: #555555; font-weight: bold;\">@PathVariable<\/span> Integer userId<span style=\"color: #333333;\">,<\/span> \r\n                         <span style=\"color: #555555; font-weight: bold;\">@PathVariable<\/span> Integer roleId<span style=\"color: #333333;\">){<\/span>\r\n    roleService<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">assignUserRole<\/span><span style=\"color: #333333;\">(<\/span>userId<span style=\"color: #333333;\">,<\/span> roleId<span style=\"color: #333333;\">);<\/span>\r\n    <span style=\"color: #008800; font-weight: bold;\">return<\/span> <span style=\"background-color: #fff0f0;\">\"redirect:\/user\/Edit\/\"<\/span><span style=\"color: #333333;\">+<\/span>userId<span style=\"color: #333333;\">;<\/span>\r\n<span style=\"color: #333333;\">}<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>The unassignRole() method is given below;<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #555555; font-weight: bold;\">@RequestMapping<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"\/security\/role\/unassign\/{userId}\/{roleId}\"<\/span><span style=\"color: #333333;\">)<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">public<\/span> String <span style=\"color: #0066bb; font-weight: bold;\">unassignRole<\/span><span style=\"color: #333333;\">(<\/span><span style=\"color: #555555; font-weight: bold;\">@PathVariable<\/span> Integer userId<span style=\"color: #333333;\">,<\/span>\r\n                           <span style=\"color: #555555; font-weight: bold;\">@PathVariable<\/span> Integer roleId<span style=\"color: #333333;\">){<\/span>\r\n    roleService<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">unassignUserRole<\/span><span style=\"color: #333333;\">(<\/span>userId<span style=\"color: #333333;\">,<\/span> roleId<span style=\"color: #333333;\">);<\/span>\r\n    <span style=\"color: #008800; font-weight: bold;\">return<\/span> <span style=\"background-color: #fff0f0;\">\"redirect:\/user\/Edit\/\"<\/span><span style=\"color: #333333;\">+<\/span>userId<span style=\"color: #333333;\">;<\/span>\r\n<span style=\"color: #333333;\">}<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Now you can fire up the application and assign and unassign some roles!<\/p>\n<p>&nbsp;<\/p>\n<h5><strong id=\"t5\">5. Restrict Page Access (HasAuthority and HasAnyAuthority)<\/strong><\/h5>\n<p>Now we want to restrict a page access based on the user&#8217;s role. So now we would like to restrict access to the userEdit page to only users with the &#8216;ADMIN&#8217; role.<\/p>\n<p>To achieve this, open the applicationSecurityConfig file and include this line in the configure section:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">antMatchers<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"\/security\/user\/Edit\/**\"<\/span><span style=\"color: #333333;\">).<\/span><span style=\"color: #0000cc;\">hasAuthority<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"ADMIN\"<\/span><span style=\"color: #333333;\">)<\/span>\r\n<\/pre>\n<p><em><strong>Note<\/strong><\/em>: To specify multiple authorities, you can use hasAnyAuthority(), then provide multiple authorities separated by comma.<\/p>\n<p>The code means that any route matching the pattern provided will only be accessible to users with role specified in the .hasRoles() part. In this case, ADMIN.<\/p>\n<p>&nbsp;<\/p>\n<h5><strong id=\"t6\">6. Update the Authorities Collection<\/strong><\/h5>\n<p>You remember that in the UserPrincipal class, we had a getAuthorities() method that returns a singleton collection of new SimpleGrantedAuthority(&#8220;USER&#8221;). Now we have to adjust that.<\/p>\n<p>We would use the list of roles we stored in our database to create list of authorities, and then return the list.<\/p>\n<p>The new code is shown below, with the previous code commented out.<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #555555; font-weight: bold;\">@Override<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">public<\/span> Collection<span style=\"color: #333333;\">&lt;?<\/span> <span style=\"color: #008800; font-weight: bold;\">extends<\/span> GrantedAuthority<span style=\"color: #333333;\">&gt;<\/span> getAuthorities<span style=\"color: #333333;\">()<\/span> <span style=\"color: #333333;\">{<\/span>\r\n\tList<span style=\"color: #333333;\">&lt;<\/span>GrantedAuthority<span style=\"color: #333333;\">&gt;<\/span> authorities <span style=\"color: #333333;\">=<\/span> <span style=\"color: #008800; font-weight: bold;\">new<\/span> ArrayList<span style=\"color: #333333;\">&lt;&gt;();<\/span>\r\n\t<span style=\"color: #008800; font-weight: bold;\">for<\/span><span style=\"color: #333333;\">(<\/span>Role <span style=\"color: #997700; font-weight: bold;\">role:<\/span> user<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">getRoles<\/span><span style=\"color: #333333;\">()){<\/span>\r\n\t\tauthorities<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">add<\/span><span style=\"color: #333333;\">(<\/span><span style=\"color: #008800; font-weight: bold;\">new<\/span> SimpleGrantedAuthority<span style=\"color: #333333;\">(<\/span>role<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">getDescription<\/span><span style=\"color: #333333;\">()));<\/span>\r\n\t<span style=\"color: #333333;\">}<\/span>\r\n\t<span style=\"color: #888888;\">\/\/return Collections.singleton(new SimpleGrantedAuthority(\"USER\"));<\/span>\r\n\t<span style=\"color: #008800; font-weight: bold;\">return<\/span> authorities<span style=\"color: #333333;\">;<\/span>\r\n<span style=\"color: #333333;\">}<\/span>\r\n<\/pre>\n<p>Also remember to autowire the RoleRepository<\/p>\n<p>With this code, when a user want to access a resource, his roles would be checked to determine if he has the permission.<\/p>\n<p>&nbsp;<\/p>\n<h5><strong id=\"t7\">7. Configure Access Denied Page<\/strong><\/h5>\n<p>We would need a page that would be displayed if a user requests for an unauthorized resource.<\/p>\n<p><strong>Step 1<\/strong> &#8211; Create an access denied page. I call it accessDenied.html<\/p>\n<p><strong>Step 2<\/strong> &#8211; Create a controller route to serve this page. Here, I use &#8220;\/accessDenied&#8221;<\/p>\n<p><strong>Step 3<\/strong> &#8211; In the configure method of the ApplicationSecurityConfig file, include the line below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">and<\/span><span style=\"color: #333333;\">()<\/span>\r\n<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">exceptionHandling<\/span><span style=\"color: #333333;\">().<\/span><span style=\"color: #0000cc;\">accessDeniedPage<\/span><span style=\"color: #333333;\">(<\/span><span style=\"background-color: #fff0f0;\">\"\/accessDenied\"<\/span><span style=\"color: #333333;\">)<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>We are done here! And please do watch the video. <a href=\"https:\/\/youtu.be\/lD7HRqCc3Hw\" target=\"_blank\" rel=\"noopener\">And please do watch the video<\/a> for any clarification. You can also leave me a comment to let me know if you have any challenges.<\/p>\n<p><a href=\"https:\/\/kindsonthegenius.com\/spring-boot\/complete-application-with-spring-boot-part-8-role-based-authorization-2\/\" target=\"_blank\" rel=\"noopener\">On to Part 2<\/a><\/p>\n<!-- AddThis Advanced Settings generic via filter on the_content --><!-- AddThis Share Buttons generic via filter on the_content -->","protected":false},"excerpt":{"rendered":"<p>The is Role-Based Authorization 2 and Part 8 of out complete spring boot application. In Part 1, we setup the Role model, repository and service. &hellip; <!-- AddThis Advanced Settings generic via filter on get_the_excerpt --><!-- AddThis Share Buttons generic via filter on get_the_excerpt --><\/p>\n","protected":false},"author":1,"featured_media":431,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[2],"tags":[50,48,51,49,19],"class_list":["post-422","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-spring-boot-tutorials","tag-authorities","tag-authorization","tag-granted-authorities","tag-role","tag-spring-security"],"_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/posts\/422","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/comments?post=422"}],"version-history":[{"count":11,"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/posts\/422\/revisions"}],"predecessor-version":[{"id":447,"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/posts\/422\/revisions\/447"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/media\/431"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/media?parent=422"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/categories?post=422"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/spring-boot\/wp-json\/wp\/v2\/tags?post=422"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}