Chr*_*vez 5 c# authentication asp.net-mvc asp.net-web-api
我目前有一个Web API控制器添加到现有的MVC 5项目(不使用.net核心),我能够成功地从我设置的控制器创建和获取数据.API的目的是在它和使用MVC项目使用的相同数据源的移动应用程序之间传递数据(我还将从API调用项目中的现有方法,因此我更希望MVC中存在API)项目).我现在正在寻找一种向API添加令牌认证的方法,因为我只希望允许移动应用程序中的登录用户访问API.我怎样才能做到这一点?
最简单的解决方案应该是使用IdentityServer 3 套件中的令牌验证中间件。
只需添加nuget 包并按照文档配置您的应用程序:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
可以app.UseIdentityServerBearerTokenAuthentication()
仅在 Global.asax 中的和
之前进行设置。这种方法允许在一个 MVC 应用程序中结合令牌和基于 cookie 的身份验证。今天唯一的问题是 IdentityServer 3 系列工具已冻结并且仅支持 System.IdentityModel 4 和 OWIN 3,因此app.UseCookieAuthentication()
app.UseOpenIdConnectAuthentication()
GlobalConfiguration.Configure(WebApiConfig.Register)
更新: ASP.NET 4.6+ 的首选解决方案变为IdentityServer3.Contrib.AccessTokenValidation —— 一个分支,根据最近的框架更改进行重构。