[英]MVC 5 Identity 2 and Web API 2 authorization and call api using bearer token
以下場景:我有一個使用Identity 2.0和Web API 2的MVC 5 Web應用程序。
一旦用戶在MVC 5中進行身份驗證,他就應該能夠調用WEB API端點,讓我們使用承載令牌來調用它: api/getmydetails
。
我需要知道的是如何在MVC 5中為特定用戶發出令牌?
我確實解決了這個問題
這是一些截圖,我也將發布演示解決方案。
只是一個簡單的mvc 5與web api支持應用程序。
您必須注冊和登錄后的主要事項。 出於演示目的,我注冊為admin@domain.com
,密碼為Password123*
。
如果您尚未登錄,則無法獲得令牌。 但是一旦你登錄你就會看到令牌:
獲得令牌后啟動Fiddler。
向api/service
端點發出get請求。 您將獲得401 Unauthorized
以下是請求的說明:
現在轉到Web應用程序,第1階段並復制生成的令牌並添加以下授權標頭: Authorization: Bearer token_here
請注意Bearer
關鍵字應該在令牌之前,如下圖所示。 立即提出新請求:
現在你將獲得200 Ok的回復。 響應實際上是user id
和user name
,顯示您被授權為該特定用戶:
您可以從這里下載工作解決方案:
http://www.filedropper.com/bearertoken
如果由於某種原因鏈接不起作用,請告訴我,我會將其發送給您。
PS
當然在你的應用程序中,你可以使用生成的bearer令牌對web api端點進行ajax調用並獲取數據,我沒有這樣做,但應該很容易......
PS 2:生成令牌:
private string GetToken(ApplicationUser userIdentity)
{
if (userIdentity == null)
{
return "no token";
}
if (userIdentity != null)
{
ClaimsIdentity identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, userIdentity.UserName));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
DateTime currentUtc = DateTime.UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
return AccessToken;
}
return "no token";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.