首页 > 解决方案 > 使用 UseCookiesAuthentication 来授权 MVC 控制器操作,它在本地工作,当应用程序部署在 azure 中时会出现问题

问题描述

我有MVC 应用程序,使用 Owin 和 Asp.Net Identity,并使用useCookieauthentication

在登录过程中,我添加了自定义声明,并且可以正确登录。```

    [HttpPost]
    public async Task<ActionResult> Login(LoginViewModel loginViewModel)
    {
        var user = UserManager.FindByName(loginViewModel.UserName);
        var signInStatus = UserManager.CheckPassword(user, loginViewModel.Password);

        if (signInStatus)
        {
            user.Claims.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim() { ClaimType = "CustomClaim", ClaimValue = loginViewModel.UserName.Trim() });
            SignInManager.SignIn(user, true, false);
            return Redirect(url);
        }
        else
        {
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(loginViewModel);
        }
    }

当我收到我的 Action 方法之一的回调时,我尝试检索我在登录过程中存储的 Claim Custom Claim。当我在本地运行和调试此代码时,它按预期正常工作。但是当我将应用程序部署到天蓝色时,我无法获得自定义声明值。

       public ActionResult Index()
        {
            var claimsPrincipal = System.Web.HttpContext.Current.User as System.Security.Claims.ClaimsPrincipal;
            var customClaimValue = claimsPrincipal.Identities.First().Claims.First(x => x.Type.Equals("CustomClaim")).Value;
            return View();
        }

标签: c#azureowinazure-web-app-serviceasp.net-identity-2

解决方案


尝试几件事,让我知道它是否仍然不适合您,根据我在其他答案中介绍的最近经验发布。

还请进一步排除故障以了解有关内部堆栈详细信息的更多信息。

  • 正如@Joey Cai 在他的回答中提到的那样**Action to take when request is not authenticated in App Service** ,将 azure 门户中的身份验证/授权部分从使用 Azure Active Directory 登录更改为**Allow Anonymous requests**。如下图所示:

在此处输入图像描述

  • 如果上述选项不起作用,请尝试以下操作:

    尝试更改 Azure 上应用程序定义的应用程序清单,以将“oauth2AllowIdTokenImplicitFlow”属性从 false 设置为 true。

    • 转到 Azure 门户,
    • 选择到 Azure Active Directory
    • 选择应用注册
    • 选择您的应用。
    • 点击清单
    • 找到值 oauth2AllowIdTokenImplicitFlow 并将其值更改为 true
    • 点击保存

Asp.net UseOpenIdConnectAuthentication 在 Azure 中不起作用

希望能帮助到你。


推荐阅读