【问题标题】:ASP.NET and OWIN Cookies Azure Open ID is not workingASP.NET 和 OWIN Cookie Azure Open ID 不起作用
【发布时间】:2021-01-25 15:14:56
【问题描述】:

我尝试使用 OpenID 连接 Azure AD,但我使用教程 https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-asp-webapp 中的确切代码,但没有成功。

我的创业:

public class Startup
{
     string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
     string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];
     static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
     string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, 
                        System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

/// <summary>
/// Configure OWIN to use OpenIdConnect
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            Authority = authority,
            RedirectUri = redirectUri,
            PostLogoutRedirectUri = redirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            ResponseType = OpenIdConnectResponseType.IdToken,
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true
            },
            
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed
            }
        }
    );
}

/// <summary>
/// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
    context.HandleResponse();
    context.Response.Redirect("/?errormessage=" + context.Exception.Message);
    return Task.FromResult(0);
}

我的登录页面代码:

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                if (!Request.IsAuthenticated)
                {
                    HttpContext.Current.GetOwinContext().Authentication.Challenge(
                        new AuthenticationProperties { RedirectUri = "/AMS/Dashboard" },
                        OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }
                else
                {
                    var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
                    lblErrorMessage.InnerHtml = userClaims?.FindFirst("preferred_username")?.Value;
                    //check user info, and create session then redirect to Dashboard
                }
            }
        }
        catch (Exception ex)
        {
             //handle error
        }
  }

我的网站结构有点复杂,如下:

我在服务器 x 上有一个网站:mydomain.com 我在服务器 y 中有一个子域:subdomain.mydomain.com 我在服务器 z 上有我的网站 AMS,并重定向到 subdomain.mydomain.com/AMS

现在要解决跨站点 cookie 我在 web config 中使用以下内容

<outboundRules>
    <rule name="Ensure httpOnly Cookies" preCondition="Missing httpOnly cookie">
        <match serverVariable="RESPONSE_Set_Cookie" pattern="^(.*; path=/)" negate="false" />
        <action type="Rewrite" value="{R:1}AMS; SameSite=none; secure; HttpOnly" />
    </rule>
    <preConditions>
        <preCondition name="Missing httpOnly cookie">
            <!-- Don't remove the first line! -->
            <add input="{RESPONSE_Set_Cookie}" pattern="." />
            <add input="{RESPONSE_Set_Cookie}" pattern="; SameSite=none; secure; HttpOnly" negate="true" />
        </preCondition>
    </preConditions>
</outboundRules>

我的问题是 Request.IsAuthenticated 始终为 false,因此页面一直重定向到 Microsoft 登录页面

有什么想法吗? 提前致谢

【问题讨论】:

  • 是否有任何 cookie 被阻止? Chrome 网络标签有一个名为“已阻止 cookie”的选项来检查这一点。
  • @Jeroen 是的
  • 如果您在 chrome 中关闭相同的站点 cookie 强制执行,它会起作用吗? support.siteimprove.com/hc/en-gb/articles/…

标签: asp.net webforms asp.net-identity owin openid


【解决方案1】:

试试这个,而不是重写规则:

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    CookieSameSite = Microsoft.Owin.SameSiteMode.None,
    CookieSecure = CookieSecureOption.Always
});

还要确保设置了安全属性

来自https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

SameSite NONE - Cookie 将在所有情况下发送,即响应第一方和跨域请求。如果设置了 SameSite=None,则还必须设置 cookie Secure 属性(否则 cookie 将被阻止)。

【讨论】:

    猜你喜欢
    • 2014-09-04
    • 2016-01-04
    • 2015-12-28
    • 2017-02-01
    • 2015-12-27
    • 2019-02-10
    • 2015-08-09
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多