首页 文章

MVC 5 Identity 2和Web API 2授权以及使用承载令牌的呼叫api

提问于
浏览
9

以下场景:我有一个使用Identity 2.0和Web API 2的MVC 5 Web应用程序 .

一旦用户在MVC 5中进行身份验证,他应该能够调用WEB API endpoints ,让我们使用承载令牌调用它: api/getmydetails .

我需要知道的是如何在MVC 5中为特定用户发出令牌?

1 回答

  • 7

    我确实解决了这个问题

    这是一些截图,我也将发布演示解决方案 .

    只是一个简单的mvc 5与web api支持应用程序 .

    您必须注册和登录后的主要事项 . 出于演示目的,我注册为 admin@domain.com ,密码为 Password123* .

    如果您尚未登录,则无法获得令牌 . 但是一旦你登录你就会看到令牌:

    enter image description here

    获得令牌后启动Fiddler .

    api/service endpoints 发出get请求 . 您将获得401 Unauthorized

    enter image description here

    以下是请求的说明:

    enter image description here

    现在转到Web应用程序,第1阶段并复制生成的令牌并添加以下授权标头: Authorization: Bearer token_here 请注意 Bearer 关键字应该在令牌之前,如下图所示 . 立即提出新请求:

    enter image description here

    现在你将获得200 Ok的回复 . 响应实际上是 user iduser name ,显示您被授权为该特定用户:

    enter image description here

    您可以从这里下载工作解决方案:

    http://www.filedropper.com/bearertoken

    如果由于某种原因链接不起作用,请告诉我,我会将其发送给您 .

    附:

    当然在你的应用程序中,你可以使用生成的bearer令牌对web api endpoints 进行ajax调用并获取数据,我没有这样做但应该很容易...

    附: 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";
        }
    

相关问题