<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ashish Rameshan</title>
    <description>The latest articles on DEV Community by Ashish Rameshan (@ashishrameshan).</description>
    <link>https://dev.to/ashishrameshan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F574729%2Fdbcd8fd8-2c75-4327-836f-913c14f8f9cf.png</url>
      <title>DEV Community: Ashish Rameshan</title>
      <link>https://dev.to/ashishrameshan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ashishrameshan"/>
    <language>en</language>
    <item>
      <title>Spring Boot : Custom Role - Permission Authorization using SpEL</title>
      <dc:creator>Ashish Rameshan</dc:creator>
      <pubDate>Sat, 06 Feb 2021 17:09:29 +0000</pubDate>
      <link>https://dev.to/ashishrameshan/custom-role-based-permission-authorization-in-spring-boot-m7f</link>
      <guid>https://dev.to/ashishrameshan/custom-role-based-permission-authorization-in-spring-boot-m7f</guid>
      <description>&lt;p&gt;This article continues the Registration with Spring Security series with a look at how to properly implement Roles and Permissions.&lt;/p&gt;

&lt;p&gt;First, let's start with our entities. We have three main entities:&lt;/p&gt;

&lt;p&gt;-&amp;gt; &lt;em&gt;User&lt;/em&gt;&lt;br&gt;
-&amp;gt; &lt;em&gt;Role&lt;/em&gt;&lt;br&gt;
-&amp;gt; &lt;em&gt;Permission&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String email;
    private String password;

    @ManyToMany 
    @JoinTable( 
        name = "users_roles", 
        joinColumns = @JoinColumn(
          name = "user_id", referencedColumnName = "id"), 
        inverseJoinColumns = @JoinColumn(
          name = "role_id", referencedColumnName = "id")) 
    private Collection&amp;lt;Role&amp;gt; roles;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
public class Role{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    // Ex : ADMIN, USER
    private String name;

    @ManyToMany 
    @JoinTable( 
        name = "role_permissions", 
        joinColumns = @JoinColumn(
          name = "role_id", referencedColumnName = "id"), 
        inverseJoinColumns = @JoinColumn(
          name = "permission_id", referencedColumnName = "id")) 
    private Collection&amp;lt;Permission&amp;gt; permissions;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
public class Permission {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    // Ex: READ,WRITE,UPDATE
    private String name;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Getter
@Setter
@Builder
public class UserPrincipal implements UserDetails {

    private Long id;
    private String name;
    private String email;
    private Collection&amp;lt;? extends GrantedAuthority&amp;gt; roles;
    private Collection&amp;lt;? extends GrantedAuthority&amp;gt; permissions;

    public static UserPrincipal createUserPrincipal(User user) {
        if (user != null) {
            List&amp;lt;GrantedAuthority&amp;gt; roles= user.getRoles().stream().filter(Objects::nonNull)
                    .map(role -&amp;gt; new SimpleGrantedAuthority(role.getName().name()))
                    .collect(Collectors.toList());

            List&amp;lt;GrantedAuthority&amp;gt; permissions = user.getRoles().stream().filter(Objects::nonNull)
                    .map(Role::getPermissions).flatMap(Collection::stream)
                    .map(permission-&amp;gt; new SimpleGrantedAuthority(permission.getName().name()))
                    .collect(Collectors.toList());

            return UserPrincipal.builder()
                    .id(user.getId())
                    .name(user.getName())
                    .email(user.getEmail())
                    .roles(roles)
                    .permissions(permissions)
                    .build();
        }
        return null;
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; – We're using the Permission – Role terms here, but in Spring, these are slightly different. In Spring, our Permission is referred to as Role, and also as a (granted) authority – which is slightly confusing. Not a problem for the implementation of course, but definitely worth noting.&lt;/p&gt;

&lt;p&gt;Also – these Spring Roles (our Permissions) need a prefix; by default, that prefix is “ROLE”, but it can be changed. We're not using that prefix here, just to keep things simple, but keep in mind that if you're not explicitly changing it, it's going to be required.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CustomSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    private Object filterObject;
    private Object returnObject;
    private Object target;

    /**
     * Creates a new instance
     *
     * @param authentication the {@link Authentication} to use. Cannot be null.
     */
    public CustomSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
    }

    public boolean hasAnyPermission(String... permissions) {
        UserPrincipal authentication = (UserPrincipal) getPrincipal();
        for (String permission : permissions) {
            if (authentication.getPermissions()
                    .stream()
                    .map(GrantedAuthority::getAuthority)
                    .anyMatch(a -&amp;gt; a.equals(permission))) {
                return true;
            }
        }
        return false;
    }

    /**
     * Validates if Current User is authorized for ALL given permissions
     *
     * @param permissions cannot be empty
     */
    public boolean hasPermission(String... permissions) {
        UserPrincipal authentication = (UserPrincipal) getPrincipal();
        if (CollectionUtils.isNotEmpty(authentication.getPermissions())) {
            List&amp;lt;String&amp;gt; authenticationPermissions = authentication.getPermissions()
                    .stream()
                    .filter(Objects::nonNull)
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toList());

            return Arrays.stream(permissions)
                    .filter(StringUtils::isNotBlank)
                    .allMatch(permission -&amp;gt; authenticationPermissions.contains(permission));
        }
        return false;
    }

    @Override
    public void setFilterObject(Object filterObject) {
        this.filterObject = filterObject;
    }

    @Override
    public Object getFilterObject() {
        return filterObject;
    }

    @Override
    public void setReturnObject(Object returnObject) {
        this.returnObject = returnObject;
    }

    @Override
    public Object getReturnObject() {
        return returnObject;
    }

    @Override
    public Object getThis() {
        return target;
    }

    public void setThis(Object target) {
        this.target = target;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Component
public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler {

    @Override
    protected MethodSecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, MethodInvocation invocation) {
        CustomSecurityExpressionRoot root = new CustomSecurityExpressionRoot(authentication);
        root.setThis(invocation.getThis());
        root.setPermissionEvaluator(getPermissionEvaluator());
        root.setTrustResolver(getTrustResolver());
        root.setRoleHierarchy(getRoleHierarchy());
        root.setDefaultRolePrefix(getDefaultRolePrefix());
        return root;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Configuration
@EnableGlobalMethodSecurity( prePostEnabled = true )
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        CustomMethodSecurityExpressionHandler expressionHandler = new CustomMethodSecurityExpressionHandler();
        return expressionHandler;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;We now have two new security expression available and ready to be used: &lt;code&gt;hasPermission&lt;/code&gt; &amp;amp; &lt;code&gt;hasAnyPermission&lt;/code&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;hasPermission&lt;/code&gt; - &lt;code&gt;@param&lt;/code&gt;- String[] , checks if current user has &lt;strong&gt;ALL&lt;/strong&gt; permissions.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;hasAnyPermission&lt;/code&gt; - &lt;code&gt;@param&lt;/code&gt;- String[], checks if Current User has &lt;strong&gt;ANY&lt;/strong&gt; permission.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now similarly how Spring Security has inbuilt expressions like &lt;code&gt;hasRole&lt;/code&gt; &amp;amp; &lt;code&gt;hasAnyRole&lt;/code&gt; , we can check permissions as well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example :&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@GetMapping
@PreAuthorize("hasRole('ADMIN') or hasPermission('READ')")
    public ResponseEntity&amp;lt;List&amp;lt;User&amp;gt;&amp;gt; findAll() {
        return new ResponseEntity&amp;lt;&amp;gt;(User.build(userService.getAllUsers()), HttpStatus.OK);
    }

@GetMapping
@PreAuthorize("hasAnyRole('ADMIN') or hasAnyPermission('READ','UPDATE','WRITE')")
    public ResponseEntity&amp;lt;List&amp;lt;User&amp;gt;&amp;gt; findAll() {
        return new ResponseEntity&amp;lt;&amp;gt;(User.build(userService.getAllUsers()), HttpStatus.OK);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>java</category>
      <category>security</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
