我尝试使用OpenID连接Azure AD,并且我使用了教程中的确切代码https://learn.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,并重定向到子域.mydomain.com/AMS
现在,为了解决跨站点cookie,我在网络配置中使用以下内容
<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>
My Problem is Request.IsAuthenticated总是false,因此页面会一直重定向到Microsoft登录页面
有什么想法吗?提前感谢
不用重写规则,试试这个:
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-Cookies将在所有上下文中发送,即响应第一方和跨来源请求。如果设置了SameSite=None,则还必须设置cookie Secure属性(否则cookie将被阻止(。