我在 ASP.NET 应用程序中遇到 SAML2 单点登录 (SSO) 身份验证问题。该应用程序设置为在启动时加载Home/Index页面。如果用户未经过身份验证,则会重定向到 SAML2 SSO 登录页面。成功登录后,应重定向到会员/主页页面。但是,我遇到了一个问题,成功登录后收到“HTTP 错误 401.0 - 未经授权”错误。我正在使用 Sustainsys.SAML2.Owin 并且 SP 是 salesforce。
我还包含了 Startup.cs、MemberController 和 HomeController 代码的相关部分。
以下是Startup.cs。
public class Startup { public void Configuration(IAppBuilder app) {
//JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Saml2",
CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager(),
SlidingExpiration = true,
ExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(ConfigurationManager.AppSettings["sessionTime"].ToString()))
});
app.UseSaml2Authentication(CreateSaml2Options());
}
private Saml2AuthenticationOptions CreateSaml2Options()
{
var saml2Options = new Saml2AuthenticationOptions(false)
{
SPOptions = new SPOptions
{
EntityId = new EntityId(ConfigurationManager.AppSettings["EntityId"].ToString()),
ReturnUrl = new Uri(ConfigurationManager.AppSettings["ReturnUrl"].ToString()),
},
};
saml2Options.IdentityProviders.Add(
new IdentityProvider(
new EntityId(ConfigurationManager.AppSettings["IssuerUrl"].ToString()),
saml2Options.SPOptions)
{
LoadMetadata = true,
SingleSignOnServiceUrl = new Uri(ConfigurationManager.AppSettings["SingleSignOnServiceUrl"].ToString()),
MetadataLocation = ConfigurationManager.AppSettings["MetadataLocation"].ToString(),
AllowUnsolicitedAuthnResponse = true,
});
saml2Options.AuthenticationType = "Saml2";
return saml2Options;
}
}
HomeController代码
public class HomeController : Controller
{
public ActionResult Index()
{
bool isSAML = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSamlLogin"].ToString());
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Home", "Member");
}
else
{
if (!string.IsNullOrEmpty(isSAML.ToString()))
{
if (isSAML)
{
System.Web.HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties
{
//RedirectUri = "Member/Home"
RedirectUri = ConfigurationManager.AppSettings["ReturnUrl"].ToString()
}, "Saml2");
return null;
}
return null;
}
}
return View();
}
成员控制器代码
[Authorize] public class MemberController : Controller { // GET: Member public ActionResult Index()
{ return View();
}
public ActionResult Home()
{
return View();
}
}
我预计在 SAML SSO 登录成功后,应用程序会将用户重定向到会员/主页,并且用户将经过身份验证并被授权访问该页面。
当身份验证过程中出现错误时,Owin 模型不是很优雅。如果 Saml2 响应处理失败,重定向仍会完成,但会添加查询字符串参数
error=access_denied
。是否添加了该查询字符串?如果是,那么启用日志应该会向您提供详细的错误消息。