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

如何在首次加载前通过授权服务器保护Angular SPA(.NET Core 2.1)

Hey Daniel, let's figure out how to get your .NET Core 2.1 Angular SPA to automatically redirect to your auth server the second someone loads the app—since the official docs skip over SPA-specific protection, I'll walk you through the exact steps to make this work.

1. Configure Backend Authentication & Middleware

First, we need to set up the .NET Core backend to intercept all SPA requests and trigger authentication if the user isn't logged in.

Update Startup.cs - ConfigureServices

Add authentication services (I'll use OpenID Connect as an example, since it's common for OAuth2/OIDC auth servers like IdentityServer4):

public void ConfigureServices(IServiceCollection services)
{
    // Keep your existing services (like MVC, SPA static files)
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });

    // Add authentication & authorization
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        // Replace with your auth server details
        options.Authority = "https://your-auth-server-url";
        options.ClientId = "your-spa-client-id";
        options.ClientSecret = "your-client-secret"; // Omit if using public client flow
        options.ResponseType = "code";
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.CallbackPath = "/signin-oidc"; // Must match auth server config
        options.SaveTokens = true;
        options.SignedOutRedirectUri = "/"; // Redirect here after logout
    });

    services.AddAuthorization();
}

Update Startup.cs - Configure

Make sure the authentication middleware runs before the SPA middleware, and add a way to trigger the auth redirect:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Error handling, static files, etc.
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSpaStaticFiles();

    // Critical: Authentication middleware must come before SPA
    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.UseAngularCliServer(npmScript: "start");
        }

        // Intercept all SPA requests to check authentication
        spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
        {
            OnPrepareResponse = ctx =>
            {
                // If user isn't authenticated, redirect to login endpoint
                if (!ctx.Context.User.Identity.IsAuthenticated)
                {
                    ctx.Context.Response.Redirect("/Account/Login");
                }
            }
        };
    });
}

Add a Login Controller

Create a simple controller to trigger the OIDC challenge:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;

public class AccountController : Controller
{
    public IActionResult Login()
    {
        // Redirect to auth server, then back to SPA root after success
        return Challenge(new AuthenticationProperties { RedirectUri = "/" }, 
            OpenIdConnectDefaults.AuthenticationScheme);
    }
}
2. Add Angular Frontend Guard

Even with backend protection, we should add a frontend guard to catch cases where the Angular dev server might bypass backend checks (like in development).

Create an Auth Service

First, a service to check if the user is authenticated:

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class AuthService {
  isAuthenticated(): boolean {
    // Check for a valid access token (adjust based on your token storage)
    const token = localStorage.getItem('access_token');
    // Optional: Add token expiration check here
    return !!token;
  }
}

Create an Auth Guard

This guard will block unauthenticated users from accessing any routes:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (!this.authService.isAuthenticated()) {
      // Redirect to backend login to trigger auth server flow
      window.location.href = '/Account/Login';
      return false;
    }
    return true;
  }
}

Protect Your Routes

Update app-routing.module.ts to apply the guard to all routes:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  { path: '', component: HomeComponent, canActivate: [AuthGuard] },
  // Add canActivate: [AuthGuard] to all other protected routes
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
3. Final Checks
  • Double-check your auth server configuration: Make sure the client ID, secret, and callback path (/signin-oidc) match exactly what you've set in .NET Core.
  • In development, ensure your Angular proxy config forwards auth-related requests to the backend (your proxy.conf.json should route /Account and /signin-oidc to the .NET Core server).
  • After authentication, the backend will redirect back to /, and the Angular guard will recognize the valid token and allow access.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:10:35