I have a Rails app and I'm trying to connect to an API.
I've been able to ping the API and send form data and everything comes back OK. The question I have is the API requires you to send a JWT authentication token with your request. So I was making this additional authentication request to get the JWT and then sending that JWT with the other API calls I was making.
The API recommends saving the initial JWT so I don't have to make the additional authentication request for the JWT. They recommend saving it for a certain amount of time and refreshing and getting a new JWT after that time. The token will be valid for 25 hours so they recommend getting a new token after 24 hours to not interrupt any services when retrieving the new JWT.
Where would I store this token? I was thinking in a session or caching it maybe? I feel like there may be security concerns with storing it in a session?
Just looking for inputs on best practices and where one would store a JWT in their App. Also do not bother telling me my question to too general or SO isn't the place to ask for opinions. I'm doing it. Thug life.
according to auth0
you store your tokens in local storage/session storage or a cookie, there are different considerations in each approach, but generally, all front-end application use local or session storage. for more info auth0
you can change/update the local JWT token to increase your security of-course, but I think it should be handled in the application(front-end) layer. but the JWT token security should be handled more in the API server
Here is a solution that a friend came up with. I prefer it much more. Using the Rails cache. It seems to work for me so far. So thought I'd post it for future generations. Tweak it as you see fit for your own App. I had to slightly tweak it but the essence is the same.
def self.fetch_from_api(attributes)
# use with_token_refresh method here.
# It will fail if the token is expired, delete the cache, then re-fetch the token.
with_token_refresh do
url = build_url(:fetch, attributes[:endpoint], [attributes[:name_id]])
#call fetch_jwt method and put it in the headers or wherever
headers = attributes.merge(jwt: fetch_jwt)
response = execute_request(url, headers(attributes))
JSON.parse(response)
end
end
def self.fetch_jwt
# will write if nothing cached, or cache expired, read if something cached
Rails.cache.fetch('jwt' , expires_in: 24.hours) do
url = 'test.com'
headers = { secret: 'stuff' }
body = 'body'
resp = RestClient.post url, body, headers
JSON.parse(resp)['access_token']
end
end
def self.with_token_refresh
yield
rescue StandardError
# delete jwt, then yield to re-fetch
Rails.cache.delete('jwt')
yield
end
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.