Spring Security - Java JWT
JWT -
AUTHENTICATION : check the identity i.e validation [user is valid or not ]
AUTHORIZATION : check weather the user is authorized to access the resource which he is demanding.
Steps for creating spring security project:
- resourse . java brains youtube channel
1. add dependency : spring web ,spring security
2.create SelfUserdetailservice class which will be extending UserDetailsService class from spring security.core library.
In This class we will override methods of UserDetailsService such as loadUserByUserName....So now this method will return the user which will also come from spring security library of User type having username, password ,roles list . So we can also create seperate class extending User class or we can directly return the user from this loadUserByUsername method.
3. Create security configuration class which extends WebSecurityConfigurerAdapter class and annotated with @EnableWebSecurity
Now override cofigure method for authentication having object of AuthenticationManagerBuilder object as parameter,so here we will authenticate by passing myUserdetailService object as parameter to userDetailService method of AuthenticationManagerBuilder object
Also add password encoder with @Bean in same configuration class
4. Now we will need to add JWT json web tokens in our project
Add dependency jjwt in in pom.xml
Also add java jaxb-api dependency if using Java 9+ version
5. Now we will create JWTutil class with@Service in this class we will generate token by passing user details as parameter also we can get username , expiration date ,isTokenExpired,validateToken..... Using jwt library that we added in dependency
6. Create an authenticate API endpoint which will accept userId and password and will return JWT in response.
So for that we will also create class having data for request (UserId, password) and response(JWT token) for authentication whcih will be used in controller
7. In controller we willl need an instance of AuthenticationManager (from spring security library) that will used for authenticating username and password coming in requestBody using its authenticate memberFunction if authentication fails it will throw BadCredentialsException so the above code wil be put in Try Catch block
Also we will need to create @Bean for AuthenticationManager in our spring security configurer class which will return super.authenticationManagerBean() for spring to know that we are using it in our code so it to its create bean for us .
And will also create object of userDetails class which will be needed as parameter while creating token from JWTutil class instance which will create and return JWT which will b3 returned by our API endpoint
8. Now in spring configurer class we will need to override configure method with httpSecurity instance as parameter.
So here we will allow the request coming for /authenticate URI endpoint to be permitted without spring securitys internal validation
9. So now we will need to intercept each request by creating a request filter for each request which will be validating token.
So we will create own filter class which will be extending springs web dependencies OncePerRequestFilter class and now we will need to override its DoFilterInternal method
Ao here in this method we will get token from HttpServeletRequest header and so on we will validate the user.
And now we'll addFilterBefore method of HttpSercurity class in spring security configuration class with the requestSercurity filter as parameter.
10 . So now whenever we will call authenticate API it will return JWT to us which a user should carry in localStorage/cookies and send it to each request in header for JWT Validation - with key as Authorization and Value as Bearer JWT.
-------------------------------------------------------------------------------------------------------------
https://www.youtube.com/watch?v=MU2e6-CC3Pc&list=PL0zysOflRCelmjxj-g4jLr3WKraSU_e8q&index=72&ab_channel=LearnCodeWithDurgesh
creating Spring security backend and front end from above video 72,73 and 74
-------------------------------------------------------------------------------------------------------------
https://medium.com/swlh/spring-boot-security-jwt-hello-world-example-b479e457664c
JWT util class for spring security
Basic Steps for spring security project
1. implement UserDetails (having methods like getAuthority()..etc) Interface from spring security for User .
2. JwtRequest [having username and password] for authenticating User
3.JwtResponce [having unique token for distinct user whenever he/she logins].
4.Implementation of UserDetailsService which spring security will internally use for calling UserDetails (basically the user) by passing username as parameter.
5.Creating spring security configuration class by Extending WebSecurityConfigurerAdapter class having configure methods with them.
6. Implement AuthenticationEntryPoint handles any exception occurred while authenticating user.
7. Implement OncePerRequestFilter Used for filtering and validating JWT token coming in header with each request for accessing resource/Url
8.Jwt Utility Class Having json web tokens utility methods which can be further used for genrating token or extracting details from token
9. Create an API class i.e the authenticate controller which will generate and authenticating token for the user coming from the Client.
Comments
Post a Comment