场景描述
B应用程序使用OID访问A站点,通过A站点的登录页输入账号密码来通过验证,获得token。
环境:.NET CORE 3.1
1.在Startup.cs中修改Configure函数、
1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
2 {
3
4 if (env.IsDevelopment())
5 {
6 app.UseDeveloperExceptionPage();
7 }
8 else
9 {
10 app.UseExceptionHandler("/Home/Error");
11 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
12 app.UseHsts();
13 }
14 app.UseDeveloperExceptionPage();
15
16 app.UseHttpsRedirection();
17 app.UseStaticFiles();
18
19 app.UseRouting();
20
21 app.UseAuthentication();
22 app.UseAuthorization();
23
24 app.UseEndpoints(endpoints =>
25 {
26 endpoints.MapControllerRoute(
27 name: "default",
28 pattern: "{controller=Home}/{action=Index}/{id?}"
29 );
30 });
31 }
2.修改ConfigureServices函数
Authority:A站点的验证地址
ClientId:在A站点注册的客户端ID
Scope:如果不执行Scope.Clear(),默认会有一个 openid profile的Scope,如果A站点没有这个scope或者不叫这个名字的话,就会很登陆报错。
CallbackPath:替代了在Framework中的 RedirectUri 属性,需要输入相对路径。如果必须要使用RedirectUri的话,可以在OnAuthenticationFailed事件中设置 context.ProtocolMessage.RedirectUri,不过这么做好像会导致登陆页面提交后无限循环访问登录页。
1 services.AddAuthentication(options => 2 { 3 options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; 4 options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; 5 options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; 6 }) 7 .AddCookie() 8 .AddOpenIdConnect(options => 9 { 10 options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; 11 options.RequireHttpsMetadata = true; 12 options.SaveTokens = true; 13 options.Authority = "https://XXXX"; 14 options.ClientId = "test_client"; 15 options.Scope.Clear(); 16 options.Scope.Add("openid"); 17 options.ResponseType = "id_token token"; 18 options.UseTokenLifetime = true; 19 options.CallbackPath = new PathString("/home/index"); 20 //options.SignedOutRedirectUri = "https://localhost/home/index"; 21 options.Events.OnTokenValidated = context => 22 { 23 var token = context.SecurityToken.RawData; 24 return Task.FromResult(0); 25 }; 26 options.Events.OnRemoteFailure = context => 27 { 28 return Task.FromResult(0); 29 }; 30 options.Events.OnAuthenticationFailed = context => 31 { 32 33 return Task.FromResult(0); 34 }; 35 36 });