Is this the best NodeJS Authorization Library? | CASL JavaScript Tutorial
ฝัง
- เผยแพร่เมื่อ 27 ต.ค. 2024
- In this video we take a look at a fairly popular authorization library: CASL. You can use this solution both on the server side, perhaps on a Node JS Express API, and on the client side like in React or Vue JS. We'll discuss the basics of how to use and how to define abilities for a given user's permission in an application.
Note: if you're using the newest version of CASL the Ability class is deprecated, instead you now have to use createMongoAbility
const { can, cannot, build } = new AbilityBuilder(createMongoAbility);
Very simple yes detailed enough explanation. You saved me multiple hours. Thank you 😊
This is amazing!, thank you so much for sharing the knowledge!, It would be good to see an example of how to use this with react, and render different UI content based on roles.
Might make a video on it when I get a chance, but pretty much as long as you understand the fundamentals from this video regarding how to define abilities, then you can just use the official react casl package which let’s you do “can” checks using a component: casl.js.org/v5/en/package/casl-react/
All tuned up for the dynamic permissions in Nest, official docs are a bit unclear on that regard. Keep up the good work, dude.
Great overview of the library! Curious how did you get the repl behavior with the inline errors etc inside of your code editor? Is that a plug-in?
Quokka js
Been looking forward to this one Marius!
thank you, looking forward for the next one 🔥
🙌
I am also looking forward for a nextjs one.
Thank you. Waiting for nestjs usage.
cool! after nestjs, the one is express with this cacl is nice btw
Thanks bro, waiting for nestjs usage too ❤️What if you additionally connect a database to better understand the communication between casl-nestjs and a db?
Will see what I can do!
thats cool, but maybe it can be work with JWT, as JWT return username too, just add if username "admin" role read & write.
Yes it can work with any authentication strategy, for you to really be able to do authorization you ideally already solved authentication and JWTs might be part of that solution.
as always, great explanation .... thanks for the vid
Thanks, great content. I'll start learning but this vídeo was a great start point.
Great video and explanation. Could you explain how can we manage dynamic assignment and un assignment? E.g. user was give access to edit Post from the frontend by admin and then revoked?
Good question, I think I forgot to mention it but you can also do ability.update(rules). You can use that in addition to using the JSON builder api, that means your rules needs to be saved in the database instead of being statically defined. Initialize the ability by pulling the rules from the database, and when an admin updates it you just need a mechanism to make sure clients are updated either by updating their sessions or perhaps triggering an ability.update(newRules) somehow
Wonderful video thank you very much. What is your vs code setup?
Yet another clear, concise, well delivered video. Really appreciate your time, Marius!
Thanks for stopping by to comment!
Thanks dude for this awesome tutorial. Please also cover the following:
1. @casl/prisma
2. @casl/react
great and simple explaination bro
thanks alot bro😇😇
Great tutorial!
Interesting ! btw, what plugin have you installed to get those indicated on valid / invalid statements , declarations ?
Like the true/false value in the editor? I used the quokka extension, very useful for demos like this
@@mariusespejo yea, thanks.
Learning so much... thanks
Class Ability has been deprecated, it says to use createMongoAbility function instead, but no much info about it when googling.
that's correct. The docs itself explains it. Note it has nothing to do with using MongoDB, just that conditions are using some syntax inspired by mongo, hence the name
Would love a cover video about casl vue
Amazin video, can u pls do a tutorial teaching how to use this in the frontend with ReactJS?
Yeah maybe when I get a chance. It’s honestly not much more to learn, basically take the fundamentals from this video and apply it to UI authorization. Basically make things visually disabled/hidden/locked if user doesn’t have the ability
Thanks for sharing bro! Let me ask you something, in your opinion, which is better keycloak or castle?
I haven’t tried keycloak but it looks like it’s more for authentication? So that would be an apple’s to oranges comparison
@@mariusespejo I've been trying keycloak from 5 months ago, Keycloak works for both Authorization and Authentication. I liked castle, I read some information about castle before but I didn't try it, it looks like easy thanks to you. (Sorry for my English).
Great Content!
Thank you!
finally ! Thanks Dude!
😄🙌
How can we archive this for REST API? how to read the subject and actions from API requests?, is it expected from API requests?
I'd love you to cover casl/vue in a following video. I'm having some troubles implementing it and I'd really appreciate it
I’ll try to cover it when I get a chance. Have you tried the official casl/vue package?
@@mariusespejo Hello! Thanks for replying so fast, wow.
Yes, I'm using the official casl/vue package, but for some reason, the $ability plugin is always 'undefined', even when it shows that it's correctly installed (the linter recognizes it)
please do video on case--react
Thanks bro, what plugin you are using when you type is has an inline suggestions?
that’s just a vs code setting I think, I don’t remember installing a plugin for that
wonderful wonderfule video :D Do you happen to have any code-repo (preferrably open sourced and MIT) with express.js that I can use a referencce to see how casl works with backends ? Super thanks for such a amzing video :)
I don’t sorry! I do have a video on using casl with nestjs though if that helps
@@mariusespejo Thankyou for the reply. Sure I am gonna search it out on your YT channel. Lotss of great videos here :D thankyou for sharing
great video
What's the point? privs are typically stored in DB and the server who decides what and when, the client is supposed to only receive and visualize permissions.
It’s just a tool to help with that, I thought that I had explained that in the video
@@mariusespejo I'm genuinely confused; you didn't connect all of those parts together.
I guess I'll take a look at the docs.
@@mariusespejo My simple apps are often not perfect enough to benefit from this, given the way I understand it currently, still trying to make sense of it though.
Maybe I'm doing authorization wrong!!
I often have to combine multiple conditions to make sure I'm covering all edge cases, some of those conditions are not a simple read, write, etc
[edit]
I'm starting to grasp why it exists, but still confused as to the very little characters it saves you from typing!
Though I like the consistency of the syntax, the only thing I think I lack in the way I implement authorization. This lib can serve as a template.
Alright, let me try to fill in some gaps. There are several ways to do authorization. You could have something as simple as RBAC (role based access control) where you simply assign a basic role to a user, e.g. admins can do special stuff, general users can do basic stuff, etc. Simple apps can get away with just that alone, and your authorization checks server-side would simply need to check roles to protect things. However that doesn’t scale very well. What happens when you start having more roles? What happens when each role start having a mix of different privileges? I’m sure you can imagine without any other tool you’d end up with several if statements in your code to satisfy all your requirements. But then what happens when your requirements change as they often do in the real world? Then you have to hunt down all those auth checks and make sure they’re all still valid.
CASL provides you with one possible solution to be able to represent all your authorization rules in a single file. There is one source of truth. The video should explain that part well, where it has a nice basic api that lets you define given a user and a subject what can or cannot be done. In addition to that in even more complex scenarios you can add conditions, e.g. a user can only edit a post if they are the author. For a lot of apps where the roles and privileges are static, this file-based approach is enough. In an even more complex dynamic privileges scenario where privileges can be modified per user, you can instead save that ability representation as json in a database, and CASL can instantiate an auth “checker” based on that saved json.
Now that checker basically encapsulates all the info you need to check if a user can do X given Y conditions, across your entire codebase whether that’s sever or client side, CASL allows you to have a unified API/utility. It seems you’re making an assumption that authorization checks can/should only happen server-side but that’s not always the case. It depends on the use case. Not something I’m going to debate in a comment.
Anyways so what’s the point? It’s just a lightweight tool, that helps you with authorization/ability representation and a util for checking at runtime.
@@mariusespejo great explanation buddy
Thank you
You’re welcome!
How can we persist these abilities as roles n permissions in db?? 🤔... What will that setup look like
You can initialize an ability from json, meaning you can represent those permissions in the db using a similar schema that the json requires: casl.js.org/v5/en/guide/define-rules#json-objects
So basically at the point when you create an ability you’ll need to add a db query. If you use sessions then you only need to do that at login, unless you want to check each request
with json:
import { createMongoAbility } from '@casl/ability';
export default createMongoAbility([
{
action: 'read',
subject: 'Post'
},
{
inverted: true,
action: 'delete',
subject: 'Post',
conditions: { published: true }
}
])
how to if want conditions such as authorId === userId?
You already have an example of conditions in your snippet there, e.g. you might do conditions: { authorId: 5 }
@@mariusespejo but it store in database and cannot fixed authorId, it's dynamic based on request from client. Can you help me?
Then just store it as string “userId” and make sure to replace it with the correct value at the time that you create the ability
Hello I'm new to programming. I know firebase auth / database and nextjs. Can I use firebase auth with this? Thanks sir
Hey Ohwell, hope you’re enjoying programming. If you’re not familiar I recommend reading about the differences between authentication and authorization. I’m not familiar with firebase auth but I’m going to assume that’s authentication. This video covers one way to do authorization, which would happen after the user is already logged in (authenticated). It doesn’t care about how you achieved that authentication, so I would assume it would work with any authentication strategy
@@mariusespejo Hello, yes its firebase authentication. Thanks for your input. I think it will work. The way you explained in the video is clear for me. Thanks!
hay lắm anh, em cảm ơn nhiều
Thanks. better if you can do the video about the Redux saga.
Redux saga is a bit overkill nowadays in my opinion. Check out react-query, there’s video in my channel. Once you realize how much that simplifies managing state from your API calls you’ll likely also realize how unnecessarily complex sagas are
@@mariusespejo Sure. thanks 🙂
Integration with Nestjs would be great
Hi friend can you make a video on saga in nestjs, DDD in nestjs
casl Vue
Hello sir can you share your vs code theme or font family please
I used github dark for this one!
nestjs recommends it too
Yes! I plan on covering that integration in a follow up video
@@mariusespejo loocking forward to it
please make uideo on casl-react
Will consider it
@@mariusespejo thank you ...plz do on ASAP...i want to use it in my code
If you need it asap then please check the docs, it’s fairly well written. Like I said I can consider it but I can’t guarantee it
Ability is kinda cringey for me. I'm used to it for games not on development. 😅
Lol you can always rename your variables however you like 😄
dude's last name is "mirror" lol
🪞