管理身份验证令牌的最佳做法 [英] Best practices for managing auth token

查看:305
本文介绍了管理身份验证令牌的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HttpCLient在Java中编写REST客户端,我访问的REST API需要每个REST操作的身份验证令牌。此令牌有效期为24小时。

I am writing a REST client in Java using the HttpCLient , the REST API that I access needs an auth token for every REST action. This token is valid for 24 hours.

我现在处理此问题的方法是调用 getAuth() 每次我需要进行REST调用的方法,这似乎是auth服务器上的开销。

The way I am handling this now is calling a "getAuth()" method everytime I need to make a REST call which seems like an overhead on the auth server.

如何方便地存储此身份验证令牌并管理其生命周期?
是否有任何记录的最佳做法?

How can I conveniently store this auth token and manage its life cycle? Are there any documented best practices?

我想到了以下解决方案

public class MySession {
    String user;
    String pass;
    public MySession(String user, String pass) {
        this.user = user;
        this.pass = pass;
    }

    public getAuth() {
        //user user, pass to get auth token 
    }
}

然后将sessions对象传递给任何需要该令牌的类。如果令牌已过期,只需再次调用此方法

and then pass the sessions object to any class that nees the token. If the token is expired, just call this method again

推荐答案

为简洁起见,我假设您正在调用一个端点无法改变。您应该如何实现将在很大程度上取决于令牌是基于应用还是基于用户(共享应用实例上的所有用户一个令牌或每个用户一个令牌)。

For brevity I'll assuming you're calling an endpoint that you can't change. How you should implement will heavily depend on whether the token is app or user based (one token for all users on a shared app instance or one token per user).

如果它是整个应用程序的一个身份验证令牌:

If it's one auth token for the entire app:


  • 将其与生存时间戳一起存储在内存中(或者捕获令牌)过期错误,请求新令牌并重试原始请求),如果不存在/已过期则刷新

  • 如果您担心应用程序后重新请求API令牌restart也将它存储在数据库中并在启动时加载(如果存在)

如果每个用户只有一个令牌:

If it's one token per user:


  • 将它存储在您的用户会话中,这正是会话所用的内容,如果您正在为用户进行授权,那么他们将会有一个会话并且已经开销了

  • 如果您不想每次登录时都重新请求令牌,请将当前令牌存储在数据库中并加载他们登录时的会话

这篇关于管理身份验证令牌的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆