[英]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.