问题描述
我尝试使用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 而且我的网站AMS在服务器z上,并重定向到subdomain.mydomain.com/AMS
<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登录页面
有什么想法吗? 预先感谢
解决方法
代替重写规则试试这个:
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 将被阻止)。