简体   繁体   中英

How to get SAML token from Application Pool Identity (for the configured user)?

Is there any way to get SAML token for the Application Pool Identity User (configured user)?

when we configure application pool dentity stores config entries (user name & password) in applicationHost.config under %systemroot%\\System32\\Inetsrv\\config path.

When application starts, it picks the user name and encrypted password for authentication. After successful authentication, will it follow token based authentication for subsequent calls or will always follows basic authentication ?

If it token based then how can i get the SAML token for application pool identity user, after the first response?

if any links please let me know.

Thanks in advance.

Ans 1: By Using Adal flow to get Jwt token for Logged on User,

if (!AdfsConfiguration.IsInitialized) throw new SecurityException(Constants.AdfsConfigurationInitilizationExceptionMessage);
if (string.IsNullOrEmpty(AdfsConfiguration.AdfsAuthorityUrl)) throw new SecurityException(Constants.AdfsConfigurationAdfsAuthorityUrlInitilizationExceptionMessage);

try
{
    var authenticationContext = new AuthenticationContext(string.Format(AdfsConfiguration.AdfsAuthorityUrl, AdfsConfiguration.AdfsInstance, AdfsConfiguration.Resource), false);

    var asyncRequest = authenticationContext.AcquireTokenAsync(AdfsConfiguration.Resource, AdfsConfiguration.ClientId, new Uri(AdfsConfiguration.RedirectUri), new PlatformParameters(PromptBehavior.Auto));
    var accessToken = asyncRequest.Result.AccessToken;
    return accessToken;
}
catch (Exception exp)
{
    var additionalInfo = $" additionalInfo : [authenticationContext : {string.Format(AdfsConfiguration.AdfsAuthorityUrl, AdfsConfiguration.AdfsInstance, AdfsConfiguration.Resource)}]";
    throw new SecurityException($"AdfsAuthorization.GetAdfsOAuthJwtAccessTokenForWinAppUserUsingAdal is failed, {additionalInfo}", exp);
}

Ans 2: By Auth code flow to get Jwt token for logged on user or Application pool identity user.

step 1 : Get Auth code from Adfs server

        var authUrl = string.Format(AdfsConfiguration.AdfsAuthUrl, AdfsConfiguration.AdfsInstance, AdfsConfiguration.ClientId, AdfsConfiguration.Resource, AdfsConfiguration.UrlEncodedRedirectUri);
        var authCode = "";

        try
        {
            do
            {
                var result = await Client.GetAsync(authUrl);
                await result.Content.ReadAsStringAsync();
                IEnumerable<string> values;
                if (result.Headers.TryGetValues("location", out values))
                {
                    foreach (string s in values)
                    {
                        if (s.Contains("code="))
                        {
                            authUrl = "";
                            authCode = s.Substring(s.IndexOf("code=", StringComparison.Ordinal) + 5);
                        }
                        else
                        {
                            authUrl = s;
                        }
                    }
                }
                else
                {
                    authUrl = "";
                }
            } while (!string.IsNullOrEmpty(authUrl));

            return authCode;
        }
        catch (Exception exp)
        {
            var additionalInfo = $"additionalInfo : [authUrl: {authUrl}]";
            throw new SecurityException($"AdfsAuthorization.GetAuthCodeForWinAppUserAsync is failed, {additionalInfo}", exp);
        }

Step 2 : Pass Auth code to get jwt token from Adfs server

        if (!AdfsConfiguration.IsInitialized) throw new SecurityException(Constants.AdfsConfigurationInitilizationExceptionMessage);

        var client = new WebClient();
        try
        {
            if (AdfsConfiguration.UseProxy == "Y")
            {
                var proxyObject = new WebProxy("Proxy", 80) { Credentials = CredentialCache.DefaultNetworkCredentials };
                client.Proxy = proxyObject;
            }

            //Uri address = new Uri(String.Format("https://{0}/adfs/oauth2/token/", AdfsInstance));
            Uri address = new Uri(string.Format(AdfsConfiguration.AdfsTokenServiceUrl, AdfsConfiguration.AdfsInstance));

            Uri redirectAddress = new Uri(AdfsConfiguration.RedirectUri);

            NameValueCollection values = new NameValueCollection
            {
                {"client_id", AdfsConfiguration.ClientId},
                {"grant_type", "authorization_code"},
                {"code", code},
                {"redirect_uri", redirectAddress.ToString()}
            };

            byte[] responseBytes = client.UploadValues(address, "POST", values);

            string response = System.Text.Encoding.UTF8.GetString(responseBytes);

            return response;

        }
        catch (Exception exp)
        {
            var additionalInfo = $" additionalInfo : [address: {string.Format(AdfsConfiguration.AdfsTokenServiceUrl, AdfsConfiguration.AdfsInstance) }, redirect Uri :{AdfsConfiguration.RedirectUri}]";
            throw new SecurityException($"AdfsAuthorization.GetAdfsOAuthTokenByAuthCode is failed, {additionalInfo}", exp);
        }
        finally
        {
            client.Dispose();
        }

To Get SAML Assertion for Application pool Identity Or Logged on user :

        string rpLoginUrl = string.Format(SapConfiguration.AdfsSignInUrl, SapConfiguration.AdfsInstance, HttpUtility.UrlEncode(GetSapTokenServiceUrl));
        string htmlContent;

        try
        {
            do
            {
                var result = await Client.GetAsync(rpLoginUrl);
                htmlContent = await result.Content.ReadAsStringAsync();
                IEnumerable<string> values;
                if (result.Headers.TryGetValues("location", out values))
                {
                    foreach (string s in values)
                    {
                        if (s.StartsWith("/"))
                        {
                            rpLoginUrl = rpLoginUrl.Substring(0, rpLoginUrl.IndexOf("/adfs/ls", StringComparison.Ordinal)) + s;
                        }
                        else
                        {
                            rpLoginUrl = s;
                        }
                    }
                }
                else
                {
                    rpLoginUrl = "";
                }
            } while (!string.IsNullOrEmpty(rpLoginUrl));
        }
        catch (Exception exp)
        {
            var additionalInfo = $" additionalInfo : [rpLoginUrl: {rpLoginUrl}]";
            throw new SecurityException($"SapAuthorization.GetSamlResponseForProcessIdentityAsync is failed, {additionalInfo}", exp);
        }

        var reg = new Regex("SAMLResponse\\W+value\\=\\\"([^\\\"]+)\\\"");
        var matches = reg.Matches(htmlContent);
        string lastMatch = null;
        foreach (Match m in matches)
        {
            lastMatch = m.Groups[1].Value;
        }

        return lastMatch;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM