将webApi控制器的令牌身份验证添加到现有的asp.net MVC 5应用程序

时间:2018-07-02 19:30:26

标签: c# asp.net-mvc authentication asp.net-web-api

我目前已将Web API控制器添加到现有的MVC 5项目(不使用.net核心)中,并且能够从已设置的控制器中成功创建并获取数据。 API的目的是在它和使用MVC项目使用的相同数据源的移动应用程序之间传递数据(我还将通过API调用项目中的现有方法,因此我希望API存在于MVC中项目)。我现在正在寻找一种向API添加令牌身份验证的方法,因为我只希望允许移动应用程序中的登录用户访问API。我该如何实现?

1 个答案:

答案 0 :(得分:2)

最简单的解决方案应该是使用IdentityServer 3套件中的Token Validation Middleware
只需添加nuget package并按照文档配置您的应用程序即可:

public class Startup
{
  public void Configuration(IAppBuilder app)
  {
    // turn off any default mapping on the JWT handler
    JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

    app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = "https://localhost:44333/core",
            RequiredScopes = new[] { "api1" }
        });

    app.UseWebApi(WebApiConfig.Register());
  }
}

仅在
app.UseIdentityServerBearerTokenAuthentication()app.UseCookieAuthentication()
之前设置
app.UseOpenIdConnectAuthentication()
并调用
{{ 1}}在Global.asax中

,这种方法允许在一个MVC应用程序中结合基于令牌和基于cookie的身份验证。
今天的唯一问题是IdentityServer 3系列工具被冻结并支持System.IdentityModel 4和仅限OWIN 3,所以

更新: ASP.NET 4.6+的首选解决方案成为IdentityServer3.Contrib.AccessTokenValidation -一种分支,根据最近的框架更改进行了重构。