如何在 C# WEB API 中 return 一个 JSON Web 令牌?

How to return a JSON Web Token in a C# WEB API?

我正在尝试使用 JWT 来保护用 C# 编写的 WEB API,但我对一些事情感到困惑。根据我的理解,流程应该是这样的:

  1. 客户端从某些客户端应用程序(Angular、.NET、移动等)向 Web API 提供 username/password
  2. Web API 验证 username/password 是否正确,然后生成一个 JWT (JSON Web Token),其中包含用户的角色、信息、到期日期和其他相关信息信息。
  3. JWT 被发送回客户端应用程序。
  4. 客户端应用程序挂在 JWT 上并将其与未来的请求一起发送。

假设以上内容正确(如果不正确请告诉我),我无法理解以下内容。

  1. 一旦 Web API 验证了 username/password 并创建了 JWT,JWT 如何传回?我是否以某种方式将其添加到 HttpResponseMessage object?我似乎无法找到明确的答案。
  2. 客户端应用程序应如何将 JWT 传回?这是在 JSON 数据中,附加到 URL,添加到 headers?
  3. 我看到很多参考 OWIN 和 OAUTH 的教程。这些是什么,为什么我需要它们?我在 WEB API 使用的数据库中持有用户凭证和角色。

Once the Web API has validated the username/password and created the JWT, how does the JWT get passed back? Do I somehow add it to an HttpResponseMessage object?

通常的做法是成功,来自服务的响应在响应 header 中有状态代码 200 OK,在响应 body[=22= 中有令牌相关数据]

200 OK
Content-Type: application/json;charset=UTF-8

{
    "access_token": "NgCXRK...MzYjw",
    "token_type": "Bearer",
    "expires_at": 1372700873,
    "refresh_token": "NgAagA...Um_SHo"
}

How should the client application pass the JWT back? Is this in the JSON data, appended to the URL, added to headers?

使用访问令牌发出经过身份验证的请求

现在您有了一个令牌,您可以向 API 发出经过身份验证的请求。这是通过在请求中设置 HTTP Authorization header 或查询字符串来完成的,具体取决于服务器的配置方式。

在一个header

Authorization: Bearer NgCXRK...MzYjw    

作为参数

GET http://localhost:35979/v2/endpoint?access_token=NgCXRK...MzYjw

I see plenty of tutorials referencing OWIN and OAUTH. What are these and why do I need them?

OWIN — .NET 的开放式 Web 界面 http://owin.org/

OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.

OWIN OAuth 2.0 Authorization Server

The OAuth 2.0 framework enables a third-party app to obtain limited access to an HTTP service. Instead of using the resource owner’s credentials to access a protected resource, the client obtains an access token (which is a string denoting a specific scope, lifetime, and other access attributes). Access tokens are issued to third-party clients by an authorization server with the approval of the resource owner.