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

最佳答案

最简单的解决方案应该是使用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()并在Global中调用GlobalConfiguration.Configure(WebApiConfig.Register)是可以的.asaxSuch方法允许在一个MVC应用程序中结合基于 token 和基于cookie的身份验证。今天的唯一问题是IdentityServer 3系列工具被冻结并支持系统。仅限IdentityModel 4和OWIN 3,因此

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

07-28 01:44
查看更多