简体   繁体   中英

Call a secure Rest api from spring boot

I have a spring boot application and i need to call a secure external api to retrieve data.

on below the steps I followed:

  1. I generate the token with the username and password

  2. I keep the token in a temporary variable

  3. I use it on each resttemplate call

    headers.add("Authorization", "Bearer " + token); 

My questions are:

  • What is the best way to keep the generated token and use it for each connected user?
  • Can we configure spring security to manage the call to the external api?

As I figured, you want proxy a secure-rest-api and response to your own users. But the secure-api needs authentication and you want to have a specific jwt per user. You have two approaches to implement:

1- Use an in-memory token storage like Redis, with persistence mode enabled to be reliable and scalable. Follow these steps: [for each user check if the token is already generated and stored in storage] -> [If yes fetch and assign it to header of restTemplate request] -> [If not fetch the token from secure-api and store it and move to restart from first step]

2- Previous solution is not the best practice because you should have in-memory storage and it will be your bottle neck. (you should cluster it and verticaly increase the resources). So the next solution is to store the tokens at client side for each user. you should follow these steps: [If your own user sent the token to your rest api, you should catch it, verify it, and forward to secure-api using restTemplate] -> [Otherwise it means that you havn't already sent the token to user, so you should fetch the token RESIGN it and respond to user]

The second solution is to forget about In-Memory db and it's IO/bound added letancy. But it adds a cpu-bound processs on your jwt tokens. Each user stores it's token in browser and you can use the token to identify your users instead of using sessions or something like that. So I highly recommend you to read about signing algorithms like sha(256,512,1024) or some other types of algs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM