I am trying to get a Kerberos token for the current user logged into Windows to make a request to a REST service that accepts Kerberos authentication.
I am using the following C code based on the solution to this question: How to get Service Token from Kerberos using SSPI
The variables domain and foundUser seem to be getting set correctly. But the Network Credentials are empty. This causes the call k1.GetToken() to throw the error System.IdentityModel.Tokens.SecurityTokenValidationException.
How can I get the Kerberos token for the user?
public String getToken(string userName)
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
var domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().ToString();
using (var domainContext = new PrincipalContext(ContextType.Domain, domain))
{
using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
{
NetworkCredential networkCred = System.Net.CredentialCache.DefaultNetworkCredentials;
string spn = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName).UserPrincipalName;
KerberosSecurityTokenProvider k1 = new KerberosSecurityTokenProvider(spn, System.Security.Principal.TokenImpersonationLevel.Impersonation, networkCred);
KerberosRequestorSecurityToken T1 = k1.GetToken(TimeSpan.FromMinutes(1)) as KerberosRequestorSecurityToken;
string sret = Convert.ToBase64String(T1.GetRequest());
return sret;
}
}
}