状态 cookie 无效。处理远程登录时遇到错误。ASP.NET Core MVC 外部社交登录

在没有 ASP.NET Core Identity 的情况下在 ASP.NET Core2.2 MVC Web 应用程序中实现外部社交登录。成功登录 Google、Facebook、Twitter、LinkedIn 和 Microsoft 后,我在重定向回应用程序时收到以下错误。

处理请求时发生未处理的异常。异常:无效的状态 cookie。地点未知

异常:处理远程登录时遇到错误。Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()

以下是Startup.cs文件中的设置


public void ConfigureServices(IServiceCollection services)

   {

       services.Configure<CookiePolicyOptions>(options =>

       {

           // This lambda determines whether user consent for non-essential cookies is needed for a given request.

           options.CheckConsentNeeded = context => true;

           options.MinimumSameSitePolicy = SameSiteMode.None;

       });


       services

           .AddAuthentication(options =>

           {

               options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;

               options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;

           })

           .AddCookie(options =>

           {

               options.Cookie.IsEssential = true;

           })

           .AddGoogle(options =>

           {

               options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

               options.ClientId = Configuration["Authentication:Google:ClientId"];

               options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];

               options.CallbackPath = "/externallogincallback";             

           })

           .AddFacebook(facebookOptions =>

           {

               facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];

               facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];

               facebookOptions.CallbackPath = "/externallogincallback";                                        

           })

http://img2.mukewang.com/64bbade90001b2b213650760.jpg

炎炎设计
浏览 101回答 1
1回答

慕的地6264312

externallogincallback您似乎想在登录 Microsoft 帐户后将请求重定向到。如果是这样,则不应microsoftOptions.CallbackPath设置externallogincallback.&nbsp;通过此设置,来自 Microsoft 的所有请求都将由 OAuth 中间件而不是您自己的端点处理externallogincallback。对于登录后重定向页面,您需要return Challenge(authenticationProperties, provider);通过设置authenticationProperties.authenticationProperties请按照以下步骤操作:REDIRECT URI在 Azure 门户中更改https://localhost:xxx/signin-microsoft更改Startup.cs为public class Startup{&nbsp; &nbsp; public Startup(IConfiguration configuration)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Configuration = configuration;&nbsp; &nbsp; }&nbsp; &nbsp; public IConfiguration Configuration { get; }&nbsp; &nbsp; // This method gets called by the runtime. Use this method to add services to the container.&nbsp; &nbsp; public void ConfigureServices(IServiceCollection services)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; services.Configure<CookiePolicyOptions>(options =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // This lambda determines whether user consent for non-essential cookies is needed for a given request.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; options.CheckConsentNeeded = context => true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; options.MinimumSameSitePolicy = SameSiteMode.None;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);&nbsp; &nbsp; &nbsp; &nbsp; services.AddAuthentication(options =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .AddCookie(options =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; options.Cookie.IsEssential = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //options.Cookie.SameSite = SameSiteMode.None;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .AddMicrosoftAccount(microsoftOptions =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; microsoftOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ClientId"];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.&nbsp; &nbsp; public void Configure(IApplicationBuilder app, IHostingEnvironment env)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (env.IsDevelopment())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; app.UseDeveloperExceptionPage();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; app.UseExceptionHandler("/Home/Error");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; app.UseHsts();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; app.UseHttpsRedirection();&nbsp; &nbsp; &nbsp; &nbsp; app.UseStaticFiles();&nbsp; &nbsp; &nbsp; &nbsp; app.UseCookiePolicy();&nbsp; &nbsp; &nbsp; &nbsp; app.UseAuthentication();&nbsp; &nbsp; &nbsp; &nbsp; app.UseMvc(routes =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; routes.MapRoute(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: "default",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; template: "{controller=Home}/{action=Index}/{id?}");&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}家庭控制器public class HomeController : Controller{&nbsp; &nbsp; //Action to issue a challange to google login&nbsp; &nbsp; public IActionResult LogInMicrosoft(string provider)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //provider = Microsot or Google or LinkedIn or Twitter or Facebook&nbsp; &nbsp; &nbsp; &nbsp; provider = "Microsoft";&nbsp; &nbsp; &nbsp; &nbsp; var authenticationProperties = new AuthenticationProperties&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RedirectUri = Url.Action("externallogincallback")&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; return Challenge(authenticationProperties, provider);&nbsp; &nbsp; }&nbsp; &nbsp; [Route("/[action]")]&nbsp; &nbsp; public async Task<IActionResult> externallogincallback()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var request = HttpContext.Request;&nbsp; &nbsp; &nbsp; &nbsp; //Here we can retrieve the claims&nbsp; &nbsp; &nbsp; &nbsp; // read external identity from the temporary cookie&nbsp; &nbsp; &nbsp; &nbsp; //var authenticateResult = HttpContext.GetOwinContext().Authentication.AuthenticateAsync("ExternalCookie");&nbsp; &nbsp; &nbsp; &nbsp; var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);&nbsp; &nbsp; &nbsp; &nbsp; if (result.Succeeded != true)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new Exception("External authentication error");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // retrieve claims of the external user&nbsp; &nbsp; &nbsp; &nbsp; var externalUser = result.Principal;&nbsp; &nbsp; &nbsp; &nbsp; if (externalUser == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new Exception("External authentication error");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // retrieve claims of the external user&nbsp; &nbsp; &nbsp; &nbsp; var claims = externalUser.Claims.ToList();&nbsp; &nbsp; &nbsp; &nbsp; // try to determine the unique id of the external user - the most common claim type for that are the sub claim and the NameIdentifier&nbsp; &nbsp; &nbsp; &nbsp; // depending on the external provider, some other claim type might be used&nbsp; &nbsp; &nbsp; &nbsp; //var userIdClaim = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject);&nbsp; &nbsp; &nbsp; &nbsp; var userIdClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);&nbsp; &nbsp; &nbsp; &nbsp; if (userIdClaim == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new Exception("Unknown userid");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var externalUserId = userIdClaim.Value;&nbsp; &nbsp; &nbsp; &nbsp; var externalProvider = userIdClaim.Issuer;&nbsp; &nbsp; &nbsp; &nbsp; // use externalProvider and externalUserId to find your user, or provision a new user&nbsp; &nbsp; &nbsp; &nbsp; return RedirectToAction("Privacy", "Home");&nbsp; &nbsp; }&nbsp; &nbsp; public IActionResult Index()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return View();&nbsp; &nbsp; }&nbsp; &nbsp; public IActionResult Privacy()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return View();&nbsp; &nbsp; }&nbsp; &nbsp; [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]&nbsp; &nbsp; public IActionResult Error()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP