Тёмный

Angular Authentication: Role Based Authorization 

Code Shots With Profanis
Подписаться 8 тыс.
Просмотров 55 тыс.
50% 1

#Angular uses guards to protect routes. In this video we will use the CanActivate guard to protect routes from non-authorized users.
The authentication is applied using #jwt token and we will make sure to block users from visiting specific routes if they are not authorized.
✨ Official doc on CanActivate guard: angular.io/api/router/CanActi...
✨ Code: github.com/profanis/codeShots...

Наука

Опубликовано:

 

15 июл 2021

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 55   
@MhmmDonuts
@MhmmDonuts 2 года назад
This is my first time building a Internet application (im a junior front end dev). Normaly we only do intranet applications but this series has helped me sooooo much to get in touch with JWT Interceptors and a basic login system. THANK YOU SO MUCH!!!!!
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Thanks for your feedback and I am really glad it helped you :)
@felixjimenezgonzalez9292
@felixjimenezgonzalez9292 2 года назад
Great video! Managed to do it thanks to you :D Thanks a lot for the content once more!
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Glad you found it usefull! Thanks for the feedback! :)
@samitdigitalart
@samitdigitalart 2 года назад
Excellent, Very simple and straight to the point. Thanks
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Glad you liked it and thanks for the feedback :)
@saurabhchauhan232
@saurabhchauhan232 2 года назад
Fantastic explanation awaiting for many more
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Thanks a lot. Glad you liked it 🙂
@aaelborollosy
@aaelborollosy 2 года назад
as usual brief and exactly to the point
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Thanks for your feedback! :) Glad you liked it!
@ziadnajami3582
@ziadnajami3582 Год назад
Just wants to say thank you, saved my semester ❤
@CodeShotsWithProfanis
@CodeShotsWithProfanis Год назад
Happy to help!
@maheshkala8641
@maheshkala8641 2 года назад
Great video, really helped me to understand the concept.
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Glad it helped you :)
@TheKkranthi
@TheKkranthi 2 года назад
Great video. Really helpful
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Glad it was helpful!
@ElmarAmanov
@ElmarAmanov 2 года назад
great video for us we wait others thanks
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Glad you liked it!
@ferooref7614
@ferooref7614 3 года назад
Useful video, thanks
@CodeShotsWithProfanis
@CodeShotsWithProfanis 3 года назад
Glad you liked it 😊
@abdelmuniemmohamed2638
@abdelmuniemmohamed2638 2 года назад
Thanks, very helpful.
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Glad you liked it :)
@raygabrielvelasquez5492
@raygabrielvelasquez5492 2 года назад
THANKYOU MY FRIEND!
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
:) Glad you liked it!
@fredericoasoares
@fredericoasoares 2 года назад
Great video!
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Thank you! 🙂
@mohamedzaki4332
@mohamedzaki4332 2 года назад
Very Nice And Useful
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Thanks Mohamed! :)
@alexandroskourtis5268
@alexandroskourtis5268 2 года назад
φιλε εισαι απλα θεος
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Πολύ χαίρομαι που σου άρεσε φίλε μου!! :)
@ThomasBurleson
@ThomasBurleson Год назад
Nice technique to parse the allowed roles from the access token.
@CodeShotsWithProfanis
@CodeShotsWithProfanis Год назад
Glad it was helpful!
@matheusjordan6031
@matheusjordan6031 Месяц назад
very helpfull
@priyankaravichandran851
@priyankaravichandran851 11 месяцев назад
Great , kindly upload Oauth validations , OKTA like that
@mrengithm
@mrengithm 4 месяца назад
Great content. May I know extension to create component and guards?
@cholasimmons
@cholasimmons Год назад
Brilliant! What happens when you have several roles that require access? My role setup isn't hierarchical .
@CodeShotsWithProfanis
@CodeShotsWithProfanis Год назад
If the user.roles property has more than one roles and you have to make sure that both roleX and roleY exist in the array, you should make sure to check if all these items exist in the user.roles array. Unless I misunderstood your question
@rconr007
@rconr007 3 года назад
What plug in are you using in viscose for schematics?
@CodeShotsWithProfanis
@CodeShotsWithProfanis 3 года назад
I use the Angular Schematics extension which you can find here marketplace.visualstudio.com/items?itemName=cyrilletuzi.angular-schematics
@curtismaple
@curtismaple Год назад
Greet video! Thnx! What theme you use in VSCode?
@CodeShotsWithProfanis
@CodeShotsWithProfanis Год назад
Glad you liked it. I am using the Dracula theme
@asjadbutt6100
@asjadbutt6100 Год назад
hi in the guard file the window.alert or the console.log doesnt work it doesnt respond with anything also the guard works but with every role no matter if youre the admin you stilld ont get access to the guarded component
@CodeShotsWithProfanis
@CodeShotsWithProfanis Год назад
Do you mind creating a stackblitz with the code you used so that I can have a look at?
@SamiullahKhan
@SamiullahKhan 2 года назад
Is it necessary to decode the way you did the role info from token, why don't just send the serialised object from server. Personally I don't like accessing info by using index signatures 😜 In addition I want to learn is it safe to store role in the local storage? Otherwise thanks for the video
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
No it is not necessary to decode the token like I did. If you choose the tokens to be part of the JWT claims, then you have to decode. An alternative would be to have the roles part of the HTTP response and not part of the JWT. In this case you do not have to decode them. As of the localStorage, it's OK to persist non sensitive information.
@alessandrocinque4542
@alessandrocinque4542 2 года назад
What is the syntax to allow more than one role to access the page?
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
You can provide an array of roles in the routing configuration (ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-YJ4dgoHEmGs.html) and then you have to check if the values of the given array exist in the array with the roles you get from the token. The code below will accomplish this. const arr = ['foo', 'bar'] const arr1 = ['foo', 'baz'] const isBoolean = arr.some(it => arr1.includes(it))
@alessandrocinque4542
@alessandrocinque4542 2 года назад
@@CodeShotsWithProfanis many thanks!
@murinho7
@murinho7 2 года назад
can you do a video where the admin sees a different navigation bar then the user?
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
good idea :)
@gibranaakib7386
@gibranaakib7386 2 года назад
Hi After that how to hide components based on role provided in route of data
@CodeShotsWithProfanis
@CodeShotsWithProfanis 2 года назад
Hi Gibran. I plan to finish a series of videos with "Libraries How-To' and this will be the next video.
@gibranaakib7386
@gibranaakib7386 2 года назад
@@CodeShotsWithProfanis now i got that but i could be very help to other's Thanks for quick reply
@MikeyCoree
@MikeyCoree Год назад
Thank you for this awesome tutorial series! I'm just in my first month of learning Angular so I cannot guarantee I got everything perfectly correct, but I'll leave here the issues I've encountered and how I solved them, in case it will help anyone (I used Angular 16) : --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * has-role.guard.ts * - From what I understand 'implements CanActivate' in Angular Guards is deprecated in Angular 16; I found out because I do not have a VSC plugin to generate angular elements by right clicking on folders, I use the CLI instead and this is the command : ng generate guard hasRole - I replaced the assignation of isAuthorized variable from 'this.authService.user.roles.includes(route.data.role);' to 'return authService.userRole?.role.includes(route.data['role']) ?? false;' Because I got the error 'type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | undefined' is not assignable to type 'CanActivateFn'. Type 'boolean | undefined' is not assignable to type 'boolean | UrlTree | Observable | Promise'. Type 'undefined' is not assignable to type 'boolean | UrlTree | Observable | Promise'.' The error is related to the return type mismatch in hasRoleGuard function. The CanActivateFn type expects the guard function to return a boolean, a UrlTree object, an Observable, or a Promise. However, guard function was returning boolean | undefined. To resolve the issue, you can update your guard function to explicitly return a boolean value. In the updated code: The return type of the guard function is explicitly set as boolean. The AuthService is injected using the inject function from @angular/core, and its type is casted to AuthService. The ?. optional chaining operator is used to safely access the role property of authService.userRole. The nullish coalescing operator ?? is used to provide a default value of false if the result of authService.userRole?.role.includes(route.data['role']) is null or undefined. - Here's how my has-role.guard.ts code looked in the end: - import { CanActivateFn, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { AuthService } from '../services/auth.service'; import { Injectable, inject } from '@angular/core'; export const hasRoleGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean => { const authService = inject(AuthService) as AuthService; const router = inject(Router); // console.log("user role: "+authService.userRole?.role); const isAuthorized = authService.userRole?.role.includes(route.data['role']) ?? false; if(!isAuthorized){ router.navigate(['']); } return isAuthorized; }; --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * auth.service.ts * - In the constructor I replaced the assignation of this.userRole variable from 'this.userRole = this.getUserRole(this.token); to ' this.userRole = this.token ? this.getUserRole(this.token) : null; ' Because I got the error 'Type 'null' is not assignable to type 'string'.' The ternary operator this.token ? this.getUserRole(this.token) : null is used to conditionally assign the value of this.getUserRole(this.token) to this.userRole if this.token is not null. If this.token is null, this.userRole is assigned the value undefined. This way, you avoid the error when this.token is null, and this.userRole will be assigned the appropriate value based on the token's availability. - I replaced the method in tap function from login method too: this.userRole = response.token ? this.getUserRole(response.token) : undefined; - I used 'user?: User' instead of 'user!: User' because I got the error 'Type 'User | undefined' is not assignable to type 'User'. Type 'undefined' is not assignable to type 'User'. ' triggered on the 2 this.user assigns mentioned above --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * user.Role / user.role / user.roles / user.Roles * - Make sure you use just one of them, in all the places, including JWT property, User model, your auth.service, has-role.guard
Далее
Angular Authentication: Custom Structural Directive
9:13
Cool Tech You’ll LOVE!
21:41
Просмотров 78 тыс.
Get to Know Signal Queries in Angular 17
17:43
Просмотров 1,5 тыс.
Auth Does NOT Have To Be Hard
17:13
Просмотров 96 тыс.
An Illustrated Guide to OAuth and OpenID Connect
16:36
Просмотров 565 тыс.
Senior Angular Developer Interview (theory)
41:57
Просмотров 10 тыс.
Здесь упор в процессор
18:02
Просмотров 342 тыс.