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

杀马特。学长 韩版系。学妹 提交于 2019-12-06 00:00:29

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?

Common practice is on success, the response from the service has the status code 200 OK in the response header, and token related data in the response body

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?

Using the access token to make authenticated requests

Now that you have a token, you can make authenticated requests to the API. This is done by either setting the HTTP Authorization header or query string in the request depending on how the server is configured.

in a header

Authorization: Bearer NgCXRK...MzYjw    

as a parameter

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 — Open Web Interface for .NET 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!