在 Angular / Golang 项目中使用 JWT

huangapple go评论75阅读模式
英文:

Using JWT in a Angular / Golang project

问题

我遇到了一个问题,无法正确使用JWT来完成我的项目。

这是情况:

我有一个网站,人们可以通过Twitch登录,这会给我一个OAuth令牌、他们的用户名以及根据我的请求提供的其他信息。
(这是身份验证过程的样子:https://github.com/justintv/Twitch-API/blob/master/authentication.md)

在我的数据库中,我有一些具有访问级别的用户名。例如,级别500表示他们可以在我的网站上看到管理员仪表板,或者他们可以从Angular发送POST请求来更改数据。

我的Angular应用程序显然无法访问数据库。我只希望通过我提供的Go Web服务器的API进行通信。

我想知道的是,如何确保试图发送安全的POST或GET请求的用户实际上是他所说的用户,并且具有执行所做命令的权限。

英文:

I am having issues figuring out how to use JWT correctly for my project.

This is the situation:

I have a website where people can login via a twitch which gives me an oauth token, their username and more stuff depending on what I request.
(this is what the authentication process looks like https://github.com/justintv/Twitch-API/blob/master/authentication.md )

In my database I have a few usernames that have an access level. For example level 500 meaning they can see the admin dashboard on my website or they can send POST requests from angular to change data.

My angular app has no access to the database obviously. I only want communication via an API provided by my go webserver.

What I am wondering is how do I make sure that the user who is trying to send a secure POST or GET is actually the user he says he is and has permission to execute the command he is doing.

答案1

得分: 2

JWT由3个部分组成:头部(用于存储加密算法等“元数据”)、声明(存储在令牌中的实际数据)和HMAC(用于验证上述两个部分是否被篡改)。

在您的情况下,当用户登录时,您应该收到OAuth令牌、他们的用户名等信息。然后,您可以使用用户名获取关联的用户级别,并将所有内容存储在您自己的JWT的声明中,然后将其发送回用户。在后续的请求中,您只需检查令牌是否有效(不要忘记给它们一个较短的生存时间),然后您可以确信发出请求的用户是它所声称的用户(这是一个记忆技巧的双关语)。

英文:

A JWT is composed of 3 parts: the header (for "metadata" like the encryption algorithm used, etc), the claimes (which are the actual data stored in the token), and an HMAC (used to verify that the two parts above aren't tampered with).

In your case, when you user login, you should receive the oauth token, their username, etc. You can then use the username to get the associated user level, and stow everything in the claims of your own JWT that you will send back to the user. In subsequent requests, you just have to check that the token is valid (don't forget to give them a short ttl), and then you are sure that the user doing the request is the one it claims it is (mnemotechnic pun intended).

huangapple
  • 本文由 发表于 2016年5月1日 04:28:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/36959901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定