Microsoft身份验证注销不起作用

时间:2020-08-10 17:27:45

标签: c# asp.net-core authentication razor-pages logout

战斗了2天...现在需要帮助。

我正在使用Visual Studio 2019中的Razor Pages使用ASP.NET Core 3.1进行项目。该项目具有本地帐户,能够注册其他外部帐户,例如Microsoft,Facebook等。我关注了有关Microsoft文档的教程设置Microsoft身份验证,并且登录可以正常运行时,注销操作不会清除会话。

为了测试该问题,我从头开始构建了应用程序,没有进行任何修改,并且按照说明进行操作,我仍然遇到相同的问题...注销未重定向到Microsoft进行注销。

体验:当我登录和/或注册帐户时,将在dbo.AspNetUsers数据表中创建一个帐户。我能够使用我的Microsoft帐户登录而没有问题,重定向有效,依此类推。注销时,我得到标准的ASP.NET注销页面,但没有Microsoft注销页面。现在,当我返回并单击“登录”时,没有提示输入用户名/密码。这里的问题是,在具有多个用户的系统上,如果一个用户不清除cookie和历史记录,则他们将可以访问以前的用户信息...并且他们将无法登录,因为周期会重复直到cookie出现为止。手动清除。我不想使用新的Azure AD身份验证,因为它不适用于本地帐户,因此由于它仍处于PREVIEW中,因此目前不适合我使用。

我对“应用程序注册”的设置为:

重定向URI

  • https:// localhost:44323 /
  • https:// localhost:44323 / signin-microsoft

登出网址

  • https:// localhost:44323 / signout-oidc

任何有助于注销的指针都很好。

以下是我的代码示例(可以在Microsoft文档Microsoft Account Documentation上找到):

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using MSAuth.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MSAuth
{
    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.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddRazorPages();

            services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
            {
                microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ClientId"];
                microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

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

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

Logout.cshtml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace MSAuth.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class LogoutModel : PageModel
    {
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly ILogger<LogoutModel> _logger;

        public LogoutModel(SignInManager<IdentityUser> signInManager, ILogger<LogoutModel> logger)
        {
            _signInManager = signInManager;
            _logger = logger;
        }

        public void OnGet()
        {
        }

        public async Task<IActionResult> OnPost(string returnUrl = null)
        {
            await _signInManager.SignOutAsync();
            _logger.LogInformation("User logged out.");
            if (returnUrl != null)
            {
                return LocalRedirect(returnUrl);
            }
            else
            {
                return RedirectToPage();
            }
        }
    }
}

_LoginPartial.cshtml

@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

<ul class="navbar-nav">
@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
        <a  class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name!</a>
    </li>
    <li class="nav-item">
        <form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Page("/", new { area = "" })" method="post" >
            <button  type="submit" class="nav-link btn btn-link text-dark">Logout</button>
        </form>
    </li>
}
else
{
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
    </li>
}
</ul>

2 个答案:

答案 0 :(得分:0)

代替在_LoginPartial.cshtml中使用@if (SignInManager.IsSignedIn(User)),将其更改为_signInManager,这是注入字段。 SignInManager是注入的类。

答案 1 :(得分:0)

看看这些

http://www.binaryintellect.net/articles/3d6ce8b3-cb62-42b7-bedc-5e7f2fb9d017.aspx

http://docs.identityserver.io/en/latest/topics/signout_external_providers.html

看来退出外部用户是您的责任...

public IActionResult SignOut(string signOutType)
{
    if (signOutType == "app")
    {
        HttpContext.SignOutAsync().Wait();
    }
    if (signOutType == "all")
    {
        return Redirect("https://login.microsoftonline.com/common/oauth2/v2.0/logout");
    }
    return RedirectToAction("Index");
}