SAML2 SSO Authentication Issue - HTTP Error 401.0 - Unauthorized

243 views Asked by At

I'm encountering a problem with SAML2 Single Sign-On (SSO) authentication in my ASP.NET application. The application is set up to load the Home/Index page on startup. If the user is not authenticated, it redirects to the SAML2 SSO login page. After a successful login, it should redirect to the Member/Home page. However, I'm facing an issue where I receive an "HTTP Error 401.0 - Unauthorized" error after successful login. I am using Sustainsys.SAML2.Owin And the SP is salesforce.

I've also included the relevant parts of my Startup.cs, MemberController, and HomeController code.

Following is 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 code

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();
}

MemberController Code

[Authorize] public class MemberController : Controller { // GET: Member public ActionResult Index() 
{    return View();
}
   
public ActionResult Home()
{
    return View();
}
}

I expected that after a successful SAML SSO login, the application would redirect the user to the Member/Home page, and the user would be authenticated and authorized to access that page.

3

There are 3 answers

0
s1mpl3 On

If you redirecting right after setting up a cookie is not a good thing, you will lose the session. Set the cookie/session and have a setTimeout to redirect the page but in the client side. I code if ruby so I didn't check your code but the behavior should be the same.

3
Shahab khan On

I got the answer. Since I was using FormAuthentication, that's why I has to set FormsAuthentication.SetAuthCookie(loginInd) after being redirected from ACS.

[AllowAnonymous]
public ActionResult Home()
{
    string samlResponse =.Params["SAMLResponse"];
    byte[] samlBytes = Convert.FromBase64String(samlResponse);
    string samlXml = Encoding.UTF8.GetString(samlBytes);
    System.Xml.Linq.XDocument samlDocument = System.Xml.Linq.XDocument.Parse(samlXml);

    XNamespace saml2Assertion = "urn:oasis:names:tc:SAML:2.0:assertion";

    loginInd = samlDocument.Descendants(saml2Assertion + "Attribute")
        .Where(attr => (string)attr.Attribute("Name") == "username")
        .Select(attr => attr.Element(saml2Assertion + "AttributeValue")?.Value);

    FormsAuthentication.SetAuthCookie(loginInd)

    return RedirectToAction("Secure", "Member", new { area = "" });
}


[Authorize]
public ActionResult Home()
{
}
1
Anders Abel On

The Owin model is not very elegant when there is an error during the authentication. If the Saml2 response processing fails, the redirect is still done, but with an added query string parameter error=access_denied. Is that query string added? If it is, then enabling logs should give you a detailed error message.