Adding JWT Authentication & Authorization in ASP.NET Core

Nick Chapsas
20 Apr 202317:24

Summary

TLDRIn this tutorial, Nick demonstrates how to integrate JSON Web Token (JWT) authentication and authorization into an ASP.NET Core application. He showcases the process using a sample movies API, explaining the importance of distinguishing between authentication and authorization. Nick guides viewers through adding the necessary NuGet package, configuring token validation parameters, and securing endpoints with the [Authorize] attribute. He also covers creating policies for role-based access control, using claims for authorization, and enhancing the developer experience with Swagger support for JWT.

Takeaways

  • ๐Ÿ˜€ Nick introduces a tutorial on integrating JSON Web Token (JWT) authentication and authorization in an ASP.NET Core application.
  • ๐Ÿ”’ The video focuses on the implementation of JWT, assuming viewers already understand the concept of JWTs and 'jot'.
  • ๐Ÿ“š Nick references other in-depth videos on JWTs and suggests checking the description for more resources.
  • ๐ŸŽฌ The demonstration uses a sample 'Movies API' to illustrate the process of adding JWT support.
  • ๐Ÿ› ๏ธ To begin, Nick shows how to add the 'Microsoft.AspNetCore.Authentication.Bearer' NuGet package for JWT support.
  • ๐Ÿ”‘ Configuration involves setting up authentication and authorization services, and using the 'AddBearer' method to configure token validation parameters.
  • ๐Ÿ“ It's important to validate the token's issuer, audience, expiration, and signature to ensure its validity and security.
  • ๐Ÿ’ก For security, keys used for token generation and validation should be stored securely, not hard-coded in settings.
  • ๐Ÿ›‘ The order of middleware matters: authentication should come before authorization in the pipeline.
  • ๐Ÿšซ Without proper authentication, unauthorized access to the API would be unrestricted, which is demonstrated with the Movies API.
  • ๐Ÿ“ Nick discusses two approaches for allowing public access to certain actions: using the 'AllowAnonymous' attribute or removing the 'Authorize' attribute from specific actions.
  • ๐Ÿ‘ฎโ€โ™‚๏ธ Authorization policies can be created based on claims within the JWT to restrict access, such as allowing only admins to delete movies.
  • ๐Ÿ› ๏ธ Custom attributes like 'RequiresClaimAttribute' can be used for fine-grained control over claims-based authorization.
  • ๐Ÿ“ The video also covers how to integrate JWT authentication with Swagger, ensuring that endpoints can be tested with proper authentication.

Q & A

  • What is the main topic of the video by Nick?

    -The main topic of the video is how to add JSON Web Token (JWT) authentication and authorization support in an ASP.NET Core application.

  • Why is Nick not explaining what a JSON Web Token is in this video?

    -Nick is not explaining what a JSON Web Token is because he already has a separate video on that topic, and he wants to focus on the implementation in ASP.NET Core specifically.

  • What is the purpose of the 'Movies API' shown in the video?

    -The 'Movies API' is used as an example to demonstrate how to implement JWT authentication and authorization in an ASP.NET Core application.

  • What does Nick demonstrate with the 'Movies API' before adding JWT support?

    -Nick demonstrates creating, listing, updating, and deleting movies in the API, showing that initially, there is no authentication or authorization required to perform these actions.

  • What NuGet package does Nick recommend to add JWT support?

    -Nick recommends adding the 'Microsoft.AspNetCore.Authentication.JwtBearer' NuGet package to implement JWT support.

  • What is the difference between authentication and authorization as explained in the video?

    -Authentication is the process of verifying that someone is who they claim to be, while authorization is the process of verifying that someone has access to what they claim to have access to.

  • How does Nick suggest storing the JWT secret key for security purposes?

    -Nick suggests storing the JWT secret key securely in a service designed to store tokens, such as Azure Key Vault or AWS Secrets Manager, rather than hardcoding it in the settings.

  • What are the minimum token validation parameters that Nick mentions should be specified?

    -The minimum token validation parameters mentioned are validating the issuer, audience, ensuring the token is not expired, and validating the signature.

  • How does Nick demonstrate passing a JWT to authenticate a request?

    -Nick demonstrates passing a JWT by setting the 'Authorization' header in Postman with the value 'Bearer ' followed by the actual token.

  • What are the two approaches Nick discusses for allowing anonymous access to certain actions in the API?

    -The two approaches are using the 'AllowAnonymous' attribute on specific actions to override the controller-based behavior, or removing the 'Authorize' attribute from the controller and applying it individually to actions that require it.

  • How does Nick explain creating a policy for role-based authorization?

    -Nick explains creating a policy by using the 'AddPolicy' method in the 'AuthorizationOptions', defining a name for the policy, and specifying the required claim name and value using a 'PolicyBuilder'.

  • What is the alternative method to policies for claim-based authorization that Nick presents?

    -The alternative method is creating a custom attribute called 'RequiresClaimAttribute' that can be used to validate claims directly on actions or controllers without defining a policy.

  • How does Nick address adding Swagger support for JWT authentication?

    -Nick explains creating a 'Swagger' directory with specific configuration files to define security schemes and requirements, and then registering these configurations in the 'Program.cs' to enable JWT authentication in Swagger UI.

Outlines

00:00

๐Ÿ“š Introduction to JWT Authentication in ASP.NET Core

Nick introduces a tutorial on integrating JSON Web Token (JWT) authentication and authorization in an ASP.NET Core application. He mentions that he won't explain what JWT is, as it's already covered in another video, and focuses on the implementation. He presents a Movies API example, demonstrating its current functionality without any authentication or authorization. He then outlines the steps to add JWT support starting with the addition of a NuGet package and configuring authentication and authorization services.

05:02

๐Ÿ” Configuring JWT Authentication and Authorization

The paragraph explains the process of configuring JWT authentication and authorization in an ASP.NET Core application. It details the need to validate the issuer, audience, and token expiration, as well as the importance of validating the token's signature. Nick also discusses storing the secret key securely and not hardcoding it in the settings. He then moves on to demonstrate how to pass a JWT to authenticate and access the API, showing how to create a token using a helper identity API and how to include it in the authorization header in Postman.

10:02

๐Ÿ› ๏ธ Implementing Authorization Policies and Custom Attributes

Nick demonstrates how to implement authorization policies and custom attributes for fine-grained access control in the application. He creates an 'Identity Data' class to hold constants for claims and policies, and then registers a policy requiring a specific claim value. He applies this policy to the 'Delete' action to restrict it to admin users only. Additionally, he introduces an alternative approach using a custom attribute called 'RequiresClaimAttribute' to validate claims without using policies. This attribute can be applied to controller actions to enforce authorization rules.

15:04

๐Ÿ“˜ Enabling Swagger Support for JWT Authentication

The final paragraph covers how to add Swagger support for JWT authentication. Nick explains creating a 'Swagger' directory with specific configuration files to define and register security schemes for Swagger UI. This setup allows users to authenticate using JWT tokens directly within the Swagger UI, providing a seamless experience for testing and interacting with the API endpoints. He concludes the tutorial by running the API and successfully demonstrating the Swagger UI's capability to accept JWT tokens for authentication.

Mindmap

Keywords

๐Ÿ’กJson Web Token (JWT)

A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. It's used for authenticating and authorizing users in web applications. In the video, JWT is the central topic as the presenter shows how to add JWT support to an ASP.NET Core application. The script mentions configuring JWT validation parameters to ensure the token's issuer, audience, and signature are valid.

๐Ÿ’กASP.NET Core

ASP.NET Core is an open-source, cross-platform framework for building modern, cloud-based, Internet-connected applications. In the video, the presenter focuses on enhancing an ASP.NET Core application with JWT authentication and authorization capabilities, demonstrating the integration of security features into this type of application.

๐Ÿ’กAuthentication

Authentication is the process of verifying the identity of a user or system. In the context of the video, the presenter explains how to implement JWT to authenticate users in an ASP.NET Core application, ensuring that users are who they claim to be before allowing access to certain API endpoints.

๐Ÿ’กAuthorization

Authorization is the process of determining whether an authenticated user has permission to access a particular resource or perform an action. The video script describes how to use JWT to authorize users, with examples such as allowing only users with an 'admin' claim to delete a movie from the API.

๐Ÿ’กNuGet Package

A NuGet package is a package management system used within the Microsoft development environment to manage library dependencies. In the script, the presenter mentions adding the 'Microsoft.AspNetCore.Authentication.JwtBearer' NuGet package to facilitate JWT support in the ASP.NET Core application.

๐Ÿ’กBearer Token

A Bearer Token is a security token delivered in HTTP Authorization request header (Authorization: Bearer <token>). The video script explains how to pass a JWT as a Bearer token in the authorization header to access protected resources in the API.

๐Ÿ’กClaims

In JWT, claims are statements about an entity (typically, the user) and additional data that is added to the token. The script discusses standard claims like 'sub' (subject) and custom claims like 'admin', which are used to make authorization decisions within the application.

๐Ÿ’กPolicy-Based Authorization

Policy-based authorization is an approach where access decisions are made based on policies that encapsulate certain conditions. The video describes creating a custom policy named 'AdminUserPolicy' that requires a specific claim value to allow an action, such as deleting a movie.

๐Ÿ’กCustom Attribute

A custom attribute in C# is a special kind of class that can be used to annotate other classes, methods, or properties with metadata. In the script, the presenter creates a 'RequiresClaimAttribute' to simplify the process of checking for specific claims in JWT for authorization purposes.

๐Ÿ’กSwagger

Swagger is an open-source software framework backed by a set of tools that helps developers design, build, document, and consume RESTful Web services. The video script includes adding Swagger support to the ASP.NET Core application, enabling the documentation and testing of JWT-secured endpoints.

๐Ÿ’กMinimal APIs

Minimal APIs in ASP.NET Core represent a simplified way to build HTTP APIs with less boilerplate code. The script briefly mentions covering Minimal APIs and how JWT authentication and authorization can be applied in this context, emphasizing the adaptability of JWT support across different API patterns.

Highlights

Introduction to adding JSON Web Token (JWT) authentication and authorization in ASP.NET Core applications.

Assumption that viewers are already familiar with JWT, focusing on its implementation in ASP.NET Core.

Demonstration of a Movies API without authentication or authorization.

Explanation of the process to add JWT support using the NuGet package Microsoft.AspNetCore.Authentication.JwtBearer.

Clarification of the difference between authentication and authorization in the context of JWT.

Configuration steps for JWT validation parameters such as issuer, audience, and token expiration.

Security best practices for storing JWT signing keys, recommending Azure Key Vault or AWS Secrets Manager.

Implementation of authentication and authorization middleware in the ASP.NET Core pipeline.

Use of the Authorize attribute to protect endpoints and require user authentication.

Creating JWT with custom claims using a helper Identity API.

Passing JWT in the Authorization header using the Bearer schema in HTTP requests.

Differentiating between allowing anonymous access and applying authorization policies on actions.

Creating and applying custom authorization policies based on JWT claims for fine-grained access control.

Using the RequiresClaim attribute for claim-based authorization without policies.

Support for JWT in minimal APIs with extension methods for authorization.

Enabling Swagger support for JWT authentication to facilitate API documentation and testing.

Final thoughts and encouragement for viewers to explore further in REST API courses for in-depth knowledge.

Acknowledgment of Patreon supporters and a call to action for likes, subscriptions, and notifications for future content.

Transcripts

play00:00

hello everybody I'm Nick and in this

play00:01

video I'm going to show you how you can

play00:03

add the Json web token authentication

play00:04

and authorization support in your ASP

play00:06

core application if you like that with

play00:08

content and you want to see more make

play00:09

sure you subscribe ring the sub

play00:10

notification Bell and for more training

play00:12

check out Nick chapsters.com okay so let

play00:14

me show what I have here and actually I

play00:16

want to point out that I'm not going to

play00:17

be explaining what the Json web token is

play00:19

or a jot because I already have a video

play00:22

on that which you can check in the

play00:23

description below but there's also tons

play00:25

of other videos going really in depth

play00:27

with the topic it is a generic topic

play00:29

it's not specific to a Sprint core and I

play00:31

want to focus on the implementation

play00:32

itself and show you how you can use it

play00:34

in a very nice way let me show what I

play00:36

have here I have this movies API and

play00:38

that's what we're going to be dealing

play00:39

with directly in this video and I'm

play00:42

going to run it to show you what this

play00:44

API can do so API is running I'm going

play00:47

to go to postman and we can list all the

play00:49

movies in the system now unfortunately

play00:51

we don't really have any so what I'm

play00:53

going to do is I'm going to create a new

play00:54

movie I'm going to create the famous

play00:55

comedy Nick the Greek both the way back

play00:57

in 2010 so that is now create it in the

play01:00

system I can list it in that previous

play01:02

endpoint as you can see or I can get it

play01:04

using an ID now oh I made a bit of a

play01:06

mistake it's actually released in 2023

play01:09

and it's also an action movie not just a

play01:11

comedy so I can update it and in the end

play01:13

I can simply just delete it now this API

play01:17

does not have any form of authentication

play01:19

authorization I don't need to be someone

play01:21

or validate that I am someone to be able

play01:24

to call it so my controller looks just

play01:25

like this I have an API controller

play01:27

attribute around implementing the

play01:29

controller base and that's how my

play01:31

endpoints look now don't worry that I'm

play01:33

using controllers I'm also going to

play01:34

cover minimal apis in a second later in

play01:37

the video so how do I add Json web token

play01:39

support well it all starts with a nuget

play01:41

package I'm going to go to nuget

play01:42

packages and I'm going to add the

play01:45

microsoft.aspoon.authentication dot dot

play01:47

Bearer and yes I know it's pronounced

play01:49

just for some reason it's a w but

play01:52

whatever and configuration thankfully is

play01:55

actually pretty simple it could be way

play01:57

way worse so the first thing you need to

play01:59

do is add actually say Services dot add

play02:02

authentication authentication comes

play02:04

before authorization and just to quickly

play02:06

recap for the avoidance of any doubt

play02:08

authentication is the process of

play02:09

verifying that someone is who they say

play02:12

they are while authorization in the

play02:13

process of verifying that someone has

play02:15

access to what they say they have access

play02:18

to or just saying what they have access

play02:19

to so a lot we have these nuget package

play02:21

I can use the jot Bearer defaults and I

play02:24

can use the default authentication

play02:25

scheme here but another approach if you

play02:28

want to just update all the defaults is

play02:30

to do something like this you can set

play02:32

the default indication scheme the

play02:33

default challenge scheme and the default

play02:35

scheme all at once and now with that

play02:37

nuget package we also get this add dot

play02:40

Bearer method which adds the support we

play02:42

need so in here we're going to configure

play02:44

what we want to validate for our jot and

play02:46

just to quickly recap what a jot looks

play02:48

like here I have a job generated from

play02:50

one of my own service we're going to be

play02:52

taking a look at that in a second and

play02:53

first we have the header which contains

play02:55

the type of the token and also the

play02:56

algorithm used to generate the signature

play02:59

then we have a bunch of standard claims

play03:00

and custom ones so Json web token ID is

play03:04

a standard one same with subject and all

play03:06

of these ones over here and then we have

play03:08

a few custom ones email user ID admin

play03:11

and trusted member which I created and

play03:13

then you have an issue and an audience

play03:15

the issuer is who create the token and

play03:17

audience is who is this token intended

play03:19

for so think of I don't know Google

play03:21

authentication creating a token for you

play03:23

to use in Google Slides maybe you don't

play03:26

have access to Google Docs with that

play03:28

thing so that token can only be used in

play03:30

Google Slides even though it was

play03:31

generated by Google and it is a valid

play03:33

token and then in the end both the

play03:35

header and the payload are actually

play03:37

Basics before URL encoded separate with

play03:39

a DOT and then there has to generate the

play03:42

signature hashing is not the only

play03:44

mechanism by the way to do this you can

play03:46

have public key cryptography as well and

play03:48

other approaches but this is by far the

play03:49

most common so a few things you want to

play03:51

validate is the issuer the audience and

play03:54

also that the token is not expired on

play03:56

top of that we want to validate the

play03:57

signature that it is a valid one we can

play03:59

validate all lot by configuring the

play04:01

token validation parameters value we can

play04:03

create a new type over here and what I'm

play04:05

going to do before I paste what goes

play04:07

here is actually add some settings so

play04:10

for the purposes of this video I'm going

play04:11

to keep this here however you would not

play04:14

store the key here you would store it

play04:16

securely in a service specific design to

play04:19

store tokens like Azure key Vault or WS

play04:22

Secrets manager if you want to know how

play04:24

you can do this with AWS secret manager

play04:26

I actually have a video on that topic

play04:27

but you should never have it in the

play04:30

settings like this not only is it not

play04:32

secure but if you want to rotate that

play04:34

token as the application is running this

play04:37

limits you significantly you have to

play04:38

redeploy and then you have to keep track

play04:40

of multiple Keys it becomes very tricky

play04:42

but for this video I'm just gonna leave

play04:43

it here just so you can wrap the code

play04:45

from the description and use it for your

play04:46

own purposes so now with these things

play04:48

set I'm gonna just show you all the

play04:50

parameters we have to specify here and

play04:52

these are sort of the minimum ones you

play04:53

need so we have the valid issuer which

play04:57

will pass down for configuration valid

play04:59

audience or as well then the issue your

play05:01

signing key and that is a new symmetric

play05:03

key in this case which we get from the

play05:05

settings again like I said you really

play05:07

want to load this from somewhere that is

play05:08

designed to store and load these things

play05:10

and then we say that we want to validate

play05:12

the issuer the audience the lifetime of

play05:15

the token so that it is in effect

play05:17

because you can actually future issue

play05:20

one but also that it is not expired so

play05:22

all of these things have to be specified

play05:24

as true and also that you have to

play05:26

validate the issue or signing key

play05:27

because that's ultimately what makes the

play05:29

jot so powerful the fact that it is this

play05:32

stateless construct that all you need to

play05:34

do is validate the signature and then

play05:36

the rest is valid and true because if

play05:38

the signature is valid then the rest of

play05:40

the thing must be because for the hash

play05:42

to be valid the payload and the header

play05:44

have to also be valid so this is

play05:45

everything we need and then the next

play05:47

thing we need is the ad authorization

play05:50

call so I'm going to add it as it is

play05:52

Bare Bones nothing in it and then I'm

play05:54

going to go all the way down to the

play05:55

middleware area and after the https

play05:58

redirection and before all the map

play06:00

controllers I'm going to say use

play06:02

authentication and then app.use

play06:05

authorization now remember that sequence

play06:08

in middleware actually matters so

play06:10

authentication happens first

play06:11

authorization second then event

play06:13

controllers meaning that everything

play06:14

above it are not part of authentication

play06:17

authorization so be very careful now

play06:19

actually in terms of authentication that

play06:21

is it obviously if I just leave my

play06:23

controller as it is and I go and I run

play06:26

it nothing really will happen I will

play06:28

still be able to get all my movies in

play06:30

the database now I have nothing of

play06:31

course but nothing really blocks me from

play06:33

getting them but if I now go in the

play06:35

controller and I say that authorize the

play06:37

users trying to access this controller

play06:39

and I try to run it again then I'm going

play06:41

to get a 401 unauthorized because

play06:43

nothing can authenticate me authorize me

play06:45

to see if I can actually use this API so

play06:48

how do we pass a Json web token to

play06:50

validate that we can actually access it

play06:52

well first we create it and I have a

play06:55

helper identity API here that knows how

play06:57

to create a token it uses the same key

play07:00

which again you don't want to store here

play07:01

as a constant like Jesus just store it

play07:04

somewhere securely and we're going to

play07:05

create a token that lasts for eight

play07:07

hours this is way too long usually for

play07:10

Json web tokens they're way more

play07:12

short-lived and then recreated and if

play07:14

you want to see a video on refreshing

play07:16

tokens leave a comment down below as

play07:17

well but then this is the process I can

play07:19

follow to generate a Json web token with

play07:21

all of my custom claims over here you

play07:24

can just grab this and use it for your

play07:25

own purposes now in reality you will be

play07:27

using something like identity server or

play07:30

OCTA or author zero or some service

play07:32

dedicated to creating these types of

play07:34

things in specific flows but because

play07:36

what these Services automatically

play07:37

generate is a Json web token we're just

play07:39

gonna focus on the implementation side

play07:41

of things we're not going to focus on

play07:42

the creation side of things so we're

play07:44

just going to use this helper service

play07:45

I'm just going to run it and go back to

play07:48

postman and I'm just going to say that

play07:50

hey this is me this is my user id create

play07:54

a token and now I have a token to use it

play07:56

so I'm going to stop this API and run

play07:58

the movies API remember we cannot access

play08:01

this because we're not authenticated but

play08:03

to say that hey it's Nick can I please

play08:05

access this all I'm going to do is go to

play08:08

the headers and specify the

play08:09

authorization header but it's not just

play08:12

pasting the token you actually have to

play08:14

say Bearer space and then the token it's

play08:17

just the way of passing down a bearer

play08:19

token and now if I have that I can go

play08:21

ahead and I can get the item so I am

play08:23

authenticated and in this case

play08:24

authorized as well because we don't

play08:25

really check for anything if the

play08:27

signature was different if in the end I

play08:29

have a zero not an O then I'm going to

play08:31

get an unauthorized because the

play08:33

signature is invalid if this thing was

play08:36

expired then I would get unauthorized as

play08:38

well but in this case I have a good

play08:39

token so nothing really breaks

play08:41

everything just works now let's talk

play08:43

about the very important thing what if I

play08:44

want my create update and delete to be

play08:47

authenticate then authorized but my get

play08:49

doesn't really matter I want everyone to

play08:51

be able to access it you have two

play08:52

approaches here you can either say allow

play08:54

Anonymous here and this allow Anonymous

play08:56

attribute will override the overarching

play08:59

in controller-based Behavior or we can

play09:01

just take the authorize from the

play09:03

controller and we can paste it on each

play09:05

individual thing we want authorize you

play09:07

can ultimately choose which one you want

play09:09

to use in general having it on a pair

play09:12

action basis is actually more used

play09:15

mainly because it allows you to specify

play09:17

different things on the action itself

play09:19

and this is actually where authorization

play09:21

comes in or the process of validating

play09:23

that someone can do what they claim to

play09:25

do for example I want everyone who's

play09:27

authenticated to create and update a

play09:29

movie but I want only admins or

play09:32

administrators to delete a movie how do

play09:34

I do that well it's a few ways but the

play09:36

simplest one is by using a claim so in

play09:39

that Json web talk and if you remember

play09:41

what I said in a custom claim is that an

play09:44

admin is false now usually when someone

play09:46

is not something you wouldn't have it in

play09:49

the token you will just not have the

play09:51

claim at all the absence of a claim

play09:52

means that that user is not something

play09:54

but if I just run this API again and I

play09:57

regenerate this token and I say that yes

play09:59

this is actually an admin then I have a

play10:02

token of someone who is an admin and can

play10:05

delete on top of create and update now

play10:07

how do we Implement that well what we're

play10:09

going to do is create an identity holder

play10:12

over here and I'm just going to create a

play10:13

new class called identity data or

play10:16

identity constants or whatever you

play10:18

really want to name it now first I'm

play10:19

going to add the constant that is the

play10:21

claim in my Json web token and also I'm

play10:24

going to add a name to a policy in this

play10:27

case that is the admin user policy now

play10:29

these things are different the claim is

play10:31

a Json web token concern the policy is

play10:34

an application concern I can Define my

play10:36

own policies based on claims or other

play10:38

things to create a policy all I'm going

play10:40

to do is go all the way up here to add

play10:42

authorization and I'm going to say

play10:44

authorization options and say options

play10:47

dot add policy and I can create my own

play10:49

policy using a name so I'm going to say

play10:51

identity data equals admin user policy

play10:54

name and then what do I want I want a

play10:56

policy using this policy Builder that

play10:58

requires a claim and the claim I want is

play11:01

in identity data dot admin user claim

play11:04

name and the value I want for this

play11:05

policy is true so now I have my policy

play11:08

registered it's not used anywhere by

play11:10

default we just have it now in the

play11:12

system and we can go ahead and just copy

play11:13

this and we can say that you know what

play11:15

create an update doesn't really need

play11:17

anything I'll go all the way to delete

play11:18

over here and say that actually I want

play11:20

this policy to be identity data dot

play11:23

admin user policy to delete and move in

play11:25

the system so I'm going to run this and

play11:27

I'm going to use the previous token I

play11:29

have that has admin as follows so if I

play11:32

try to create a movie using that all

play11:34

token the non-admin token then I can and

play11:36

I get my movie but if I go to delete

play11:39

over here to delete that movie without

play11:41

being an admin what I'm going to get is

play11:43

403 or Biden not for one unauthorized

play11:46

forbidden you're forbidden to make this

play11:48

action and that is because I just don't

play11:51

match the profile that the policy

play11:53

requires me to have which is having the

play11:55

claim as true now if I go and I use this

play11:58

new token over here which is an admin

play12:00

then I can go here replace this send and

play12:03

now it is deleted and it no longer

play12:05

exists in the system and that is it now

play12:07

you can go even deeper and have multiple

play12:09

policies and mix and match on different

play12:11

things in customer sessions but this is

play12:13

the most basic way of making a policy

play12:15

however Some people prefer to validate

play12:18

based on a single claim without using a

play12:21

policy and one of the preferred ways is

play12:23

to actually create a custom attribute

play12:24

which validates claims what I'm going to

play12:27

do is create a new attribute called

play12:29

requires claim attribute over here and

play12:32

I'm going to have that be an attribute

play12:34

used on classes or methods and it's

play12:37

going to extend application and

play12:39

Implement I authorization filter if you

play12:42

needed an async version of this there's

play12:44

I async authorization filter we don't

play12:47

need async in this case so I'm just

play12:48

gonna use this and all you get is an on

play12:51

authorization method now this is not

play12:53

usable with minimal apis because of how

play12:55

the filtering works there however for

play12:58

controllers this does work if you want

play13:00

to have the equivalent of this in

play13:01

minimal ABS you have to use a minimal

play13:03

apis endpoint filter and now here all we

play13:06

need to pass down is a claims name and

play13:08

the claims value that we expect and then

play13:10

all we need to say in all authorization

play13:11

is hey if this user doesn't have this

play13:14

claim with this value then say forbid or

play13:17

unauthorized depending on how the flow

play13:19

works in your application the reason why

play13:21

I say that is because in this example

play13:23

over here what we're going to say is

play13:25

actually authorize first and then

play13:28

requires claim second and all we need

play13:31

here is actually the identity data dot

play13:34

admin user claim name and the value

play13:36

needs to be true and if we do that I'm

play13:39

going to put a breakpoint in the

play13:40

attribute and then go ahead and debug

play13:42

the application and again the same way

play13:44

as before I'm going to revert to the all

play13:48

token in fact first I'm going to

play13:50

generate a movie so the movie is created

play13:52

take that ID and then try to delete that

play13:54

movie with the valid token and let's see

play13:57

what happens oh request comes in here we

play13:59

have the context we have everything and

play14:01

then the claim name is admin and the

play14:02

value we expect is true is that true

play14:04

well let's see claims principle over

play14:06

here and then we have all the claims and

play14:08

one of them is admin true so it will be

play14:11

validated so it will have it it will

play14:13

step out of it and the action will in

play14:16

fact happen okay if we use the old token

play14:19

and we try to do the exact same thing

play14:20

then we come in here but the user claim

play14:22

as you can see in the claims is actually

play14:25

false so it's gonna fall in here say

play14:27

forbidden and then return 403 Forbidden

play14:29

because we are authenticated but not

play14:31

authorized that's another way you can

play14:33

get clever and have a handy approach in

play14:35

claim-based authorization and you can

play14:37

take this in any direction you want

play14:38

really now if you were to be using

play14:40

minimal apis all of those things are

play14:42

actually still valid the difference

play14:43

would be that yes you can for example

play14:46

say map post and let's have a movies

play14:49

endpoint over here and return results

play14:51

dot OK for example now you can pass down

play14:54

and authorized attribute over here and

play14:57

all of that will still work or requires

play14:59

claim like that is just valid C sharp

play15:01

however in minimal apis we actually

play15:04

prefer the extension method approach so

play15:06

we're going to say require authorization

play15:07

and you can create your own extension

play15:09

for the claims and everything but you

play15:11

can pass down like a policy over here

play15:13

you can see all the parameters you can

play15:15

pass down multiple policy names as well

play15:17

but in this case if I just say identity

play15:19

data dot admin user policy name this

play15:22

will be the same thing as having the

play15:24

attribute with the policy name now the

play15:26

last thing you might be interested is

play15:27

actually Swagger support because if I

play15:30

just go ahead and I run this API as it

play15:32

stands I can go in Swagger and even

play15:33

though I can see all my endpoints I

play15:36

can't see a way to actually authenticate

play15:38

with the token so how do I do that well

play15:40

it's actually quite simple all I'm going

play15:42

to do is create a new directory called

play15:43

Swagger and I'm going to bring two files

play15:45

in here the first one is called

play15:47

configure Swagger option so we're gonna

play15:48

contain all the swag related options in

play15:51

here and this will need to implement the

play15:52

iconfigure options and then have the

play15:54

Swagger gen options file in here

play15:56

implemented and we have the configure

play15:57

method in here and I'm not going to buy

play15:59

you with typing all of this but

play16:01

ultimately what you need is a security

play16:03

definition and we say that this is a

play16:05

better token specify that is located in

play16:06

the header authorization HTTP jot better

play16:09

everything is here same with the ad

play16:11

security requirement and really that is

play16:13

it from that front and then once you

play16:15

have that you actually need to register

play16:17

it in the program.cs so all the way up

play16:20

here we're gonna go here and register

play16:22

the iconfigure options interface with

play16:24

its implementation and once that's in

play16:26

place all I'm going to do is just run it

play16:27

and now if we go back to Swagger as you

play16:29

can see I have this authorized button

play16:31

which I can click and provide the Json

play16:33

web token so I'm gonna go all the way

play16:35

back here copy just the token you don't

play16:37

need anything else and just paste it

play16:38

here authorize and if I go to create a

play16:41

movie for example and say tried out

play16:43

paste it and then execute no problem it

play16:46

all worked it was created if I wasn't if

play16:49

I just say padlock and log out and I try

play16:51

to do this again I'm going to get a 401

play16:53

hey you cannot do this so now we also

play16:56

have Swagger support this is it for all

play16:58

the basics you can take it in any

play16:59

direction you want from this point on I

play17:01

do go way more in depth in my rest API

play17:03

calls on every single one of those

play17:05

Avenues however you are now in the right

play17:07

track and you can take it everywhere you

play17:09

want from that point well that's all I

play17:10

have for you for this video thank you

play17:11

very much for watching special thanks to

play17:13

my patreons for making videos possible

play17:14

if you want to support usually going to

play17:16

find the link description down below

play17:17

leave a like if you like this video

play17:18

subscribe more content like this in the

play17:20

Bell as well and I'll see you the next

play17:21

video keep coding

Rate This
โ˜…
โ˜…
โ˜…
โ˜…
โ˜…

5.0 / 5 (0 votes)

Related Tags
JWTAuthenticationASP.NET CoreTutorialAPI SecurityAuthorizationWeb TokensCoding TutorialPostman APISecurity Best Practices