SECURE Your App with Roles and Permissions in Spring Security!

TheCodeAlchemist · Intermediate ·🔧 Backend Engineering ·1y ago

Key Takeaways

Securing applications with roles and permissions using Spring Security

Full Transcript

hey guys welcome back in the last video we learned how to implement username and password based authentication using HTTP basic o and in this video we will learn the concept of authorities which is granted Authority in Spring Security before we start let me make it clear that whatever we learn in this video has nothing to do with HTTP basic the only reason we are going to continue with the same project is that we have covered only HTTP basic so far so I will reuse the project to implement the authorities otherwise you can do the same thing with let's say JWT or oo so as we go on with the demo don't think that you have to implement HTTP basic in order to work with authorities it's not a mandatory requirement it can work with any other authentication mechanism so that being said let's get [Music] started as the name suggests granted Authority is an authority which is granted to a particular principle now principle here represents any entity which is being authenticated or which has been authenticated so it can be a human user or maybe another machine in case of machine to machine communication so it could be anything who is trying to access the system and who has been authenticated so Authority represents a permission a privilege or a role which has been granted to that entity so it basically represents what the entity can do in the system so in the absence of authority any user which is authenticated can do anything in the system which is allowed almost everything is allowed but authorities are used to put some constraints to put some restrictions based on the role of the user so for example there could be a read privilege or a root privilege which represents the particular Authority which if assigned to a particular user will be able to do some kind of tasks a predefined set of tasks which are only allowed by The Authority so that is what we mean when I say Authority or granted Authority in Spring Security so here we can see there are different authorities there could be n number of authorities in a system it's up to us how we Define different permissions or privileges in the system then we have the concept of role in the system so as we will see in the demo in Spring Security it does not distinguish between role and Authority in terms of implementation both of them are implemented using granted Authority which is an object provided by the Spring Security the only difference is how we use roles and authorities and how we assign them authorities can be considered as a low-level permission or privilege which defines what a user can do then we can combine different authorities for the sake of Simplicity different privileges different permissions Under the Umbrella of role so role acts as a container for different authorities in terms of the grouping so different authorities can be grouped and put inside a role and then that role can be assigned to a particular entity which will Define what all actions can be performed by that entity from the assignment perspective a role has different authorities so you see there is one to many relationship or even many to many relationship because there could be n number of roles as well so an authority represents a permission or a privilege then the role represents a grouping of different permissions let's not talk about what we are going to do with roles and authorities how we are going to implement roles and authorities in the demo project so there are three entities user role and Authority as we learned Authority represents the permission or the privileges in the system so what we can do we have defined three permissions three privileges in the system which is delete read and write in the same way you can Define as many as you want depending on the use case and the scenario then we will also Define two roles the first one is admin as you can see admin rule will have all the three authorities which means if the user has r admin then the user can delete read and write basically it can perform all the operations whereas for the second role which is user this role has only two authorities read and write but it cannot delete the entities or the resources in the system okay then we will create couple of users so for example this user will have the role of admin so basically John do can do anything in the system and then we have the remaining users Jack and Rick which will have the user role that means they can only read and write but cannot delete the resources in the system let's move on and try to understand the flow that we are going to implement so that's the flow we will develop in the application there will be three endpoints basically two controllers one endpoint would be/ admin and the other two endpoints will be read and update now what would happen this endpoint will only be accessible to users which have the admin role so when the user logs in using HTTP basic C because that's what we developed in the last video so we will build this project on top of the work that we did already in the last video so when the user logs in the application will check if the user has admin role if the user has admin role then the user will be allowed and the user will be able to access the admin endpoint in the same way let's say when the user logs in again here in this scenario then we will keep slash read Ando open for all the logged in users that means for this endpoint we will not check any Authority or any role so I just want to show you this is is also possible that you do not protect an endpoint by any Authority if the user is logged in correctly if the user has provided the correct credentials then we can allow the users to access certain endpoints okay as for the third and the last endpoint which is update we will check if the user has the user role and the authority right so here we are checking two conditions that role must be user and the authority must be right so we will cover these use cases in this demo project and we will see how to imp Implement them now before we move on let's understand how Spring Security deals with granted Authority so what happens in Spring Security whether it is role or authority is implemented by the same class or object which is called granted Authority okay so granted Authority represents a simple Authority or even a rule now the question is how does it distinguish between the rule and Authority the thing is whenever we Define The Authority or role in the system we basically Define a fix set of strings so in this case you can see these strings are admin user delete read and write so we have a list of five strings for Spring Security these five strings represent basic granted Authority so at this point it does not know anything about the role or the simple Authority for Spring Security there are five granted authorities with string values like admin user delete read and write so when we ask Spring Security to check or to apply the authority check and pass it a value what it will do it will simply use the simple string value to check the authority so for example if we ask Spring Security to check if the user has delete Authority then spring knows there is a delete string which is available in the context and so it will apply for the granted Authority check but when we ask Spring Security to work with the rule what it does it uses the same Authority okay and it considers a prefix which is Rule underscore so if a granted Authority has a prefix rule underscore then it will be treated as a rule otherwise as a simple Authority what I mean by that is suppose in the system we have these three strings forget about admin or user for now so suppose in the system we have defined three authorities delete read and write so what that means is we can use these three values as simple Authority all right but we can also reuse the same thing as role all we need to do is if we append Ro underscore delete for example if we prefix the delete Authority with role underscore then Spring Security will consider it as a role and then we can use this value for the role checks as well all right so that's how Spring Security works with role and Authority we basically Define a fixed set of strings then we use those strings either as Authority or as role by prefixing them with rule underscore although this can be customizable this can be changed I will show you the correct section of the documentation where we can see how to change this prefix so let's talk about how we are going to change the project existing project what changes do we need and how we are going to implement so here is the updated data model that I'm going to use for this demo because we are still using MySQL as the database where we are storing the user information okay and we are using HTTP basic where the user will enter the credentials and then we will check the database for the correct username and password so in order to support roles and authorities we need to update the data model we need additional tables in the mySQL database to store the roles and the authorities so here you as you can see we have the existing table users which we will reuse and then we will create two new tables the one table the first table is for authorities to store the authorities and this second table is for rules although springing security considers them as a single object which is granted Authority but for the data model we will keep them separate authorities will be stored in the authorities table and rules will be stored in the rules table then you can see we will create couple of more tables basically for the joining purpose for the association so you can see there is another table user roles because a user can have different roles so in this table we will store the user and the corresponding role and similarly we will have another table to hold the or to store the association of role and authorities so in this table we have the role ID for the role and Authority ID so that is going to be the data model for this demo and what I will do I will clone the old project that we developed in the last video we will cut a new feature and then I will also change the database because I don't want to change the existing database of the last video since we are building on top of the existing project which is related to http basic so we are going to use the same code base and what I've done I've created a new feature as you can see here and we will push changes related to rules and authorities in this feature now in order to save some time I have done some changes already to the base project and the main reason is because a great portion of the project has to do with spring data code because we need to store the roles and authorities along with the user information that is plain spring data jpa and uh why we are doing this because as you know we are managing the user store ourselves which is the my SQL database in this case so we need to store the rules and authorities first in know before we can use them so I will walk you through the changes that I have already done which are required to save the data in the database then we will develop the Spring Security part where we will use the rules and authorities together so let me give you a walk through first of all let me show you the application. EML where I have changed the database so we will use a new database for this demo as you know we have changed the data model we have updated the tables to store the rules and authorities as well so we will use a new database for this demo and in the MySQL as you can see this is the new database and there are new tables because we will create the tables when we start the server using ddl now the second step is to update the dto as you know from the last video we are using these dtos to map the incoming post request to Java objects now this is how the new request would look like so along with the username password and email we have a new field in the request roles and this is going to be an array that means a user can have multiple roles here as we can see the user John do has a single role with name admin and the role would have a set of authorities so there is another field inside the role which represents a collection of authorities and Authority is going to be pretty simple it has a single field name so you can see the role is admin then this admin role has different authorities which means read perm write perm and delete perm in this case so in order to map this incoming post request to the user D what I have done I have modified the existing user D to add a new field which is a collection of roles and here we are using a new D which is called Ro D so let me open up the RO D and split it here like this so now what will happen when we receive the post request okay spring will map the incoming request to the DS that we have and this particular part this portion of roles will be mapped to this Ro dto so as you can see for the name field we have a string variable name in the RO dto then we have added a new dto which is to store or to map The Authority information and in this case Authority only has a single field which is named so we have a simple string variable in the authority D so now when we hit the request hit the post request to register a new user we will submit a similar request like this and the user dto will be populated accordingly with all the relevant information so we have added two new dtos rule dto Authority dto and we have also updated the existing user dto now the third step is once we have the data from the incoming request we know we are also creating the jpa entities because we are storing the data in the database using spring data jpa so we need to update the jpa entities as well now if we go back to the uh diagram we know we have the updated data model we have three tables users roles and authorities so that means we need at least three entities and we already have the user entity so I will modify the user entity and then I will add to new entities for authorities and roles table so let me show you the changes here we have the user entity okay so this is the existing user entity what I have done I have added this particular part which is to handle the incoming rules now in this case as we discussed user will not store roles directly but there will be a joint table so we have a collection of roles in this case set and it has a many to many relationship with the role entity which means with the role Table and there will be a new join table user roles where we will store the mappings of user and their corresponding roles and you can see the same information here we have this user uncore roles table to store the user and the role mapping all right so let's go to the roll jpa entity which is the new entity that I have added this is plain spring data jpa if you need any help how spring data jpa works please refer this playlist where you will see all the details related to Spring data and that's why I have done this already because I don't want to spend time on the spring data jpa code this is this has nothing to do with Spring Security actually that's why so we have a new entity role and we are mapping this to the roles table and then we have the required columns like primary key the name and because user and roles have many to many relationship so we are adding the users field here as well you know from the user to roles and from the role to user okay then because the role and authorities would also have a many to many relationship so in the same way we are adding a new field here which is a collection of authority and this again has a many to manyu relationship with the joint table rule uncore authorities which is this one rule uncore authorities all right then the last jpa entity in this case is going to be Authority which is mapped to the Authority's table and it has only two columns the primary key ID and the name because Authority only has the name attribute all right so we have added two new jpa entities for role and authority and we have modified the existing user entity to basically establish the many to many relationship with the role and the second relationship between the role and Authority so that completes the data model and how are we going to work with these entities for that we need spring data repository so in the same way if you come to the user repository this time we don't need any changes in the user repository we have added two new repositories for the rule so this is rules repository and we have added a custom method to find a role by name okay instead of finding the role by ID because we need the flexibility to find a role by name so we have also added a custom method in the roles repository and similarly in the authority repository we have added the similar method to find the authority by name we will see how and why we need this kind of method when we cover the uh registration part where we will store the rules and authorities along with the user information all right so we have covered the dto the changes in the dto and repository and to The Entity now when we submit the hit request we know there was a register method in the user service which was basically preparing and inserting the data in the my SQL database so we will cover some changes that I have done in the user service as well and then we will start with the Spring Security part so here in this user service we had this register method where we were preparing the user entity basically the jpa entity and we were calling user repository. save method to save the user information the new changes in this code will be basically to map the users as well so this is the previous code where we were creating the user entity and setting the required feeld like email okay username and hash password now the new thing in this code will be to map the rules as well so from the user dto we are getting a collection of rules because we know the user can have multiple roles so what we are doing we are iterating each rule okay and for each rule first we are getting or creating the rule from the database so in case for example let me open up the user dto to see the incoming request so suppose in this case let's go back to the user service as well so suppose in this case what we will do if in the incoming request we received the rule as admin then the first step we are doing we are checking if this role already exists in the database so we are getting or creating the role let's go to this method and if you see we are simply using the rules repository and it's find by name method okay so we are saying give me the role corresponding to this name in this case admin if you find the name then it means the role exists in the database if not then immediately create the new role in the system so you see we are creating a new role setting the name whichever we accepted in the request in the incoming request then immediately we are saving or storing the role information in the table so in case if we received the role for the first time from here we will store the role immediately otherwise we will fet the existing rule from the database so this is the first step here we are resolving the rule and here we are doing the same thing with the authori so if you check this method what we are doing from the role dto we are getting all the authorities it means these three authorities in this case Okay and then we are calling get or create Authority so in the same way we are using Authority repository to find the corresponding Authority in the database so if the authority is already present in the database then we are returning that Authority name otherwise in the same way we are creating a new Authority in the system and storing that in the database all right so this is simply get or create kind of uh pattern that we are using here and once we have the rule and the authorities we are setting the authorities to that particular role so in this case these three authorities will be linked to this role and all these roles will be collected to a collection because the user can have multiple roles and in the end we are using the set roles method me to set the rules for the user entity and in the end we are calling user repository. save method which will basically save the whole user object in the database so that means the basic user information and the corresponding rules and authorities and their linking so that's the part that I have already implemented basically to store the incoming data in the database and once we have the data in the database we will enhance the code basically for the Spring Security part and I will show you how to read the authorities and rules and Link it with the the user information so that Spring Security can use that information but before we start with the Spring Security part let's add some users in the system so I will run the service and I will try to add a couple of users that will test the existing functionality as well so let me start the service so the service is up which is a good thing that means the basic code is working fine and if we check the database and uh refresh the database we can see we have the empty tables now which are us users roles and authorities and they linking as well which means role authorities and user roles all right so the next step is let's go to the post man and try to add some users now this is going to be the first user with name John do the password the email and this is going to be an admin user so the role is admin and this role would have all the authorities so let's hit the send button and we see the user created successfully let's check the database and first let's check the users so we have the joho user you see the hash password and if we check the roles we have the one new role admin and if we check the authorities we have three new authorities in the system and let's check the menu to menu or the joint table as well so you see this role is assigned to this user and similarly for role and authorities we see the roles and authorities are mapped accordingly all right so there is one user in the system that means the code that we did is working fine so let's do one more thing let's create one more user but this time it's not going to be an admin user this will be a simple user with a user role what I mean by that is this is what we discussed so we are going to have two roles one is admin and the second one is user rle so we already created a user joho which has the admin rule we will create a new user let's say Jack uh which will have the user rle so let's do that as well so I will change the username we'll keep the password same and this time this is going to be a user rule okay we'll keep the email same as well we are not doing anything related to the user information we just need to focus on the username and the role and Authority Section now in case of the user rule the user role would not have the delete access that means it can read and modify but it should not be able to delete the resources that is going to be the difference between the user and the admin rule so let's add the second user as well and we have the second user created let's verify quickly so from the user table we have two new users okay Jack and jondo and let's go to the user roles and here if I check the user roles so you see the second user is mapped to the second rule all right and in the roles and authorities we should see the new mapping so you can see for the RO ID 2 okay this and this we have uh uh corresponding authorities only one and two all right so we have the required users in the system now let's see what we are going to implement using Spring Security so here this is the flow that we are going to use we said we will have an admin endpoint which will be handled by the Admin controller and this will be only allowed if the incoming user has the admin rule okay so that is the first functionality or the first flow that we will implement so if we go back to the implementation here let me stop the application so what I done I have created a new admin controller which will have the/ admin and point and in this controller there is a simple method admin Ops and this is the same code that we are using the only difference is it will have a different method that it is admin access and the user you are allowed that's it now we have the admin controller but how do we say or how do we enforce this rule that this admin and point should only be accessible to the users which have the admin role so to do that we will go to the security config although there are a couple of ways to implement the same thing but in this video we will focus on the security config how to enforce the roles and the permissions using security config so here if you remember the use of request matchers here we can match a pattern of requests and then we can ask Spring Security to perform some actions and we are going going to use the same thing so if you remember here what we were saying that if you find an incoming request following this endpoint okay/ API / userregister then permit them and everything else must be authenticated and that's why we are able to use the registration endpoint without authentication because we are permitting this endpoint request and in the same way we will use the request matcher so we will say another request matcher and this time we will provide the admin endpoint okay and then we will use the methods has Ro has any Ro and you can see there are methods like has Authority and has any Authority as well we will cover has Authority in a bit but let's focus on the has rule so here we can use the has R method to enforce the rule related checks when we use the has Ro method then we pass a single rle and when we use the has any role method then we pass a list of roles so that means if you find any match with the provided list of roles then based on the configuration either allow the access or block the access so to implement the flow that the admin and point must be accessible to the user only if the user has admin role we will use the method has role and in this case we will pass the name of the role which is going to be admin all right so now we are saying that if you find this endpoint then permit if you find the admin endpoint then check if the user has the admin rule let's go to the second one and here we are saying that if this is the read end point then it must be allowed do not check any role of permission so let's go back to the implementation and for this one we have added a greed controller and in this greed controller if you see this is the end point that represents basically this read part okay there is a name mismatch but it doesn't matter the thing is in this GD controller if you access the API / GRE point then it will not check any role so this is simple if you don't provide anything explicitly here then the access of that endpoint will be managed by Spring Security accordingly okay so in order to allow all we don't need to do anything in this case then there is the second end point and access to this endpoint is allowed only if the user has the role user and the authority right all right so let's see how to do that now in the same greed controller let's go to the greed controller I have added a new slash update endpoint which means the endpoint will be / API /re and/ update and we will enforce the rule that allow this endpoint only if the user has the right permission okay so let's deal with the permission part only and then I will enhance this code to check the user as well so we will go to the same security config and then we will add a new role which is request matchers and I will add the endpoint which is going to be / API SLG greed and slash update and this for this end point we will check the authority this time not the role but the authority that check if the user has the authority WR permission and we know the name of the authority in this case would be rightor perm because if we go back to the postman you see these are the names given to the authorities read uncore pum write uncore pum all right so we will follow the same pattern we will give here the name of the authority wror pum and that's it now the as for the updated configuration what Spring Security will do first of all if it finds this endpoint it will be permitted if it finds the request is for/ admin endpoint then it will check if the user has admin access and if the request is for this endpoint then it will check if the user has this particular Authority so that's how we use the roles and authorities we simply provide the exact name to the ha role or as Authority method so let's quickly test it so the service is up let's try to test the first flow which means if we try to access the admin endpoint then it must be allowed only if the user has admin access so that means if we try to access the endpoint using Jack's credentials then it must not be allowed because Jack has the role user not the admin so for this one we'll add a new tab and this is going to be a get request to the admin endpoint and let me copy the base path like this and we will say admin all right then we also need to pass the login information using authorization we know this already we are using basic o and in this case the credentials will be Jack and password 123 so we are hitting the slash admin and point using ja's credentials and Ja does not have the admin access so let's see what happen and we can see we got an error forbidden that means jack user is not allowed to access the admin end point and that's what we implemented right now what happens if we try to access the update endpoint which is uh this one in the GD controller basically this one because it is only checking the user must have the right perm and uh because the Jack has the right permission if you notice here Jack has the right perm Authority so it must be allowed right so let's try to hit the update endpoint which means SL API SLG greed and update but this is also forbidden what is happening Here We Know Jack has the right permission because we saved the user with user role which has the right permission then why is it not allowed because that's what we implemented here in the security config that allow this endpoint if the user has the right permission then what is happening here why is Jack not allowed to do so the reason is we have some Gap in the implementation now the thing is we already know how this works this method is called in the authentication flow so when the user is authenticating itself Spring Security will call load user by username method to basically find the user details so that it can compare the incoming data with the user information which is present in the database which means the username and the password so in this case also it will call the load user by username method and it will find the Corr responding user but if you notice in this implementation which is coming from the last demo we are only reading the user information okay we are simply calling find by username and returning the user as an authenticated user okay as part of the user details implementation but we are not returning the corresponding roles and authorities so that means even if the Spring Security is able to find the user it only knows the corresponding username and password it knows nothing about the roles and authorities why because if you check we are passing this user to this authenticated user and from this method which is get authorities we are still returning an empty list so that means even though the data is available in the database Spring Security has no idea what authorities or roles this user has so that's why this call is failing because Spring Security does not have any information or any data on the authorities so so it cannot verify that and it will see okay that the user does not have the right permission or any permission at all so based on the security config it will not allow this call that's why this call is failing so the next step is we need to modify the user service as well we need to modify this implementation we need to enrich the roles and the authorities as well all right so let's see how to do that it's it's a very small change and that is the main part of the implementation because we not only need to store the data in the database we also need to fetch the data in the authentication flow okay so what we need to do is once we have the user information we will fetch the authorities and we will also fetch the rules all right so let's do that how do we do that first of all we will have a list because there will be a list of authorities and rules and how we manage authorities and roles there is a class granted Authority which represents basically The Authority because as we discussed Spring Security does not distinguish between a rule and the authorities for Spring Security it is simply a string we can use the same string value even as a rule or an authority so what I mean by that is if we go back to the postman and this particular string you can use this particular string as an authority or even as a rle this is allowed so we will use the granted Authority here this is going to be a list of granted Authority and we will name the object as authorities as well all right now the second step is from the user entity we will get all the roles and then because a user can have multiple roles and each role would have multiple authorities so in order to get the final list of authorities what we will do we will call the flat map like this and for each role we will get the authority it's authorities basically okay and then we will loop on the authorities as well like this and then for each Authority we will create an object of something called Simple granted Authority and to this object we will pass the name of uh the authority like this and in the end we will collect that list something like this and we don't need the unmodifiable so I will simply change it to two list so using this we have the list of authorities for all the roles that this user have that's why we are using flat map all right so let's put a log here all right so what's next we need to fetch the roles as well because if you notice here we are simply reading the authorities but how do we fish the rules which is simple so in the same list which is authorities because roles and authorities are same from the Spring Security perspective they are both granted authorities so we will do something like this add all and the same thing you do get rules because this time we only need the rules so we will say stream. map simple granted Authority r. get name collect and to list like this and let's add a logger here as well then what we will do we will pass this authorities to this authenticated user all right let's go to the authenticated user and we will add a new field here list of granted Authority authorities and uh a new field here as well like this and once we have the authorities instead of returning the empty list we will simply return the authorities in this case so so this time if the user has the roles or the authorities the same will be returned from the get authorities Method All right so let's quickly start the service and check the values so the service is up now and since we are adding the authorities and the roles of that user from the database in the user service in the load user by username method we should be able to access the corresponding end points so let's try to see if we are able to make it now so this time we will start with the admin endpoint because admin endpoint will be accessible to any user which has the admin role so this is the admin endpoint and in fact this is the URL this is the tab that I was using so let's change it to admin and we need to change the user because Jag does not have the admin access so let's go to the database and verify this is John do all right so we will change the username password Remains the Same and let's hit the send button and we see the Forbidden although we have changed the code to read the rules and permissions and now we are using the admin rule okay to access the admin endpoint but still we are getting the same error so let's go to the terminal and see what kind of data now are we adding to the authorities so if we check the logs here the first log which is for authorities we can see that we are successfully adding the available authorities like read perm delete perm and write perm which all belong to the admin role and and as to the roles available you see after adding the roles of that user the final authorities list has that admin role so if we have the admin value in the authorities list then why are we not able to access the admin and point using the admin role well the reason behind that is if we go to the security config whenever we use the method has role and when we pass it a value what Spring Security does it basically tries to find a Val Val in the authorities list with this pattern rule underscore name of the rule okay so in this case what Spring Security will do it will try to find if in the authorities list we have a value something like this so if we pass the value admin Spring Security will internally convert into a string value which is rore admin and then it will try to find that value in the list and if you notice in this list we don't have any value which starts with the value rle underscore so we do not have any value in this list which has the prefix rle underscore so that is something we need to understand so whenever we are using rle or we are using has R method and if we pass it a value what Spring Security will do it will always add the prefix rcore and then it will try to find that value in the list of authorities which is not the case here we don't have that value that's why this check is failing so even though we have the role admin there is a a mismatch spring is looking for something called roore admin all right so in the same way let's say if we change the role to user then what Spring Security will do it will find the value of roore user okay so let me R this now how do we correct it instead of passing it a ro value we can even pass it something called read uncore per which is the value of authority PR security does not care about it what it will do if we pass it let's say this Authority then it will try to find the value rore read uncore perm in the list of authorities okay so we can use the same string value as a rule or even as an authority the only difference is if we are using a value as a rule then we need to add the prefix role underscore okay so let me rever it back to the admin and how do we fix it we'll go back to the user service and where we are actually adding the rules to the list what I will do I will add the prefix here which is rore and that's it so let me restart the application so the service is up Let Me Clear the console and and we will retry the same request and this time you see the request was successful we got the response that admin access hi joho you are allowed now what if we change the user let's try the same URL with user Jack which does not have the admin access so we'll hit the send request and you see we got the Forbidden response and if we check the logs for the user Jack in the authorities list we have two permissions or two authorities which is read underscore perm and write underscore perm and notice the rule this time we have rule uncore user but what Spring Security is looking for for admin endpoint that is rore admin so there is a mismatch and spring can identify that this user is not authorized the user does not have the correct rule okay so we got one thing right right we can now move on to test the second flow which was to use the authority so in the security config we have the second flow as well which is testing the authority which has to be rightor perm in this case in order to access this endpoint so we have the service running we can test this condition as well we will go to the postman and I will change the endpoint from admin to/ API slre and first we will check with the admin user okay so what was the admin user it was I think John do and if we send the request we see that the John do user is allowed to update the resource and the main reason is if we check the service logs let's see the list of authorities so you can see because this user has the admin role so it has all the authorities which are right uncore per read uncore per and delete uncore p and here is the final list with rore admin as well so that means when the Spring Security will check the user login it will find the rore perm in the list of authorities so that's why the user is allowed now if we try the second user which was Jack and notice this user does not have the admin access and we can see user Jack is also allowed to update the resource let's check the logs and as you can see even though this user does not have the admin access but it has the user role which has right and read permissions and we are simply checking the right perm which is allowed now there is one more case that I would discuss so suppose in this case we are simply checking the authority we are not checking the role so any role which has the corresponding Authority in this case will be allowed but let's say you also want to try some combinations like the role must be so and so and the authority must belong to a particular role how do we handle that so there is one simple way to do that that I will show you so in case we have to implement something like that even though admin and user both rules have rightor perm but allow this endpoint only if the corresponding Authority which is rightor perm belongs to the user role so instead of passing rightor perm Authority directly in this case which has no information of the corresponding role what we can do in the user service instead of adding The Authority directly we can also append the role name so in this case I would do something like this roore get name because we have the role details as well and then we will append the rule here like this so instead of adding Authority directly what we are doing we are adding the corresponding role with the authority title okay so the corresponding string value will be rule underscore the name of authority and then what we can do instead of just passing the right underscore perm in the security config we can also pass the name of role which in this case would be user _ wror perm so that will make sure that even though the admin user has the right permission but if the user has the user role only in this case then it will be allowed so let's try this as well all right so the service is up let me clear the logs and we will go back to the postman and we will retry the same request using user Jack because we know the user Jack has the user rule so we can see user Jack is still allowed and if we check the server logs we can see in the list of authorities we now have the updated Authority which is it has the name of the role as well okay and because in this case we are checking user undor wror perm it will find that value in the list of authority that's why user Jack is allowed but if we use the same endpoint with John do which has the admin role let's see if it happens we can see it is forbidden so even the admin rule has the right permission but if you notice the corresponding values for the right permission for the admin role it has admin rore perm but what we are checking in the security config for this endpoint is user undor wror perm so in this case admin is not allowed even though it has the right access so we can use different combinations because ultimately these are string values to achieve different things to implement different constraints okay so that's all for now that's all I wanted to share on the rules and Authority is in this demo and in the next video I will see you with a new topic on Spring Security thanks for watching

Original Description

Code - https://github.com/therealdumbprogrammer/spring-security-httpbasic-auth/tree/feature/roles.and.authorities Playlist - https://www.youtube.com/playlist?list=PLpxcSt9FGVVFqDPqI8m_F5SvDZTMbZ1YX --------------------------------------------------------------------- In this video, we dive into the core concept of managing roles and permissions in Spring Security using the GrantedAuthority interface. Whether you are new to Spring Security or looking to strengthen your understanding of securing REST APIs, this tutorial will guide you step-by-step through: 1) What are GrantedAuthority and Authorities? 2) The difference between roles and permissions in Spring Security. 3) How to implement role-based and permission-based security using GrantedAuthority. 4) Practical examples of securing endpoints with specific roles and permissions. 5) Tips and best practices for managing authorities in a Spring Boot application. By the end of this video, you'll have a solid understanding of how to effectively control access to your APIs using roles and granular permissions. Don't forget to like, subscribe, and hit the notification bell for more Spring Security tutorials! 00:00 Intro 00:53 Roles & Authorities 3:24 User/Roles/Authorities 4:37 Usecase 6:00 GrantedAuthority 8:52 Data Model 10:23 Code Walkthrough 21:07 Adding Users 24:07 Implementing Roles 27:01 Implementing Authorities 29:30 Testing the Project 33:14 Enriching Roles and Authorities ----------------------------------------------------------------- #springboot #springsecurity #security #java #programming #coding #https
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Playlist UUjEfGki6QSKs0mL6-h2pm3Q · TheCodeAlchemist · 9 of 50

1 #java threadlocal #coding #programming #education #softwareengineer #shorts
#java threadlocal #coding #programming #education #softwareengineer #shorts
TheCodeAlchemist
2 ThreadLocal values #java #coding #codingtutorial #programming #programmer #education #shorts
ThreadLocal values #java #coding #codingtutorial #programming #programmer #education #shorts
TheCodeAlchemist
3 Immutable Design and Java Concurrency | Immutability Explained
Immutable Design and Java Concurrency | Immutability Explained
TheCodeAlchemist
4 #java concurrency and immutability #coding #programming #100k #shorts #javaprogramming
#java concurrency and immutability #coding #programming #100k #shorts #javaprogramming
TheCodeAlchemist
5 MASTER HTTP Basic Authentication in Spring Boot in Just 1 Hour | Step-by-Step Tutorial
MASTER HTTP Basic Authentication in Spring Boot in Just 1 Hour | Step-by-Step Tutorial
TheCodeAlchemist
6 #springsecurity #java #coding #programming #springboot #education #javaprogramming #shorts
#springsecurity #java #coding #programming #springboot #education #javaprogramming #shorts
TheCodeAlchemist
7 Encoding passwords in #springsecurity #springboot #java #programming #coding #security
Encoding passwords in #springsecurity #springboot #java #programming #coding #security
TheCodeAlchemist
8 #springboot #coding #springsecurity #shorts #java #programming
#springboot #coding #springsecurity #shorts #java #programming
TheCodeAlchemist
SECURE Your App with Roles and Permissions in Spring Security!
SECURE Your App with Roles and Permissions in Spring Security!
TheCodeAlchemist
10 #springsecurity roles & permissions #java #programming #coding #shorts #springboot
#springsecurity roles & permissions #java #programming #coding #shorts #springboot
TheCodeAlchemist
11 #java #springboot #spring #springsecurity #coding #programming #shorts
#java #springboot #spring #springsecurity #coding #programming #shorts
TheCodeAlchemist
12 Mastering Pre-Authentication with API Keys Like a PRO
Mastering Pre-Authentication with API Keys Like a PRO
TheCodeAlchemist
13 What is an Event Streaming Platform #kafka #java #coding #youtubeshorts
What is an Event Streaming Platform #kafka #java #coding #youtubeshorts
TheCodeAlchemist
14 #apachekafka #coding #code #java #javadevelopment #programming #youtubeshorts
#apachekafka #coding #code #java #javadevelopment #programming #youtubeshorts
TheCodeAlchemist
15 Running Kafka in KRaft Mode without Zookeeper
Running Kafka in KRaft Mode without Zookeeper
TheCodeAlchemist
16 #tutorial #kafka #coding #javadevelopment #java #programming #youtubeshorts
#tutorial #kafka #coding #javadevelopment #java #programming #youtubeshorts
TheCodeAlchemist
17 Kafka Producer and Consumer with Java: Hands-On Tutorial
Kafka Producer and Consumer with Java: Hands-On Tutorial
TheCodeAlchemist
18 How to Use Kafka Consumer Groups in Java | Beginner-Friendly Demo
How to Use Kafka Consumer Groups in Java | Beginner-Friendly Demo
TheCodeAlchemist
19 #kafka consumer groups #kafkatutorial #java #programming #coding #shorts #apachekafka
#kafka consumer groups #kafkatutorial #java #programming #coding #shorts #apachekafka
TheCodeAlchemist
20 Sticky vs Hash Partitioner in Kafka: Full Guide + Java Consumer Group Demo
Sticky vs Hash Partitioner in Kafka: Full Guide + Java Consumer Group Demo
TheCodeAlchemist
21 Step-by-Step Kafka Transactions Demo
Step-by-Step Kafka Transactions Demo
TheCodeAlchemist
22 The DEVELOPER'S Guide to AI and ML: Fundamentals
The DEVELOPER'S Guide to AI and ML: Fundamentals
TheCodeAlchemist
23 LLMs Explained: Tokens, Embeddings, and API Basics
LLMs Explained: Tokens, Embeddings, and API Basics
TheCodeAlchemist
24 Your first OpenAI API App - Step-by-Step Guide
Your first OpenAI API App - Step-by-Step Guide
TheCodeAlchemist
25 #chatgpt #llm #openai #tutorial #technology #tech #programming
#chatgpt #llm #openai #tutorial #technology #tech #programming
TheCodeAlchemist
26 JVM Bytecode Made Simple: Essential Concepts
JVM Bytecode Made Simple: Essential Concepts
TheCodeAlchemist
27 Master #java Bytecode #jvm #jvminternals #programming #coding #shorts
Master #java Bytecode #jvm #jvminternals #programming #coding #shorts
TheCodeAlchemist
28 #jvm operand #stack #explained #java #coding #programming
#jvm operand #stack #explained #java #coding #programming
TheCodeAlchemist
29 JVM Internals: JVM Opcodes and Java ClassFile Explained
JVM Internals: JVM Opcodes and Java ClassFile Explained
TheCodeAlchemist
30 Java Bytecode Deep Dive | What JVM Sees That You Don’t
Java Bytecode Deep Dive | What JVM Sees That You Don’t
TheCodeAlchemist
31 #java #bytecode constant pool #programming #coding #youtubeshorts
#java #bytecode constant pool #programming #coding #youtubeshorts
TheCodeAlchemist
32 Inside the JVM: Class Loading Explained
Inside the JVM: Class Loading Explained
TheCodeAlchemist
33 Java Developers: You MUST Understand These 5 JVM Memory Areas
Java Developers: You MUST Understand These 5 JVM Memory Areas
TheCodeAlchemist
34 User Signup with Email Verification 🔥 Spring Boot + Spring Security
User Signup with Email Verification 🔥 Spring Boot + Spring Security
TheCodeAlchemist
35 How to Build a Secure Password Reset Flow | Spring Security
How to Build a Secure Password Reset Flow | Spring Security
TheCodeAlchemist
36 #springboot #springsecurity #passwordreset #java #programming #javadeveloper #programmingshorts
#springboot #springsecurity #passwordreset #java #programming #javadeveloper #programmingshorts
TheCodeAlchemist
37 JWT Simplified | What Developers Must Know About Token-Based Auth
JWT Simplified | What Developers Must Know About Token-Based Auth
TheCodeAlchemist
38 #jwt #security #springsecurity #springboot #java #programming #coding #codingtutorial #codingtips
#jwt #security #springsecurity #springboot #java #programming #coding #codingtutorial #codingtips
TheCodeAlchemist
39 #jwt #jwtauthentication #authentication #security #websecurity #springsecurity #springboot #java
#jwt #jwtauthentication #authentication #security #websecurity #springsecurity #springboot #java
TheCodeAlchemist
40 Master Spring Security JWT in 1 Hour
Master Spring Security JWT in 1 Hour
TheCodeAlchemist
41 Want to Master Payment Processing? Watch This Now
Want to Master Payment Processing? Watch This Now
TheCodeAlchemist
42 #paymentgateways #java #coding #programming
#paymentgateways #java #coding #programming
TheCodeAlchemist
43 #education #paymentgateways #payments #paypaltutorial #shorts #programming #programmingshorts
#education #paymentgateways #payments #paypaltutorial #shorts #programming #programmingshorts
TheCodeAlchemist
44 Stripe Payments with Spring Boot | Full Hands-On Tutorial
Stripe Payments with Spring Boot | Full Hands-On Tutorial
TheCodeAlchemist
45 #paymentgateways with #springboot #java #coding #programmingshorts #programming
#paymentgateways with #springboot #java #coding #programmingshorts #programming
TheCodeAlchemist
46 #java #javacoding #coding #paymentgateways #payments #springboot #springboottutorial
#java #javacoding #coding #paymentgateways #payments #springboot #springboottutorial
TheCodeAlchemist
47 #java #coding #programming #jvm #codingtips #programmingshorts
#java #coding #programming #jvm #codingtips #programmingshorts
TheCodeAlchemist
48 Can Spring Boot Apps Really Deploy in Minutes on Kubernetes?
Can Spring Boot Apps Really Deploy in Minutes on Kubernetes?
TheCodeAlchemist
49 #java on #kubernetes with #springboot #programming #coding #programmingshorts
#java on #kubernetes with #springboot #programming #coding #programmingshorts
TheCodeAlchemist
50 Spring Boot + Postgres on Kubernetes | Cloud-Native Series
Spring Boot + Postgres on Kubernetes | Cloud-Native Series
TheCodeAlchemist

Related Reads

Chapters (12)

Intro
0:53 Roles & Authorities
3:24 User/Roles/Authorities
4:37 Usecase
6:00 GrantedAuthority
8:52 Data Model
10:23 Code Walkthrough
21:07 Adding Users
24:07 Implementing Roles
27:01 Implementing Authorities
29:30 Testing the Project
33:14 Enriching Roles and Authorities
Up next
How I Built an App with Lovable in Under 1 Hour (2025 Tutorial)
Alex Leischow
Watch →