简体   繁体   English

如何使用 go-guardian JWT 策略主动注销用户?

[英]How to actively logoff a user with go-guardian JWT strategy?

I'm using go-guardian with the JWT "basic-bearer" strategy for authentication in my project and it works really nice.我在我的项目中使用带有 JWT“基本承载”策略的 go-guardian 进行身份验证,效果非常好。 When the client has no token, he logs in with his credentials and receives a JWT, which he can then use for further requests like this one:当客户端没有令牌时,他使用他的凭据登录并收到 JWT,然后他可以将其用于像这样的进一步请求:

                $.ajax({
                    headers: {
                        'Authorization': 'Bearer ' + token
                    },
                    url: '/api/archive',
                    type: "post",
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify(searchData),
                    dataType: 'json',
                    success: onDataReceived,
                    error: onError
                });

However, I wonder how to do an active logoff on the server side when the client hits the /auth/logoff route, for example?但是,我想知道当客户端点击/auth/logoff路由时如何在服务器端进行主动注销? Sure, the client can simply delete the token, but then the server would still accept it.当然,客户端可以简单地删除令牌,但服务器仍然会接受它。 How can I actively invalidate or remove a token on the server side, so that I can safely say that the client has to reauthenticate?如何在服务器端主动使令牌无效或删除,以便我可以安全地说客户端必须重新验证?

You can keep a separate table user_session where the session also includes the token of the user.您可以保留一个单独的表user_session ,其中 session 还包括用户的令牌。 When an endpoint is hit you check the signature of the token and also if that token is in the database.当端点被命中时,您检查令牌的签名以及该令牌是否在数据库中。

You also need to store the token when users are logged in, and remove this token when users are logged out.您还需要在用户登录时存储令牌,并在用户注销时删除此令牌。

The reason you need multiple sessions per user is because users might log in from separate devices using multiple tokens.每个用户需要多个会话的原因是因为用户可能使用多个令牌从不同的设备登录。 To logoff a user you can delete that particular session from user_session or to logoff from all devices you can remove all sessions of that user.要注销用户,您可以从 user_session 中删除该特定user_session或从所有设备注销,您可以删除该用户的所有会话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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