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

如何为集成Vue.js的.NET Core MVC Web应用选择Identity Server授权流程?

实现Identity Server与带Vue.js的.NET Core MVC集成的服务端授权校验

我刚好折腾过类似的场景,给你梳理一套完整的实现方案,确保未认证用户完全碰不到你的客户端视图,全程靠服务端做授权校验,稳得很。

第一步:给.NET Core MVC项目配置Identity Server认证

首先得在Program.cs里把Identity Server的认证服务加上,顺序一定要注意,中间件的先后直接影响校验逻辑是否生效:

var builder = WebApplication.CreateBuilder(args);

// 注册MVC服务,顺便加NewtonsoftJson方便后续传数据给Vue
builder.Services.AddControllersWithViews()
    .AddNewtonsoftJson();

// 配置认证方案:Cookie存本地会话,OIDC对接Identity Server
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
    options.Authority = "https://your-identity-server-address"; // 替换成你的Identity Server地址
    options.ClientId = "mvc-vue-client"; // 对应你在Identity Server注册的客户端ID
    options.ClientSecret = "your-client-secret-here"; // 客户端密钥,要和Identity Server里的一致
    options.ResponseType = "code"; // 用授权码流,更安全
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.SaveTokens = true; // 把令牌存在Cookie里
    options.GetClaimsFromUserInfoEndpoint = true; // 从用户信息端点拉取额外信息
});

// 启用授权服务
builder.Services.AddAuthorization();

var app = builder.Build();

// 中间件顺序不能乱:HTTPS重定向 → 静态文件 → 路由 → 认证 → 授权 → MVC路由
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

// 先做认证,再做授权
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

第二步:服务端校验保护首页视图

给你的Home控制器加上[Authorize]特性,这样用户访问首页时,服务端会先检查认证状态:未认证的话直接重定向到Identity Server的登录页,认证通过才返回首页视图(也就是Vue的入口)。

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace YourMvcApp.Controllers;

[Authorize] // 整个控制器都受保护,所有动作都需要认证
public class HomeController : Controller
{
    public IActionResult Index()
    {
        // 可选:把用户信息传递给Vue,比如通过ViewData序列化到页面
        var userClaims = User.Claims.ToDictionary(c => c.Type, c => c.Value);
        ViewData["UserInfo"] = userClaims;
        return View();
    }
}

然后在Index.cshtml里加载Vue应用,顺便把服务端的用户信息传给前端:

@{
    ViewData["Title"] = "Home Page";
}

<!-- Vue应用的挂载点 -->
<div id="app"></div>

<script>
    // 把服务端的用户信息注入到全局,供Vue使用
    window.serverUserInfo = @Html.Raw(Json.Serialize(ViewData["UserInfo"]));
</script>
<!-- 引入你的Vue打包后的JS文件 -->
<script src="~/js/app.js"></script>

第三步:可选但推荐:保护静态资源

如果不想让未认证用户直接下载Vue的JS/CSS资源,可以给静态文件加上授权校验:

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        // 检查用户是否认证,未认证就返回403
        if (!ctx.Context.User.Identity.IsAuthenticated)
        {
            ctx.Context.Response.StatusCode = StatusCodes.Status403Forbidden;
            ctx.Context.Response.ContentLength = 0;
            ctx.Context.Response.Body = Stream.Null;
        }
    }
});

第四步:Identity Server端的客户端配置

最后要确保在Identity Server里正确注册你的MVC客户端,配置授权码流、重定向URI这些关键信息:

public static IEnumerable<Client> Clients =>
    new List<Client>
    {
        new Client
        {
            ClientId = "mvc-vue-client",
            ClientName = "MVC + Vue 客户端",
            ClientSecrets = { new Secret("your-client-secret-here".Sha256()) },

            AllowedGrantTypes = GrantTypes.Code,
            RequirePkce = true,
            RequireClientSecret = true,

            // 重定向URI要和MVC项目的OIDC回调路径完全一致
            RedirectUris = { "https://your-mvc-app-address/signin-oidc" },
            // 退出登录后的回调URI
            PostLogoutRedirectUris = { "https://your-mvc-app-address/signout-callback-oidc" },

            AllowedScopes = { "openid", "profile" },
            AllowOfflineAccess = true,
            AccessTokenLifetime = 3600 // 按需调整令牌有效期
        }
    };

几个关键注意点

  • 中间件顺序:UseAuthentication()必须在UseAuthorization()之前,否则授权校验会直接跳过认证步骤,完全失效。
  • 重定向URI匹配:Identity Server里配置的重定向URI必须和MVC项目的回调路径完全一致,包括HTTP/HTTPS协议,不然会被Identity Server拒绝。
  • 前端路由双重校验:虽然服务端已经做了入口保护,但Vue内部的路由也建议加上认证判断(比如读取window.serverUserInfo,不存在就跳转到服务端登录页),双重保险更稳妥。

这样配置完之后,用户访问你的网站时,服务端会先做认证校验:已登录就返回首页加载Vue;未登录直接跳Identity Server登录页,登录成功后自动跳回首页,完全确保未认证用户碰不到你的客户端视图。

内容的提问来源于stack exchange,提问作者Anonymous Creator

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:08:58