What is the right way to Securing a SPA by authorization server before first load using ASP.NET Core 3.0?
我正在使用 IDE (Visual Studio 2019) 在 dotnet core 3.0 中为 Angular v8.0 SPA 应用程序使用”新”项目模板。
我要做的是在首次加载应用程序之前保护 SPA 本身。这意味着:当我打开我的 SPA 时,例如https://localhost:44318/ 我想立即被重定向到授权服务器,而不是单击一些将进行身份验证的按钮。
查看项目结构:
我已经尝试过的:
1
2 3 4 5 6 7 8 9 10 11 12 |
//Added this to redirect to Identity Server auth prior to loading SPA
app.Use(async (context, next) => { if (!context.User.Identity.IsAuthenticated) { await context.ChallengeAsync(“Identity.Application”); } else { await next(); } }); |
上面我在 app.UseSpa
之前添加的行
我的 Startup.cs:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
public class Startup
{ public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. services.AddDefaultIdentity<ApplicationUser>() services.AddIdentityServer() services.AddAuthentication() // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.Use(async (context, next) => app.UseSpa(spa => spa.Options.SourcePath =“ClientApp”; if (env.IsDevelopment()) |
当前行为:
当我运行我的应用程序时,我会立即重定向到我的授权服务器并路由到 https://localhost:44318/Identity/Account/Login?ReturnUrl=/ 但我无法路由到我的 SPA 路由和页面.当我单击 XYZ 上的锚链接时,理想情况下它是主组件上的路由,或者如果我强制从 url 路由计数器组件,它会向我显示以下相同的登录页面。请帮助我解决我做错了什么以及在首次加载之前通过授权服务器保护 SPA 的正确方法。
输出
- 如果我的问题是正确的,那么您有一个 SPA,并且用户要查看索引页面,他们必须获得授权。现在您已经实现了,但是在单击登录按钮后,该页面仍会加载身份验证页面。 1.您是否从服务器接收令牌? 2.您是否将令牌保存到语言环境? 3. 你的应用能识别令牌吗?
- 单击登录按钮时,它会验证我的身份并显示我的电子邮件,但是当我将自己路由到 SPA 组件时,它不允许我将我带到登录页面上,但我仍然通过了成功的身份验证。
您使用 cookie 身份验证,如果您未通过身份验证,您的应用会将您重定向到带有该代码的 openid 登录页面。
1
2 3 4 5 6 7 8 9 10 11 |
app.Use(async (context, next) =>
{ if (!context.User.Identity.IsAuthenticated) { await context.ChallengeAsync(“Identity.Application”); } else { await next(); } }); |
- 如果我没有看到它,请纠正我,但他正在使用 AddIdentityServerJwt();您在哪里看到 Cookie 身份验证?
来源:https://www.codenong.com/58363393/