Link to home
Create AccountLog in
Avatar of angel7170
angel7170Flag for United States of America

asked on

Context.User.Identity.name in C#

Hello Experts,

I have successfully parsed SAML response and got the username from the SAML assertion attribute (this.UserID holds the username)  but I don't know how to pass this username to Context.User.Identity.name in the startup.cs. Could you please please help? Any assistance is greatly appreciated.  This is very urgent.  Thank you so much

Attached is my startup.cs code
 
                    @if (Context.User.Identity.Name != null)
                    {
                        <li class="text-white">
                            <a href="#">@Context.User.Identity.Name </a>
                        </li>
                        <li>
                            <form asp-controller="Account" asp-action="Logout" method="post">
                                <button type="submit" class="btn btn-link" name="provider" value="Saml2">Sign out</button>
                            </form>
                        </li>
                    }
                    else
                    {
                        <li>
                            <form asp-controller="Account" asp-action="ExternalLogin" method="post">
                                <button type="submit" class="btn btn-link" name="provider" value="Saml2">Sign In</button>
                            </form>
                        </li>
                    }

Open in new window


Here is my saml parsed code

string encodedSaml = this.Request.Form["SAMLResponse"];
            //EncodedeSAML = rawSamlData;
            // the sample data sent us may be already encoded, 
            // which results in double encoding
            if (encodedSaml.Contains('%'))
            {
                encodedSaml = System.Web.HttpUtility.UrlDecode(encodedSaml);
            }

            // read the base64 encoded bytes
            string samlAssertion = Decode64Bit(encodedSaml);
            DecodedSAML = samlAssertion;
            //SamlParser(DecodedSAML);

            //samldata = Decode64Bit("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=") + samldata;
            string samldata = DecodedSAML;

            if (!samldata.StartsWith(@"<?xml version="))
            {
                samldata = Decode64Bit("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=") + samldata;
            }

            string firstName = string.Empty;
            XmlDocument xDoc = new XmlDocument();
            samldata = samldata.Replace(@"\", "");
            xDoc.LoadXml(samldata);
            //xDoc.Load(new System.IO.TextReader());//Suppose the xml you have provided is stored in this xml file.

            XmlNamespaceManager xMan = new XmlNamespaceManager(xDoc.NameTable);
            xMan.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
            xMan.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            xMan.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");


            XmlNode xNode = xDoc.SelectSingleNode("/samlp:Response/samlp:Status/samlp:StatusCode/@Value", xMan);
            if (xNode != null)
            {
                this.AuthenticationStatus = false;
                string statusCode = xNode.Value;
                if (statusCode.EndsWith("status:Success"))
                {
                    this.AuthenticationStatus = true;

                }

            }

                        // samlp:Response  saml:Assertion saml:AttributeStatement saml:Attribute
            xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute[@Name = 'urn:oid:0.9.2342.19200300.100.1.1']/saml:AttributeValue", xMan);
            if (xNode != null)
            {
                
                this.UserID = xNode.InnerText;
            
            }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Duy Pham
Duy Pham
Flag of Viet Nam image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of angel7170

ASKER

Thank you! where should the code be placed? In startup.cs or accountcontroller.cs?

How do I get the username from the accountcontroller passed on this principal? Sorry I am not familiar with this concept so could you please let me know?
Usually it should be set right after login, and that would be kept through the session until session is expired or application explicitly resets the identity (e.g.: when user signs out).

Once principal/identity is set on your current thread/context, your subsequent requests will be able to get that UserName. But be aware that subsequent requests are server requests, so you probably want to refresh current page after signing in, or if you do signing in using AJAX, you need to send back username as part of the response in order to be able to use that UserName value in client-side without refreshing the page.

I'm not sure which kind of authentication (authorization) scheme and system you are using in your application, so I can't help much with the details.