Cannot resolve KeyInfo for unwrapping key: KeyInfo 'SecurityKeyIdentifier - c#-3.0

I am writing code for Wcf Client. My Wcf client interacts with OSB which requires me to use custom binding and authentication mode as usernameovertransport, OSB in turn calls a third party vendor.
When I make a request to OSB I am getting an encrypted response from the vendor (I can see response using SOAP UI and Fiddler).
However my wcf client is throwing error,
Cannot resolve KeyInfo for unwrapping key: KeyInfo 'SecurityKeyIdentifier
(
IsReadOnly = False,
Count = 1,
Clause[0] = X509SubjectKeyIdentifierClause(SKI = ***Value***)
)
', available tokens 'SecurityTokenResolver
(
TokenCount = 0,
)
'.
I tried adding endpoint behavior and mentioning ClientCredentialType with the certificate details there but still we are getting the same error.
Any help or guidance on this issue is highly appreciable. Thanks in advance.
Note: We own the private key and certificate is installed in the store.

Related

Keycloak integration to external identity provider fails when validation tokens with JWKS URL

I'm configuring an external identity provider in my Keycloak instance and trying to get it to validate the tokens using a external JWKS URL. Using the converted PEM from JWKS works fine, the using the URL is not working.
The token validation fails upon login with the following message:
[org.keycloak.broker.oidc.AbstractOAuth2IdentityProvider] (default task-4) Failed to make identity provider oauth callback: org.keycloak.broker.provider.IdentityBrokerException: token signature validation failed
I debugged the Keycloak server get more on the problem and found a "problem" in class JWKSUtils:
/**
* #author Marek Posolda
*/
public class JWKSUtils {
//...
public static Map<String, KeyWrapper> getKeyWrappersForUse(JSONWebKeySet keySet, JWK.Use requestedUse) {
Map<String, KeyWrapper> result = new HashMap<>();
for (JWK jwk : keySet.getKeys()) {
JWKParser parser = JWKParser.create(jwk);
if (jwk.getPublicKeyUse().equals(requestedUse.asString()) && parser.isKeyTypeSupported(jwk.getKeyType())) {
KeyWrapper keyWrapper = new KeyWrapper();
keyWrapper.setKid(jwk.getKeyId());
keyWrapper.setAlgorithm(jwk.getAlgorithm());
keyWrapper.setType(jwk.getKeyType());
keyWrapper.setUse(getKeyUse(jwk.getPublicKeyUse()));
keyWrapper.setVerifyKey(parser.toPublicKey());
result.put(keyWrapper.getKid(), keyWrapper);
}
}
return result;
}
//...
}
The if fails with a NullPointerException because the call jwk.getPublicKeyUse() returns null.
But I found out that it's null because the JWKS URL returns a single key without the attribute use, which is optional according to the specification. [https://www.rfc-editor.org/rfc/rfc7517#section-4.2]
Keycloak only accepts JWKS URLs that return all keys with the attribute use defined. But the IdP I'm trying to connect does not return that attribute in the key.
Given that situation, to who should I file an issue, the IdP or to Keycloak? Or is there something I'm doing wrong in the configuration?
I filed an issue with Keycloak about this exact problem in August 2019.
Their answer:
Consuming keys without validating alg and use is dangerous as such
Keycloak requires these to be present.
In my case, I contacted the IdP and they were able to populate the "use" parameter. If that is not an option, then you're pretty much stuck with your workaround.

Getting error while accessing rally using rally-rest-api-2.1.2.jar

I am getting an authentication error for API key in rally. Even api key is given full access.
java.io.IOException: HTTP/1.1 401 Full authentication is required to access this resource
at com.rallydev.rest.client.HttpClient.executeRequest(HttpClient.java:163)
at com.rallydev.rest.client.HttpClient.doRequest(HttpClient.java:145)
at com.rallydev.rest.client.ApiKeyClient.doRequest(ApiKeyClient.java:37)
at com.rallydev.rest.client.HttpClient.doGet(HttpClient.java:221)
at com.rallydev.rest.RallyRestApi.query(RallyRestApi.java:168)
This is The code :
String wsapiVersion = "v2.0";
restApi.setWsapiVersion(wsapiVersion);
restApi.setApplicationName(projectname);
QueryRequest testCaseRequest = new QueryRequest("Testsets");
if(null !=workspace && ""!=workspace)
testCaseRequest.setWorkspace(workspace);
QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);
What is wrong here ?
One of the things I would check for is whether you are inside a corporate network that uses authenticated proxy servers. Unless you configure the connection correctly, the proxy will reject your request before it even gets to Rally.
Second thing I just thought of is, whether you are setting the right field in the header to enable the use of an APIKey. The Rally servers expect the ZSESSIONID to be set to the APIKey, I believe.

Play WS OAuth content length required

I am having trouble connecting to the Evernote API using the OAuth wrapper bundled with Play 2.6.10 WS.
I am currently using sbt 0.13.15, Oracle JDK 1.8, and Scala 2.12.3.
The relevant piece of code from my OAuth Play controller:
import play.api.libs.oauth._
val KEY = ConsumerKey("KEY", "SECRET")
val EVERNOTE = OAuth(
ServiceInfo(
"https://sandbox.evernote.com/oauth",
"https://sandbox.evernote.com/oauth",
"https://sandbox.evernote.com/OAuth.action",
key = KEY
),
use10a = false
)
// Step 1: Request temporary token
EVERNOTE.retrieveRequestToken(CALLBACK_URL) match {
case Right(t: RequestToken) =>
// Step 2: Request user authorization; pass temporary token from Step 1
// Also, store temporary token and secret for later use
Redirect(EVERNOTE.redirectUrl(t.token)).withSession("token" -> t.token, "secret" -> t.secret)
// TODO: check this out!
case Left(e) => throw e
}
The application crashes due to the exception thrown from the Either returned by retrieveRequestToken. The exact exception is:
OAuthCommunicationException: Communication with the service provider failed: Service provider responded in error: 411 (Length Required)
After some snooping around, it seems as if this issue is common in OAuth and requires the POST request headers to contain a Content-Length (typically set to 0). Example: Why I get 411 Length required error?. But as far as I can tell, Play WS does not expose this option from Signpost (OAuth library under the hood), so I was not able to try this solution.
Of course, I may be overlooking something here. Has anyone experienced a similar issue? I just want to make sure before creating a new issue on the WS repo.
Thanks.
Evernote requires content-length for the API calls so I think that's the case.
Getting 411 error bad request in Evernote

Cannot Validate AccessToken with IdentityServer

We are using IdentityServer for authentication and we are validating the access token using JwtSecurityTokenHandler ValidateToken. This used to work fine, but after we upgraded our client application to ASP.NET Core 1.0 RTM (from RC1), the validation fails. The received error is:
IDX10501: Signature validation failed. Unable to match 'kid'
When I look at the KeyID of the used certificate and the kid of the token, I can see that they are different. I checked the IdentityServer jwks-endpoint to check that I had the correct certificate and noticed that the kid and certificate key id are different from that endpoint too. From what I've understood, they are supposed to be the same?
Any ideas why the code broke during the upgrade since the certificate, token and IdentityServer are still the same and only the client app core was upgraded.
EDIT (More information)
I suspect that ValidateIssuerSigningKey is false by default and the key has not even been validated before (thus it was working). Now it seems that the ValidateIssuerSigningKey is being ignored (as bad practice?) and thus the validation fails.
Workaround/Fix
By setting the IssuerSigningKeyResolver manually and giving the key to use in validation explicitly, fixes the issue and validation passes. Not sure how good the workaround is and why the default doesn't work, but at least I can move on for now.
simplified code...
new JwtSecurityTokenHandler().ValidateToken(authTokens.AccessToken,
new TokenValidationParameters()
{
IssuerSigningKeys = keys,
ValidAudience = audience,
ValidIssuer = issuer,
IssuerSigningKeyResolver = (arbitrarily, declaring, these, parameters) => new List<X509SecurityKey> { securityKey }
}, out securityToken);
The Client and API should refer to the same instance of IdentityServer. We are running IdentityServerHost in Azure, which has different slots (main and staging) and two applications inconsistently referred to different slots. The Client received access token issued by IdSrv-main provider and passed it to API, that expected it from different provider IdSrv-staging. API validated it and returned error.
The problem is that the errror doesn't give a hint to the actual cause of the issue. MS should provide much more detailed error message to help debugging.
The current error message is not sufficient to identify the cause.

How to grab serialized in http request claims in a code using WIF?

ADFS 2.0, WIF (WS-Federation), ASP.NET: There is no http modules or any IdentityFoundation configuration defined in a web.config (like most WIF SDK samples show), instead everything is done via program code manually using WSFederationAuthenticationModule, ServiceConfiguration and SignInRequestMessage classes. I do http redirect to ADFS in a code and it seems to work fine, returning claims and redirecting user back to my web site with serialized claims in http request. So the question is how to parse this request using WIF classes, properties and methods and extract claims values from there? Thanks
Just in case want to share my experience, it might help somebody in the future. Well, solution I finally came to looks like this:
var message = SignInResponseMessage.CreateFromFormPost(Request) as SignInResponseMessage;
var rstr = new WSFederationSerializer().CreateResponse(message, new WSTrustSerializationContext(SecurityTokenHandlerCollectionManager.CreateDefaultSecurityTokenHandlerCollectionManager()));
var issuers = new ConfigurationBasedIssuerNameRegistry();
issuers.AddTrustedIssuer("630AF999EA69AF4917362D30C9EEA00C22D9A343", #"http://MyADFSServer/adfs/services/trust");
var tokenHandler = new Saml11SecurityTokenHandler {CertificateValidator = X509CertificateValidator.None};
var config = new SecurityTokenHandlerConfiguration{
CertificateValidator = X509CertificateValidator.None,
IssuerNameRegistry = issuers};
config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("MyUri"));
tokenHandler.Configuration = config;
using(var reader=XmlReader.Create(new StringReader(rstr.RequestedSecurityToken.SecurityTokenXml.OuterXml)))
{
token = tokenHandler.ReadToken(reader);
}
ClaimsIdentityCollection claimsIdentity = tokenHandler.ValidateToken(token);
I found few similar code that uses SecurityTokenServiceConfiguration (it contains token handlers) instead of Saml11SecurityTokenHandler to read and parse token, however it did not work for me because of certificate validation failure. Setting SecurityTokenServiceConfiguration.CertificateValidator to X509CertificateValidator.None did not help coz Security Token Handler classes uses their own handler configuration and ignores STS configuration values, at least if you specify configuration parameters through the code like I did, however it works fine in case configuration is defined in web.config.