0

バックグラウンド

Visual Studio 2013、ASP ネット 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);

しかし、クライアントでここに指定されたこのトークンを使用して、いくつかの「承認」サービスを使用しようとすると。未承認の例外が発生しています。ここで指定されたトークンが有効であることを確認するにはどうすればよいですか。

そうでない場合、どうすれば有効なものを生成できますか?

4

1 に答える 1

0

カスタム セキュリティ フローを使用する場合は、AuthorizeAttributte を使用できると思います。お気に入り:

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 に答える