Implement login using JWT in MSA project
I’m thinking about introducing React into the UI,
so I’m going to implement login with JWT instead of session
All requests pass through the ApiGateway, so
Authentication is handled in Api gateway
ApiGateway
to give a long story short…
Add a Token Authentication Filter to the gateway,
Apply filter to all requests except login requests
When login, issue a token and
All other requests must contain tokens
What is JWT?
Let me apply JWT in my PRJ
First, modify the UserService (MicroServices)
UserService
UserService/pom.xml<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency><dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency><!-- UsernamePasswordAuthenticationFilter -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency><dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency><dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
I’m going to make them Bean and use
And will make AuthenticationFilter in UserService
inherit UsernamePasswordAuthenticationFilter
make a Vo to use before creating AuthenticationFilter
Make changes to fit your project
Now create method to create token
Set the end time and key
This is the end of AuthenticationFilter
Service must be modified before apply Filter
extends UserDetailsService
Return after granting authority
And add AuthenticationFilter to all Request.
in /security/WebSecurity.java
IpAddress : Gateway IpAddress or other
Now run login
No need to build a controller
Because it’s provided by Spring Security
There’s only one left, Modifying the API Gateway
API Gateway
First, make the filter
And apply to requests
ApiGateway/pom.xml<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency><dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
Make a filter in Api Gateway
Verify that the token is a token issued by our Service
Must use the same key
And create error handling
If make a this function, it’s done
Removes the token name
Declare where to apply this filter in .yml
Do not apply filters to login
Add filter to remaining requests (GET, POST)
It’s really really the end…
Now do it
can see that the filter is applied well
I’m going to login and get the token
Login is not filtered, so it can run without token
Retry the previous request, including the token