Dav*_*ury 9 token oauth-2.0 asp.net-mvc-5 asp.net-web-api2
以下场景:我有一个使用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";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4399 次 |
| 最近记录: |