gpt4 book ai didi

c# - 在 Asp.net Web 服务中集成 JWT

转载 作者:行者123 更新时间:2023-11-30 22:08:38 26 4
gpt4 key购买 nike

谁能告诉我如何将 JWT 集成到默认的 Web API 项目中。

Here is the library

他们只是解释了如何使用 NuGet 安装库以及如何生成 token 。但现在如何将它与基于身份验证的系统集成?

到目前为止我的实现:

public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.Filters.Add(new **AuthFilterAttribute()**);
}
}


public class TokenAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
// In auth web method you should implement functionality of authentication
// so that client app could be able to get token
if (actionContext.Request.RequestUri.AbsolutePath.Contains("api/auth"))
{
return;
}

// Receive token from the client. Here is the example when token is in header:
var token = **actionContext.Request.Headers["Token"];**

// Put your secret key into the configuration
var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";

try
{
string jsonPayload = JWT.JsonWebToken.Decode(token, secretKey);
}
catch (JWT.SignatureVerificationException)
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
}
}

最佳答案

实现 TokenAuthenticationAttribute 并全局注册:

Global.asax 注册:

GlobalConfiguration.Configuration.Filters.Add(new TokenAuthenticationAttribute());

TokenAuthenticationAttribute:

public class TokenAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
// In auth web method you should implement functionality of authentication
// so that client app could be able to get token
if (actionContext.Request.RequestUri.AbsolutePath.Contains("api/auth"))
{
return;
}

// Receive token from the client. Here is the example when token is in header:
var token = actionContext.Request.Headers["Token"];

// Put your secret key into the configuration
var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";

try
{
string jsonPayload = JWT.JsonWebToken.Decode(token, secretKey);
}
catch (JWT.SignatureVerificationException)
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
}
}

关于c# - 在 Asp.net Web 服务中集成 JWT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22172039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com