Use Zuul and Spring Security for a global authentication via the popular JWT token.
The service to issue the JWT token.
- The client POST
{username,password}to/login. - This service will authenticate the username and password via
Spring Security, generate the token, and issue it to client.
Provide three simple services:
/admin/user/guest
The Zuul gateway:
- Define
Zuulroutes toauth-centerandbackend-service. - Verify
JWTtoken. - Define role-based auth via
Spring Security:/loginis public to all./backend/admincan only be accessed by roleADMIN./backend/usercan only be accessed by roleUSER./backend/guestis public to all.
mvn clean packagejava -jar auth-center/target/auth-center-1.0.0.jar
java -jar backend-service/target/backend-service-1.0.0.jar
java -jar api-gateway/target/api-gateway-1.0.0.jarcurl -i -H "Content-Type: application/json" -X POST -d '{"username":"shuaicj","password":"shuaicj"}' http://localhost:8080/loginYou will see the token in response header for user shuaicj. Note that the status code 401 will be returned if you provide incorrect username or password. And similarly, get token for user admin:
curl -i -H "Content-Type: application/json" -X POST -d '{"username":"admin","password":"admin"}' http://localhost:8080/loginThe user admin is defined with two roles: USER and ADMIN, while shuaicj is only a USER.
The general command to verify if the auth works is as follows:
curl -i -H "Authorization: Bearer token-you-got-in-step-3" http://localhost:8080/backend/useror without token:
curl -i http://localhost:8080/backend/userYou can change the token and the URL as need. To sum up, the following table represents all possible response status codes while sending requests to different URLs with different tokens:
| /backend/admin | /backend/user | /backend/guest | |
|---|---|---|---|
admin token (role USER ADMIN) |
200 | 200 | 200 |
shuaicj token (role USER) |
403 | 200 | 200 |
| no token | 401 | 401 | 200 |