Skip to main content
 首页 » 编程设计

c#之如何使用 mvc 4 向我的 api 添加 token

2024年02月20日12zengkefu

我如何添加安全 token 来访问 API,以便不是每个人都能获得它。我希望我的网址格式为:api.example.com/*key*/person?id=5 当我发送此请求时,如果 key 有效,它将返回如果无效它将返回无效登录。我正在使用 mvc 4 api 和 C# 来制作这个,链接或其他东西会很棒。

请您参考如下方法:

您最喜欢的关键词是您需要创建并添加自定义 ActionFilterAttribute。

在谷歌上快速搜索发现了这篇博客文章,其中讨论了如何做到这一点 exact thing (以及其他一些过滤器)。

以防万一有一些链接失效这里是要点(博客文章的摘录):

  1. 提出一些生成/验证 API token 的方案

  2. 创建您的属性,在属性中使用第 1 步中的验证

  3. 将属性添加到全局配置

代码

public class TokenValidationAttribute : ActionFilterAttribute 
{ 
  public override void OnActionExecuting(HttpActionContext actionContext) 
  { 
   string token; 
 
   try 
   { 
    token = actionContext.Request.Headers.GetValues("Authorization-Token").First(); 
   } 
   catch (Exception) 
   { 
    actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest) 
    { 
     Content = new StringContent("Missing Authorization-Token") 
    }; 
    return; 
   } 
 
   try 
   { 
    //This part is where you verify the incoming token 
    AuthorizedUserRepository.GetUsers().First(x => x.Name == RSAClass.Decrypt(token)); 
    base.OnActionExecuting(actionContext); 
   } 
   catch (Exception) 
   { 
    actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) 
    { 
     Content = new StringContent("Unauthorized User") 
    }; 
    return; 
   } 
    } 
  } 
} 

要使这些操作过滤器成为全局的,Global.asax Application_Start() 中的以下代码将起到作用:

var config = GlobalConfiguration.Configuration; 
config.Filters.Add(new TokenValidationAttribute());