#38 Spring Security | Validating JWT Token

Telusko
8 Aug 202420:36

Summary

TLDRThis video tutorial demonstrates the process of implementing JWT authentication in a Spring Security application. It covers creating and verifying JWT tokens, modifying the security configuration to prioritize JWT over traditional username/password authentication, and adding a custom filter to handle token validation. The presenter guides viewers through coding examples, troubleshooting, and adapting to changes in library versions, ultimately enabling a secure, token-based authentication system.

Takeaways

  • 🔒 The video demonstrates the process of creating and using a JWT (JSON Web Token) for authentication in a Spring Security context.
  • 📝 It explains that after successful login with username and password, a JWT is generated and sent to the client for subsequent requests.
  • 🔄 The client must send the JWT in the Authorization header without the username and password for accessing secured resources.
  • 🛠️ The video outlines the need to create a custom JWT filter that precedes the default username and password authentication filter in the security filter chain.
  • 👤 The JWT filter is responsible for extracting the token from the Authorization header, validating it, and creating an authentication object if the token is valid.
  • 🔑 The process of validating the token involves decoding it, checking for expiration, and ensuring it corresponds to a valid user in the database.
  • 🛑 The video emphasizes the importance of checking if the security context is already authenticated to avoid re-authentication of the user.
  • 📚 It mentions the creation of methods in the JWT service for extracting the username from the token and validating the token's authenticity and expiration.
  • 🔄 The video script includes code snippets and explanations for implementing the JWT filter and service, including handling changes in library versions.
  • 📈 The presenter guides the viewer through the entire flow from token generation to validation, emphasizing the steps involved in securing an application with JWT.
  • 💻 The video concludes with a successful demonstration of the JWT authentication flow in a Postman request, showing that the system is working as expected.

Q & A

  • What is the purpose of JWT in the context of the script?

    -JWT (JSON Web Tokens) are used for authentication and authorization in the script. They allow the server to generate a token after a successful login, which can then be used to access secured resources without the need to send username and password with every request.

  • How does the server verify the username and password in the script?

    -The server verifies the username and password by checking them against the credentials stored in the database. If they match, the server proceeds to generate a JWT for the user.

  • What issue is being addressed with the token in the script?

    -The issue being addressed is that while the token is being generated correctly, the application is not able to use it to access resources like fetching students' data. The token needs to be validated on the server side to make this work.

  • What is the role of the 'OncePerRequestFilter' in the script?

    -'OncePerRequestFilter' is an abstract class that ensures the filter logic is executed only once per request in the Spring Security filter chain. It is used as a base for creating custom filters like the JWT filter.

  • How does the script handle the order of filters in the Spring Security configuration?

    -The script modifies the filter chain order by adding a custom JWT filter before the UsernamePasswordAuthenticationFilter. This ensures that the JWT filter is checked first for authentication before falling back to username and password authentication.

  • What is the significance of the 'doFilterInternal' method in the script?

    -The 'doFilterInternal' method is an abstract method that must be implemented in any filter extending 'OncePerRequestFilter'. It contains the core logic for processing the incoming HTTP request and is where the JWT validation takes place.

  • How does the script extract the JWT from the HTTP request header?

    -The script extracts the JWT from the 'Authorization' header of the HTTP request. It checks if the header starts with 'Bearer ', and if so, it extracts the substring that represents the actual token.

  • What is the process for validating the JWT in the script?

    -The validation process involves extracting the username from the JWT using a service method, checking if the token is not expired, and ensuring that the username exists in the database. If these conditions are met, the token is considered valid.

  • How does the script create an authentication object after validating the JWT?

    -After validating the JWT, the script creates a 'UsernamePasswordAuthenticationToken' with the username as the principal, null as the credentials, and authorities fetched from the user details.

  • What changes are required in the 'JWTService' class to support the new version of the JWT library?

    -In the new version of the JWT library, changes include using 'verifyWith' instead of 'setSigningKey', and updating method calls to reflect changes in the library's API, such as using 'signedClaims' instead of 'claims' and 'payload' instead of 'body'.

  • How does the script ensure that the authentication process is secure?

    -The script ensures security by validating the JWT for each request, checking for token expiration, and ensuring that the username mentioned in the token exists in the database. It also sets the authentication object in the security context to bypass the username and password authentication filter for subsequent requests.

Outlines

00:00

🔐 JWT Token Creation and Usage

This paragraph discusses the creation of a JWT token for authentication purposes. It explains the process of generating a token upon successful login with username and password verification. The token is then used to access resources like fetching student data without the need to resend credentials. The speaker highlights an issue where sending a token to access a resource is not working as expected and outlines the need to validate the token on the server side. The explanation includes the server's default behavior of using username and password authentication and the intention to prioritize JWT token validation over this default method.

05:00

🛠️ Implementing JWT Token Validation

The focus of this paragraph is on implementing JWT token validation in a Spring Security configuration. It details the steps to modify the security filter chain to prioritize JWT token validation before the username and password authentication filter. The process involves creating a custom JWT filter by extending the 'OncePerRequestFilter' class and implementing an abstract method to handle the filter logic. The paragraph also addresses the need to import necessary classes and create a JWT filter object in the security configuration, which leads to the creation of a new class for the JWT filter if it's not available by default.

10:01

📜 Extracting and Validating JWT Tokens

This section delves into the technicalities of extracting and validating JWT tokens within a custom filter. It describes how to retrieve the token from the authorization header, verify its structure, and decode it to extract the username. The paragraph explains the importance of checking if the token is not already authenticated and how to use a JWT service to validate the token's authenticity and expiration. It also outlines the creation of an authentication object using the extracted username and setting this object in the security context to pass the authentication to subsequent filters.

15:03

🔄 Updating JWT Service for Token Handling

The paragraph discusses updates required in the JWT service to handle token extraction and validation. It mentions creating methods for extracting claims from a token and validating the token's validity, including checks for expiration and the presence of the user in the database. The speaker also addresses changes in the library's method signatures due to version updates and provides guidance on adapting the code accordingly. The paragraph concludes with the successful execution of the flow, where a token is generated, used to authenticate a request, and the subsequent resource access is granted without the need for username and password.

20:05

🚀 Finalizing JWT Integration and Security

The final paragraph wraps up the process of integrating JWT for secure resource access. It summarizes the entire flow from token generation upon login to its validation in subsequent requests. The speaker emphasizes the importance of correctly setting up the JWT filter in the security configuration and the JWT service for claim extraction and validation. The paragraph concludes with a demonstration of the successful authentication flow using a token and hints at future implementations in an ongoing project, encouraging continuous learning until the next video.

Mindmap

Keywords

💡JWT Token

A JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties. In the video, the creation and use of JWT tokens for authentication purposes are central to the discussion. The script describes the process of generating a JWT token upon successful login and then using it to access resources without re-entering username and password.

💡Spring Security

Spring Security is a powerful and customizable authentication and access-control framework for Java applications. The video script frequently mentions Spring Security in the context of configuring and using it to handle JWT authentication. It is the foundation for the security mechanisms being discussed, including the creation of filters and the authentication process.

💡Authentication

Authentication is the process of verifying the identity of a user or device. In the script, authentication is a key theme, with detailed steps provided for how a user's credentials are checked and a JWT token is generated upon successful authentication. It's also discussed how subsequent requests use this token for authentication.

💡Authorization Header

The Authorization Header is part of the HTTP protocol and is used to contain the credentials (e.g., tokens) that a client sends to a server as part of an HTTP request. In the video script, the authorization header is mentioned as the place where the JWT token is sent from the client to the server for resource access.

💡Filter Chain

In Spring Security, a filter chain is a sequence of filters that are applied to an HTTP request. The script explains how to modify the filter chain to include a JWT filter before the default username and password authentication filter, which is crucial for the authentication process using tokens.

💡Username and Password Authentication Filter

This is a specific type of filter in Spring Security that handles authentication based on a username and password. The script describes how, in the context of JWT, this filter is not used for initial login but comes into play after the JWT has been verified, ensuring that the request is associated with a logged-in user.

💡Claims

In JWT, claims are statements about an entity (typically, the user) and additional metadata. The script refers to extracting claims from a JWT token, which includes the username and other potential information that is used for validating the token's authenticity and the user's identity.

💡Token Validation

Token validation is the process of checking the integrity and authenticity of a token. The video script outlines the steps for validating a JWT token, including checking the signature, the expiration time, and ensuring the token has not been tampered with.

💡Security Context

The Security Context in Spring Security is an object that holds the current authentication object and is used to determine the currently authenticated user. The script describes how, after validating the JWT token, an authentication object is created and set in the security context to represent the user's session.

💡Postman

Postman is a popular API client used for testing and interacting with HTTP services. In the script, Postman is used to demonstrate the process of logging in to obtain a JWT token and then using that token to make authenticated requests to the server.

💡Service Layer

In software architecture, the service layer is a logical grouping of business logic that is separate from the presentation and data access layers. The script mentions the service layer in the context of creating methods for extracting usernames and validating tokens, which are part of the business logic for handling JWTs.

Highlights

Introduction to creating and using JWT tokens for authentication in a web application.

Demonstration of the login process and token generation upon successful authentication.

Explanation of how to send login details and the server's verification process to generate a token.

Using a token for accessing resources without passing username and password each time.

Troubleshooting the process when the token is not working as expected.

Details on configuring Spring Security to permit certain requests without authentication.

The necessity of adding a JWT filter before the user password authentication filter.

Creating a custom filter class by extending OncePerRequestFilter.

Implementing the doFilterInternal method to handle the JWT authentication process.

Retrieving the JWT token from the authorization header in the request.

Decoding the JWT token to extract the username and validate the token's authenticity.

Using Spring Security context to check if the user is already authenticated.

Creating an authentication object if the token is valid and setting it in the security context.

Continuing the filter chain after successful JWT validation.

The importance of updating service methods to support token extraction and validation.

Changes in the JWT library and how to adapt the code for newer versions.

Final demonstration of the complete flow from token generation to validation in requests.

Conclusion and summary of the JWT authentication process in Spring Security.

Transcripts

play00:00

so till this point we were able to

play00:02

create the token the JWT token so just

play00:05

to show you how it was looking so if you

play00:07

go back here and if you click on login

play00:09

so we are passing the details if you can

play00:11

see the body we are sending the login

play00:13

details which is Navina and and at the

play00:15

rate 1 to3 when you click on send the

play00:17

request goes to the server and then on

play00:19

the server side it verifies the username

play00:21

password and if the username is password

play00:23

is correct in that case it generates a

play00:25

token which you can see here and of

play00:28

course using this token I want to do

play00:30

other activities example I've done the

play00:31

login once right and I got the token and

play00:33

now let's say from the application if I

play00:36

want to access any resource example if I

play00:38

want to fetch students and I don't want

play00:40

to pass the username password now so in

play00:42

the earlier scenario we were sending the

play00:45

username password but now we don't want

play00:46

to do that we want to send a token which

play00:48

is a better token and here we should be

play00:51

able to paste it and we are doing that

play00:53

but when you click on send this is not

play00:55

working and we want to make it work so

play00:57

generating token done but we have to WR

play01:00

the token and give the access to the

play01:02

user that's what you have to do in this

play01:03

video okay u in fact this token is also

play01:05

valid we have checked that on jw. we got

play01:08

the details we got the claims and we got

play01:10

other details so things are working out

play01:12

it's just that now we have to validate

play01:14

token and we have to make this work now

play01:16

how we are going to do that so of course

play01:17

there are multiple steps involved the

play01:19

first thing you have to do is when you

play01:20

send a request to the server by default

play01:22

see one there's one thing uh I wanted to

play01:24

point it out if you go to security

play01:26

config we have mentioned that for this

play01:28

two requests the register and and for

play01:30

login you don't have to check for

play01:32

authentication so basically they are

play01:33

permitted but for the all the other

play01:35

request it will be authenticated that

play01:36

means when you request for the students

play01:38

it will be authenticated and by default

play01:41

the authentication we follow is user

play01:43

password authentication so by default

play01:45

that filter comes to picture now if you

play01:47

remember we have talked about filters

play01:48

right so in Spring Security we have

play01:50

multiple filters one of the filter is

play01:52

user password authentication filter this

play01:54

is a filter which gets activated and

play01:56

then it checks for username password now

play01:58

what we are saying is hey you know I

play01:59

don't don't want this filter to be

play02:01

activated first before this filter I

play02:03

mean I want to make this filter which is

play02:06

UF as your second filter and the first

play02:09

filter should be your JWT filter now

play02:11

this will check for the token right now

play02:13

once you verify token as a first filter

play02:16

then it will send the request to the uh

play02:18

UPA filter by saying hey I have verified

play02:21

and this is a user already logged in so

play02:23

I'm confirming that so you can just

play02:25

continue with the other work so this is

play02:26

what we want to do so that means we have

play02:27

to add a filter before the user password

play02:30

authentication filter and the way you

play02:32

can do that is very simple it's not

play02:33

actually you know this this video is

play02:35

also very lengthy so just be with me and

play02:37

there a lot of things going on and if

play02:39

you watch it with me and if you write

play02:41

the code with me it will make much more

play02:43

sense so the first thing you do is

play02:45

before you build you know I'm in the

play02:47

security config and we are working with

play02:49

security filter chain basically we're

play02:50

working with Filter chain and before you

play02:52

say build what you do is you add a

play02:54

filter before the user authentication

play02:56

filter right so you will say add filter

play02:59

before so you can you can add filter

play03:00

anytime you can add filter uh you can

play03:02

add filter at particular point you can

play03:04

add filter after or before so I want to

play03:06

add before the user authentication

play03:07

filter so I will do that uh the first

play03:09

parameter is actual filter so let's say

play03:11

I want to say this is a JWT filter so

play03:13

that's the object we have to pass the

play03:14

second one is the class the filter class

play03:17

so I will say usern name password

play03:20

authentication filter now this is what

play03:22

we have to specify so what I'm doing is

play03:24

I'm saying that hey you know before you

play03:26

hit this particular filter use this

play03:28

filter but what is this filter we have

play03:30

to work with this so in that case you

play03:32

will go up here and create the object of

play03:36

private

play03:37

JWT filter J filter so this is what so

play03:41

we have created the object here I mean

play03:43

we are doing Auto wire and then that

play03:45

object would be used here okay but the

play03:47

problem is and it says that uh this jwd

play03:50

filter is not able to find it so it's

play03:52

very simple you can just simply say

play03:53

control space let's import the package

play03:56

oh it says no suggestion that means in

play03:58

your library of sping security we don't

play04:00

have this filter by default and that's

play04:02

where you get the opportunity to create

play04:04

a new filter I know I'm using some

play04:06

positive words here opportunity yeah we

play04:08

have to get another class to make it

play04:10

work so let's do it you know anyway we

play04:12

are doing this only once so I will just

play04:13

click here and say hey create a class

play04:16

and when I want to do that maybe in the

play04:17

same package config logically it should

play04:19

be in a separate package called filter

play04:21

package but config works for this

play04:22

example I will click on okay and we got

play04:25

this new class now I want this to behave

play04:28

like a filter okay how do we make make

play04:29

something behave like a filter what you

play04:32

do is you extend those properties right

play04:34

so if I want to be rich I want to get

play04:35

adopted by some Bia right so here I want

play04:39

to extend I want to make this a child

play04:41

class of some parent class which has a

play04:44

filter capability so one of the filter

play04:46

we are going to use here is I mean

play04:47

that's one one of the class we're going

play04:48

to extend is once per request filter I

play04:51

know very nice name to give to a filter

play04:54

or the class this is called once per

play04:56

request filter see the reason is every

play04:58

time you send a request you want want a

play05:00

filter to get activated and in the

play05:01

filter chain you want this filter to be

play05:04

executed only once so for every request

play05:07

you want this filter to be executed only

play05:09

once and that's why you're saying once

play05:10

per request filter now it is giving you

play05:12

some error I was not expecting but let's

play05:15

see this once per filter is actually an

play05:18

abstract class which means there might

play05:19

be some abstract methods which we have

play05:21

to implement and if you scroll down down

play05:23

down all the methods are defined but one

play05:26

method is there yeah there's always one

play05:28

so one method is there which is called

play05:29

called do filter internal which is

play05:31

abstract method that means if you want

play05:33

this to work we need to we need to we

play05:35

need to we need to implement it so let's

play05:37

click on Implement and okay so this is a

play05:40

filter we have to work with now if you

play05:41

go back to our sessions on Spring web we

play05:43

have talked about HTTP subet behind the

play05:46

scene everything is sub right and it

play05:47

gives you two objects to work with

play05:49

request object to work with the data in

play05:51

the request of the user response object

play05:53

if you want to add something to the

play05:54

response and here I just want to work

play05:56

with a request so let's use request but

play05:58

what I want to do that's a big question

play06:00

see it's actually very simple see on the

play06:02

client side you are sending a request

play06:04

right for for the students and with that

play06:06

request you are sending a token as well

play06:08

now this token when you receive on the

play06:10

server side you will not get to the

play06:11

Token as this just the token what you

play06:13

will receive is can I type here no I

play06:15

can't type here uh maybe I will type in

play06:17

body so what I receive from this server

play06:19

not a good place to type right okay so I

play06:21

will just go back here and I will write

play06:23

a comment so from the client side what

play06:24

you will get is better that's the first

play06:26

word and then you will get the token I

play06:28

think token is this yeah so this is what

play06:30

you get from the client side so it

play06:32

starts with better and then a space and

play06:34

then it starts with the actual token

play06:36

this is what you get from the client

play06:38

side right now what you have to do is

play06:40

you have to get this token and you have

play06:41

to cut that better part you just have to

play06:42

focus on this part get this token and

play06:45

viate it so simple right okay not that

play06:47

simple I mean breaking out is simple

play06:49

viting is difficult so let's be with me

play06:51

so how will I get this thing the entire

play06:53

stuff and actually it's a part of

play06:55

request so it sends the data this better

play06:58

and the token in the request object in

play07:01

the headers so what I can do is I can

play07:02

get the headers so I will say security I

play07:04

will say or header so header will have

play07:06

lot of things I don't want everything so

play07:09

from the request I just want a header

play07:11

which talks about authorization this is

play07:13

the only header I need it will have lot

play07:15

of headers but I just want authorization

play07:17

and once you got this Au header this

play07:19

will have this token but I want only the

play07:21

last part so I will save this token

play07:23

somewhere in the token and by default I

play07:25

will keep it null I want the username as

play07:27

well because somewhere we have to work

play07:28

with the username because because you

play07:29

will generate a token you will verify

play07:30

the token with the help of username and

play07:32

now let's get started so first thing I

play07:34

want to check is do we have any

play07:36

authorization header so let's check that

play07:37

so if there is a o header which is not

play07:40

equal to null in that case you have to

play07:42

continue so that's the first thing you

play07:43

want to check you you want to make sure

play07:44

that this is not null and you have to

play07:46

also verify do we have a better token so

play07:49

again I will check Au header so it

play07:52

starts with it should start with better

play07:54

so you can even say B but to be on safe

play07:56

side I will say it should start with

play07:57

better in case if it is starting with

play07:59

that I will set the token and I want to

play08:01

fetch the token now and fetching token

play08:03

is very easy you will say Au header dot

play08:06

uh you want you don't want the entire

play08:07

string right you just want this

play08:09

particular token here so I want to skip

play08:10

these letters now what are this letters

play08:12

so I will start with index of zero so

play08:14

this is b is0 1 2 3 4 5 and then six the

play08:20

space is also there right so I want to

play08:22

start from seven so it should start the

play08:25

substring from Seven index number seven

play08:27

and I want to get the username from the

play08:29

token so I will say username equal to

play08:31

now how will you get the uh username

play08:33

from the token because token is encoded

play08:35

right so you can see this you have to

play08:37

find usern from this as a human also you

play08:38

can't do that so we have to do something

play08:40

for the program to work but I will make

play08:42

sure that I do that in the service so I

play08:44

will use Service uh object and we don't

play08:46

have the service auto autowired here so

play08:49

I will say autowired private JWT service

play08:53

service okay so I will use this and in

play08:57

this I will make sure that I have an

play08:58

object I have I have a method called

play09:00

extract username maybe it will have

play09:02

username so for where exactly it will

play09:04

extract the to extract the username from

play09:06

the token and you can see there's a red

play09:07

here because we don't have this method

play09:08

in the service yet so what I will do is

play09:10

I will say okay uh create this method of

play09:12

uh extract token and at this point I

play09:14

will just return empty we'll code it

play09:16

later so this is empty so so that we

play09:18

will not get any error and you can see

play09:19

there's no error here now once you got

play09:21

this two now we have to verify so once

play09:22

you got the details you got the token

play09:24

now you got username so I will check if

play09:26

so the username should not be equal to

play09:28

null that's the first thing I to check

play09:29

and I also want to make sure that

play09:31

there's no it's not already

play09:32

authenticated so if the object is

play09:34

already authenticated why you have to

play09:35

verify all those things so I will say

play09:37

security context holder dot get

play09:41

context. get authentication and this

play09:44

should be null so if it is not null then

play09:46

I don't want to continue because it's

play09:47

already auth authenticated so I will

play09:49

just continue with this so this should

play09:50

be null if these two are matching see

play09:52

ultimately what you have to do is we

play09:54

have to validate token see we into

play09:55

filter now right so see if this filter

play09:57

is Success then we'll forward it to the

play09:59

user pass authentication filter right

play10:01

now how do you specify that is this is

play10:02

Success the first thing you have to do

play10:03

is you have to validate the token if the

play10:05

token is valid valid in that case you

play10:07

will create the authentication object

play10:09

and that's what you have to do here so

play10:11

to do that I want to verify right so I

play10:13

will say JWT service dot in this

play10:15

particular class I want a method which

play10:17

will validate the token because all the

play10:19

things we are doing in the JW service

play10:21

right so let's do that so there should

play10:22

be a method called validate token and

play10:24

you have to pass the token now when

play10:25

you're validating you have to check two

play10:27

things one in the token the token should

play10:29

be valid and second the username which

play10:31

is it is mentioning it should be part of

play10:33

a database right and to refer to

play10:35

database I will pass the object of user

play10:37

details and we have to create this

play10:39

object somewhere now where should I

play10:40

create the object I can do that here so

play10:42

I can say user details we have to import

play10:45

the package use it details and then I

play10:49

can actually Auto if you keep it on top

play10:51

but I think it will create a cyclic

play10:52

redundancy so what you can do is you can

play10:54

get the hold on the application context

play10:56

object so I will say autowire and applic

play10:59

context context remember when we were

play11:02

running about spring framework we have

play11:04

used this application context to get the

play11:06

bean so here also I will say context.

play11:09

get bean of type user

play11:13

details. class but the problem is it

play11:15

will give you a empty object I don't

play11:17

want empty object what I want is I want

play11:20

the object of user details which will

play11:21

have the user data now if you go back to

play11:23

my Detail Service in this you have this

play11:25

method called load user by username and

play11:28

this will give you the object of us

play11:29

details that means if I ask for the

play11:32

object of my user details service dot

play11:36

class and from this object if I can get

play11:38

load by username and if I pass the

play11:40

username here it will file database and

play11:43

it will get me the username right and

play11:45

not just username it will give me the

play11:46

entire user D object okay so that's what

play11:48

we are doing here but if you can see in

play11:50

JW service we don't have this method so

play11:52

I will just create one so the method

play11:54

name is Ved token and at this point I

play11:55

will return true okay let's go back to

play11:57

the filter now if the token is valid it

play11:59

in that case remember we have the next

play12:01

filter we have to make it work so the

play12:03

next filter is next next filter will

play12:05

work with the username password

play12:06

authentication filter but I want to pass

play12:08

a token there so I will create a token

play12:10

and I will say new username password

play12:12

authentication token now this token asks

play12:14

you for three things one is a principal

play12:17

next is a credentials and third is

play12:19

authorities so user principles we

play12:20

already have which is the object of user

play12:22

details which will have all the details

play12:23

about the user credentials I don't want

play12:25

to mention so I will keep it null

play12:26

authorities I have is so will get it

play12:29

from user details. getet authorities

play12:32

okay that is that that is what it was

play12:34

asking and we are getting is it a

play12:36

warning variable token is already

play12:38

defined in the scope where exactly I'm

play12:40

using token okay so I will use something

play12:43

else okay toen token we already have it

play12:45

here right so this should be Au token if

play12:48

it makes it happy now o token knows

play12:51

about the user but or token has no idea

play12:53

about the request object right so this

play12:55

request object will have lot of data and

play12:56

we are just creating this object and we

play12:58

are passing it so this object should

play12:59

also know about the uh request object so

play13:03

you will say set details and to specify

play13:05

that you have to use web authentication

play13:07

details Source sometime you have to just

play13:09

remember the class names and stuff it

play13:11

becomes very complex you just get get

play13:13

into it and with this object you will

play13:15

say build details and you will pass the

play13:17

request object and now once you have

play13:19

this OD token ready is just you have to

play13:21

set this in the context so this

play13:23

particular thing which is authentication

play13:24

should not be there by default and

play13:25

that's what we are taking for null now

play13:27

once it is verified you have to set the

play13:28

Authentication so you will say secur the

play13:30

context holder dot now instead of saying

play13:32

get authentication you will say set

play13:34

authentication and you will pass the a

play13:36

token object so by doing this you are

play13:38

adding the token in the chain and once

play13:40

it is ready you will simply pass the

play13:42

request or the filter so now you will

play13:44

say filter chain. do filter so continue

play13:46

the filter because this is one filter go

play13:48

for the next filter once it is done and

play13:50

by doing this you'll pass to objects

play13:51

request and response and done so filter

play13:54

work is done so the JWT filter it will

play13:57

valid the token it will uh create the

play13:59

authentication object it will pass it

play14:00

next so now it will we not we don't have

play14:03

to pass the username password now if

play14:04

you're thinking this is done uh not

play14:06

exactly what is missing now is this if

play14:10

you go back to your jbu service we do

play14:12

have two methods which are empty you

play14:14

need to make sure that this is completed

play14:16

now of course we can type the entire

play14:18

code here but then when you want when

play14:20

you got a token and when you want to

play14:22

extract the usern name it's not a simple

play14:24

process we have to decode it we have to

play14:25

fetch the claims from that we have to

play14:27

fetch the username for valid token we

play14:30

have to do M lot of steps you have to

play14:31

check for the expiration time uh you

play14:33

have to check if the account is not I

play14:35

mean lot of things are involved right so

play14:37

we can do that here but I what I want to

play14:39

do is I just want to copy paste so that

play14:41

we can save some time so basically this

play14:43

is the thing we do so I will explain the

play14:44

code to you don't worry okay so this is

play14:46

the code which you have to work with so

play14:48

if you can see if you go up this is what

play14:50

we have done before but now we are

play14:52

saying that you have to extract the

play14:53

username now to extract the username

play14:55

it's not just extracting a username

play14:56

right first you have to get the claims

play14:57

because username is is a part of the

play14:59

claim and that's what you can see here

play15:01

so we we creting a method called extract

play15:03

claims in which you are passing the

play15:05

claims and you're passing the token now

play15:07

in this extract claim basically it will

play15:09

fetch the claim it will extract all the

play15:11

claim and that's what we are doing here

play15:13

extracting the claim with the help of

play15:15

signing key because you have to also use

play15:16

the key to do that and we are fetching

play15:20

it here in the claims and that's what

play15:22

you are returning it here so from that

play15:24

you will get the username so you can see

play15:26

from the claim we getting the subject

play15:27

and if you go down we are also we also

play15:29

have a meod called validating but for

play15:31

validity of course you have to check if

play15:32

the token is expired or not and that's

play15:34

what we are doing here so it's checking

play15:35

if the expiration time is before this

play15:38

then it will give you false otherwise it

play15:39

will give you true and uh I mean of

play15:42

course it will return true if it is

play15:43

expired then we have to check it should

play15:45

not be expired and this is how you're

play15:47

extracting the expiration time so

play15:49

basically what you're doing is you are

play15:50

fetching the claims I pasted this code

play15:52

because it's more redundant code and

play15:54

you'll be doing it only once that's why

play15:56

you pasted it important point to observe

play15:58

there are few changes from the last time

play16:00

I did this so first of all let me just

play16:01

import claims that's one and import this

play16:04

function type and one more change they

play16:06

have done some changes in the new

play16:07

version so the code is for the older

play16:10

version uh for the new version they have

play16:12

made some changes the first thing they

play16:13

did is if you go to pass a builder

play16:14

there's no passer Builder so jws has a

play16:17

it's a class and it has a method called

play16:19

passer and then this passer has a method

play16:22

so if you can see earlier we used to use

play16:24

set signin key but now we have to use

play16:26

something called it's verify with so in

play16:28

of signing key we have to say verify

play16:31

with uh but it takes the type of secret

play16:33

key not the key because get key gives

play16:35

you key so what I can do is I can just

play16:37

change the type of it and this should

play16:38

work so I will use secret key here so

play16:40

that it will not give issue here so

play16:42

remember this we have to make one change

play16:44

uh in the get key you have to return

play16:45

secret key now depend upon which version

play16:47

you're using so if you're using the uh

play16:49

version which I'm using then you have to

play16:50

make this changes so anything before

play16:52

this works perfectly for the earlier

play16:53

code but since I'm using 0.12 and

play16:56

anything after that you have to make

play16:57

these changes so go back here to the JW

play17:01

service okay there's also change in the

play17:03

past claim so I will first of all do

play17:06

enter here so in of past claim they they

play17:08

made some good changes so now it is

play17:11

signed claims because it makes sense

play17:13

because it is already signed instead of

play17:15

body they now call it as a payload and

play17:17

how will you know all these things if

play17:18

you go to the method documentation you

play17:19

will see what they have replaced it with

play17:22

again that code will work it's just that

play17:24

it's good to go for the new versions a

play17:26

new code don't go for dicated methods

play17:28

and that's it that should work and where

play17:31

you will find this code you will you can

play17:32

check the description uh you will find

play17:33

the link for the GitHub repository if

play17:35

not there let us know we'll put it there

play17:37

and now after making these changes I

play17:39

hope this will work and if it it works I

play17:41

will tell you the entire flow what we

play17:43

are doing I hope nothing is null nowhere

play17:46

okay cool so this got restarted and we

play17:49

got an error it says okay I

play17:53

think no filter we are using Auto but

play17:57

this itself is not a component

play17:59

component that's what it says Okay so

play18:02

let's make this component just restart

play18:04

and there's no error let's go back to

play18:05

postman first of all let's do the login

play18:07

so I will click on this and okay we got

play18:10

the token though there's no problem with

play18:11

the token I will just copy this and now

play18:14

when you are sending a request for the

play18:15

students you don't have to pass of

play18:17

course the body is not import body is

play18:19

important maybe you're getting the

play18:21

you're getting it right so we don't I

play18:22

have to pass the data uh in the

play18:24

authorization we have to pass the token

play18:26

we are not passing username password now

play18:28

click on send it worked you can see it

play18:30

says okay so what is happening behind

play18:33

the scene let's go with the flow again

play18:34

the first thing you're doing is you are

play18:36

generating a token now who is

play18:37

responsible to generate token if you go

play18:39

back to your security config we are

play18:41

saying that the authentication manager

play18:43

now this time we have a hold on it and

play18:46

we are creating something called login

play18:47

form so if you see user controller we

play18:48

got something a login and inside this

play18:50

login we are doing verify and in verify

play18:52

we are using this filter to achieve that

play18:54

so once we got this we are generating a

play18:57

token so once it is verified the user

play18:58

ified we are generating a token right

play19:00

now in this token generation what we are

play19:02

doing is we are doing all those step

play19:03

building a token with the help of claims

play19:05

we are signing it where it's here we are

play19:07

signing it we have subject issue date

play19:09

expiration after doing all those things

play19:11

what you get is the token right now next

play19:13

time when you send a request you are

play19:15

sending a token now since we are sending

play19:17

a next new request and in that request

play19:19

you are not passing username password in

play19:22

that case you have to mention hey you

play19:23

know don't go for username password go

play19:26

with the jwd filter now what we doing in

play19:27

filter is in the filter basically we are

play19:30

saying that uh first of all get the

play19:32

token from the user or the request check

play19:35

if the token is not empty or token

play19:37

starts with the better if it is there

play19:39

get the username get the token get the

play19:42

data from the database based on what

play19:44

username is you are passing and verify

play19:46

if the it is matching or not if it is

play19:48

matching of course you have to write a

play19:49

token if it is matching you have to

play19:51

create a new authentication object and

play19:53

you have to set that in the context once

play19:55

it is done you through because in for

play19:58

the next filter you have specified that

play19:59

I do have the authentication but there's

play20:01

one problem in the validate token we

play20:02

have to actually validate token and to

play20:04

do that you have to extract the username

play20:05

to extract the usern we have to extract

play20:08

the claims and to extract the claims lot

play20:10

of steps are involved right so yeah

play20:12

that's what we have done in the entire

play20:13

flow and by doing this uh all this thing

play20:16

have been done now you know what is

play20:18

sping security now you know how to

play20:20

generate a token how do you verify the

play20:21

token now you can make your application

play20:23

secure so I hope uh this all these

play20:26

things make sense uh we'll try to

play20:28

implement this in our project which we

play20:30

are building and maybe it will take some

play20:32

time see you in the next video till that

play20:34

point keep learning bye-bye

Rate This

5.0 / 5 (0 votes)

الوسوم ذات الصلة
JWTSpring SecurityAuthenticationToken GenerationWeb SecurityAPI SecurityUser VerificationSecurity FiltersClaims ExtractionSecure Coding
هل تحتاج إلى تلخيص باللغة الإنجليزية؟