【问题标题】:Validate ASP NET API Token?验证 ASP NET API 令牌?
【发布时间】:2014-06-14 17:39:34
【问题描述】:

背景

Visual Studio 2013,ASP NET WEB API 2

问题

我正在使用 .NET 的“标准”成员资格提供程序,但我需要自定义登录方法。所以我添加了一个新方法,然后我使用这个来生成令牌:

// Sign-in the user using the OWIN flow
                var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                // This is very important as it will be used to populate the current user id 
                // that is retrieved with the User.Identity.GetUserId() method inside an API Controller
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id, null, "LOCAL_AUTHORITY"));
                AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                ticket.Properties.IssuedUtc = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(new TimeSpan(14, 0, 0, 0));
                accesstoken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
                Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accesstoken);
                Authentication.SignIn(identity);

但是当我尝试使用在我的客户端中给出的这个令牌来使用一些“授权”服务时。我得到了一个未经授权的例外。如何验证此处给出的 Token 是否有效。

如果不是,我怎样才能生成一个有效的?

【问题讨论】:

    标签: c# .net asp.net-membership asp.net-authorization


    【解决方案1】:

    如果您打算使用自定义安全流程,我认为您可以使用 AuthorizeAttribute。 喜欢:

    public class ApiAuthentication : AuthorizeAttribute
    {
      protected override bool IsAuthorized(HttpActionContext context)
      {
           //Your Authentication Logic Here for example:
           //context.Request.Headers.TryGetValues("Authorization", out buffers);
      }
    }
    
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
          //this method is for handling Unauthorized Request
    }
    

    然后你可以装饰你的控制器的方法

    [ApiAuthentication]        
    [Queryable]
    public IEnumerable<ProductIndex> GetProductIndex()
    {
        // Return Data
    }
    

    *干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 2017-02-17
      • 2019-02-22
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多