簡體   English   中英

ASP.NET MVC-兩個應用程序之間的相同身份驗證

[英]ASP.NET MVC - Same authentication between two applications

我創建了兩個共享相同身份驗證的MVC應用程序。 在應用程序中,我使用可以分配給每個用戶的不同用戶角色。 當我以管理員身份登錄時,一切正常,我登錄到第一個應用程序,並且使用相同的cookie登錄到第二個應用程序,不涉及登錄提示。

當我以分配了不同角色的用戶身份登錄時,即使登錄到第一個應用程序,登錄屏幕也會再次彈出,並且不會消失。

這些應用程序都在同一台IIS服務器上。 機器密鑰已在IIS服務器中正確配置(顯然,因為如果我以分配了管理員角色的用戶身份登錄,它會起作用),這是這兩個應用程序的Startup.Auth.cs的代碼:

第一次申請:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    CookieName = "DefaultCookie",
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

第二次申請:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    CookieName = "DefaultCookie",
    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("./Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
        OnApplyRedirect = ApplyRedirect
    },
});

private static void ApplyRedirect(CookieApplyRedirectContext context)
{
    Uri absoluteUri;
    if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri))
    {
        var path = PathString.FromUriComponent(absoluteUri);
        Trace.WriteLine(path);
        if (path == context.OwinContext.Request.PathBase + context.Options.LoginPath)
            context.RedirectUri = "/Account/Login" +
                new QueryString(
                    context.Options.ReturnUrlParameter,
                    context.Request.Uri.AbsoluteUri);
    }
    context.Response.Redirect(context.RedirectUri);
}

有誰知道為什么會這樣,我該怎么做才能解決?

這是一個授權問題,而不是身份驗證問題。 如果你可以分享的登錄所有,即在您的管理員用戶的話,那么一切都在這一方面的罰款。 但是,必須已授權用戶角色訪問控制器/操作,否則即使他們已經通過身份驗證,他們仍將被重定向到登錄頁面。 這樣做是為了讓他們有機會使用具有適當特權的帳戶重新進行身份驗證,因為他們顯然使用的那個帳戶沒有訪問權限。

長話短說,您需要確保希望用戶能夠訪問的任何控制器/動作都允許分配給他們的角色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM