Asp.net-Web-Api

在 Web Api / Owin 架構中,對“/token”的請求在哪里處理?

  • April 22, 2014

我正在嘗試了解 Asp.net Web Api 個人帳戶身份驗證和授權。我在網上看到了幾個教程,包括這個。簡而言之,當使用者代理提供使用者名和密碼時,API 會發出一個令牌,客戶端將在隨後呼叫 API 時使用該令牌來辨識自己。使用者代理通過發出請求來接收令牌,通常發送到:<http://example.com/Token>。路徑似乎是在 Startup 類中設置的,如下所示:

TokenEndpointPath = new PathString("/Token")

我的問題是,我找不到任何與該路徑匹配的控制器方法。這是如何運作的?

當您在 ASP.NET 中創建具有個人身份驗證的新項目時,將使用 OAuth 提供程序創建解決方案以處理身份驗證請求。

如果您查看您的解決方案,您應該會看到一個帶有 ApplicationOAuthProvider 類的 Providers 文件夾。

此類實現了在您的網站中驗證您的成員的所有邏輯。配置在啟動時設置,允許您通過 OAuthOption 自定義 url 端點。

OAuthOptions = new OAuthAuthorizationServerOptions
{
   TokenEndpointPath = new PathString("/Token"),
   Provider = new ApplicationOAuthProvider(PublicClientId),
   AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
   AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
   AllowInsecureHttp = true
};

TokenEndPoint Path 屬性定義了將觸發 GrandResourceOwnerCredentials 的 GrantResourceOwnerCredentials 方法的 url。

如果你使用 fiddler 進行身份驗證並使用這種 body

grant_type=password&username=testUserName&password=TestPassword

您應該傳入以下方法:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
   {
       var userManager = context.OwinContext.GetUserManager&lt;ApplicationUserManager&gt;();

       ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

       if (user == null)
       {
           context.SetError("invalid_grant", "The user name or password is incorrect.");
           return;
       }

       ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
          OAuthDefaults.AuthenticationType);
       ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
           CookieAuthenticationDefaults.AuthenticationType);

       AuthenticationProperties properties = CreateProperties(user.UserName);
       AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
       context.Validated(ticket);
       context.Request.Context.Authentication.SignIn(cookiesIdentity);
   }

其中 context.UserName 和 context.Password 使用請求中使用的數據進行設置。確認身份後(此處使用實體框架和數據庫中的一對使用者名、密碼),將持有者令牌發送給呼叫者。然後可以使用此承載令牌對其他呼叫進行身份驗證。

問候。

引用自:https://stackoverflow.com/questions/23215672