Azure AD:在 MVC5.NET C# 中注销后无法登录

huangapple go评论92阅读模式
英文:

Azure AD: can not LOG IN after LOG OUT MVC5.NET C#

问题

我有一个 Web 应用程序,应该支持 Azure AD。
我已经成功实现了重定向到 Home/Index 的登录功能。
也成功实现了重定向到 Home/Index 的注销功能。
但是,当我在注销后尝试登录时,出现错误提示:"无法登录,请重试"。

在 Azure 中显示所有的登录都是成功的。而且,如果清除浏览器缓存并重新加载页面,它会重定向到正确的已登录用户。有什么解决方法吗?

//Startup

public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
    {
        ClientId = clientId,
        RedirectUri = redirectUri,
        PostLogoutRedirectUri = postLogoutRedirectUri,
        ResponseType = "code id_token",
        Scope = "openid profile", // 包括其他所需的范围

        TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false // 如果要验证发行者,请将其设置为 true
        },
        MetadataAddress = metadataAddress, 
        CookieManager = new SystemWebCookieManager()             
    });
}

用户控制器中的注销方法

public void Logout()
{
    // 在注销时清除会话数据
    HttpContext.Session.Clear();
    HttpContext.Session.Abandon(); // 可选,但建议执行

    HttpContext.GetOwinContext().Authentication.SignOut(
        //new AuthenticationProperties { RedirectUri = postLogoutRedirectUri },
        OpenIdConnectAuthenticationDefaults.AuthenticationType,
        CookieAuthenticationDefaults.AuthenticationType);         
}

Home/Index

public ActionResult Index()
{
    var claimsIdentity = User.Identity as ClaimsIdentity;
    var name = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
    var x = HttpContext.Session["UserID"];
    // 如果用户已经通过身份验证,根据用户类型重定向到适当的视图
    if (User.Identity.IsAuthenticated)
    {
        //var claimsIdentity = User.Identity as ClaimsIdentity;
        //var name = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
        HttpContext.Session["UserID"] = name;
        if (User.IsInRole("some role"))
        {
            return RedirectToAction("Index", "Admin");
        }
        else
        {
            return RedirectToAction("Index", "User");
        }
    }
    if (!Request.IsAuthenticated)
    {
        // 如果用户未经身份验证,启动 Azure AD 身份验证流程
        HttpContext.GetOwinContext().Authentication.Challenge(
            new AuthenticationProperties { RedirectUri = redirectUri },
            OpenIdConnectAuthenticationDefaults.AuthenticationType
        );
    }

    return new EmptyResult();
}

我尝试在注销后清除 cookies,但没有帮助。

此外,在调试过程中,我注意到它只是在 Index 中循环,因为 User.Identity.IsAuthenticated = false(但在输入凭据后应该为 true)。

英文:

I have web application that should support Azure AD.
I already have successful log in with redirect Home/Index
Also successful log out with redirect to Home/Index.
But when i am trying to log in after log out error occurs "We couldn't sign you in. Please try again"

in azure itself shown that all loggings are successful. Moreover, if clear browser cash and reload - it redirects to necessary logged user. Any ideas how to resolve it?

//Startup

  public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                ResponseType = "code id_token",
                Scope = "openid profile", // Include any other required scopes
                
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false // Set to true if you want to validate the issuer
                },
                MetadataAddress = metadataAddress, 
                CookieManager = new SystemWebCookieManager()             
            });
        }

Logout Method in user controller

 public void Logout()
        {

            // Clear session data on logout
            HttpContext.Session.Clear();
            HttpContext.Session.Abandon(); // Optional, but recommended

            HttpContext.GetOwinContext().Authentication.SignOut(
                //new AuthenticationProperties { RedirectUri = postLogoutRedirectUri },
                OpenIdConnectAuthenticationDefaults.AuthenticationType,
                CookieAuthenticationDefaults.AuthenticationType);         
        }

Home/Index

  public ActionResult Index()
        {
            var claimsIdentity = User.Identity as ClaimsIdentity;
            var name = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            var x = HttpContext.Session["UserID"];
            // If the user is authenticated, redirect to the appropriate view based on user type
            if (User.Identity.IsAuthenticated)
            {
                //var claimsIdentity = User.Identity as ClaimsIdentity;
               // var name = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
                HttpContext.Session["UserID"] = name;
                if (User.IsInRole("some role"))
                {
                    return RedirectToAction("Index", "Admin");
                }
                else
                {

                    return RedirectToAction("Index", "User");
                }
            }
            if (!Request.IsAuthenticated)
            {
                // If the user is not authenticated, initiate the Azure AD authentication flow
                HttpContext.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties { RedirectUri = redirectUri },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType
                );

            }


            return new EmptyResult();
        }

I tried to clear cookies after logout but it didn't helped.

Azure AD:在 MVC5.NET C# 中注销后无法登录

Also during debugging i noticed that it just looped in Index, cause User.Identity.IsAuthenticated = false ( but it should be true after entering credentials)

答案1

得分: 0

我自己解决了:Microsoft.Owin的最新版本(4.2.2)有bug。我回滚到了版本4.1.0,然后一切开始正常工作了。我花了5天时间找到解决方法。

英文:

i resolved it by myself: the last version of Microsoft.Owin (4.2.2) is bugged. I rolled bacl to version 4.1.0 and everything started to work. It took 5 days for me to figured out.

huangapple
  • 本文由 发表于 2023年8月9日 17:40:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76866459.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定