0

背景

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 是否有效。

如果不是,我该如何生成一个有效的?

4

1 回答 1

0

如果您打算使用自定义安全流程,我认为您可以使用 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
}

*干杯

于 2014-04-29T02:35:41.610 回答