You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC 5项目新增Token Based Authentication功能的相关教程咨询

MVC5 现有个人身份验证体系新增Token认证实现流程

前置依赖检查

  • 首先确保项目已安装对应NuGet包:Microsoft.Owin.Host.SystemWeb、Microsoft.Owin.Security.OAuth、Microsoft.AspNet.WebApi.Owin,未安装可直接通过NuGet包管理器搜索安装
  • 原有基于ASP.NET Identity的个人身份验证逻辑无需修改,Token认证与原有表单Cookie认证可完全共存,不影响现有浏览器端登录访问流程

步骤1:配置OWIN OAuth授权中间件

打开项目App_Start文件夹下的Startup.Auth.cs文件,在原有认证配置基础上新增OAuth Token配置:

public void ConfigureAuth(IAppBuilder app)
{
    // 原有表单Cookie认证配置,完整保留即可
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
        }
    });

    // 新增OAuth Bearer Token配置
    app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
    {
        // Token获取接口路径,第三方应用调用该地址获取认证Token
        TokenEndpointPath = new PathString("/api/token"),
        // 生产环境必须设置为false,仅允许HTTPS请求访问Token接口
        AllowInsecureHttp = false,
        // Token有效期可根据业务需求自行调整
        AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
        Provider = new OAuthAuthorizationServerProvider
        {
            // 账号密码校验逻辑,复用现有ASP.NET Identity用户体系
            OnGrantResourceOwnerCredentials = async context =>
            {
                var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
                ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "用户名或密码错误");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = CreateProperties(user.UserName);
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            },
            // 无需客户端密钥校验的场景可直接返回验证通过
            OnValidateClientAuthentication = async context =>
            {
                context.Validated();
            }
        }
    });
}

// 新增辅助方法,用于返回Token附带的用户信息
public static AuthenticationProperties CreateProperties(string userName)
{
    IDictionary<string, string> data = new Dictionary<string, string>
    {
        { "userName", userName }
    };
    return new AuthenticationProperties(data);
}

步骤2:配置Web API认证过滤器

打开App_Start文件夹下的WebApiConfig.cs文件,新增双重认证配置,让API接口同时支持Cookie认证和Token认证:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // 新增双重认证过滤器,原有`[Authorize]`特性无需修改即可适配两种认证方式
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie));

        // 原有Web API路由、格式化等配置保留不动
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

功能验证方法

  • 获取Token:第三方应用向/api/token发送POST请求,请求体格式为x-www-form-urlencoded,携带参数grant_type=password、username=用户账号、password=用户密码,请求成功后返回报文中的access_token字段即为可用认证凭证
  • 调用API接口:第三方请求时在请求头添加Authorization: Bearer 实际获取的access_token即可通过身份验证,原有加了[Authorize]特性的接口不需要做任何适配修改
  • 原有基于角色、声明的权限校验逻辑完全复用,不需要额外调整

可选优化项

  • 若需要支持Token刷新,可额外添加refresh_token存储与校验逻辑,减少用户重复提交账号密码的频率
  • 若需要限制第三方应用访问权限,可在OnValidateClientAuthentication方法中添加客户端ID、密钥校验逻辑,仅给授权过的第三方应用发放Token
  • 生产环境必须关闭AllowInsecureHttp配置,强制所有Token相关请求走HTTPS,避免Token泄露

提示:整个配置过程不会改动原有浏览器端的登录访问逻辑,两套认证体系完全独立共存。

内容的提问来源于stack exchange,提问作者Systems Development

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:15:05