Play Framework: How can I use a given certifcate for an HTTP WS.url call? - scala

I have a certificate from a REST services provider, and I need to tell an given HTTP get call to use it when contacting a given provider. The codebase I'm working on used to use a third party library to achieve this, but I want leverage the timeout features and niceties of the WS.url call.
I've had a look at the API docs and the docs on the website, and I only unearthed a few clues, and those clues have so far not lead me to any solutions.

You should be able to approach it by adapting the SSLContext of the AsyncHttpClient.
The idea is to provide the client certificate with the underlying client. I assume you have a pkcs12 flying around.
It seems like that the AsyncHttpClientConfig cannot be updated as it is auto initialised. Therefore a new client should be instantiated and used.
The following should send off the request as stated with the SSLContext containing the pkcs12 file.
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
KeyStore clientCert = KeyStore.getInstance("pkcs12");
InputStream is = new FileInputStream("/conf/brazo.p12");
clientCert.load(is, "brazo".toCharArray());
kmf.init(clientCert, "brazo".toCharArray());
SSLContext sc = SSLContext.getInstance("TLSv1");
sc.init(kmf.getKeyManagers(), null,
new SecureRandom());
AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder().setSSLContext(sc).build();
AsyncHttpClient client = new AsyncHttpClient(config);
String url = "https://your-url";
Request req = new RequestBuilder().setUrl(url).setMethod("GET").build();
client.executeRequest(req);
Sadly this goes away from Play! standard WS library.

Related

Using Proxy Authorization Header with ScalajHTTP

I'm getting a 407 error using scalajHTTP. I read through the repository and it seems like I should be able to pass the basic auth credentials as a base64 encoded value. I've also tried using the helper method described in the GitHub issues .proxyAuth but that is no longer part of HTTPRequest in ScalaJ according to error messages (as well as it not being in the documentation)
Any ideas? My endpoint URL is HTTPS as well as my proxy (for additional context)
val proxyHost= s"https://$forwardProxy"
val requestForward = Http(url).postData(redactedSecret)
.option(HttpOptions.allowUnsafeSSL)
.headers(("Content-Type", "application/json"), ("Proxy-Authorization", s"Basic $proxyAuth"))
.proxy(proxyHost, 8080).asString
val responseForward: HttpResponse[String] = requestForward
This issued posted in Github but still not resolved, https://github.com/scalaj/scalaj-http/issues/87
I found a solution to this problem. I researched around and after trying http client libraries, I kept getting 407 errors even though they all support proxy auth. Anyway, I ended up having to do the following.
add
import java.net.{Authenticator,PasswordAuthentication}
and the modified code body that I previously above looks like:
val requestForward: HttpRequest = Http(url).postData(data)
.header("Content-Type", "application/json")
.proxy(proxyHost, 8080)
.option(HttpOptions.allowUnsafeSSL)
Authenticator.setDefault(new Authenticator() {
override def getPasswordAuthentication(): PasswordAuthentication = {
new PasswordAuthentication( s"$username", s"$password".toCharArray())
}
})
So as you can see I removed the header from the original request object and instead overrode the credentials. Make sure you do this before you call on the response object.

Spring WS remove flexible URL, Restricting WSDL URL and service URL

I'm trying to make a Spring Boot Soap WebService application, and was following the Get Started (https://spring.io/guides/gs/producing-web-service/) example to learn how to do this.
I've created what I want, but I have two URL problems with this setup and I could not find what configuration should I change to fix this :
WSDL URL basic is localhost:8080/ws/countries.wsdl but anything like localhost:8080/ws/whatever/countries.wsdl is correct
service URL for SoapUI request is localhost:8080/ws but anything like localhost:8080/ws/whatever is correct
I know that this is a feature for Spring WS, but I want a fixed URL (without 'whatever' in both cases) and could not find what to change for this
There is no straight forward way to restrict the way you want.
SOAP service is not URL based.
SOAP message body describe the endpoint.
The thing you wanted is possible following way.
Changing URL mapping in ServletRegistrationBean to restrict URL access
Existing /ws/* mapping is the reason why all the /ws/whatever url successfully responded.
Change as new ServletRegistrationBean(servlet, "/ws");
Effect will be you can not request other than /ws URL
Now the problem is, you can not get WSDL by this mapping.
Solution to get WSDL
The DefaultWsdl11Definition is actually generating WSDL from XSD on every request.
Save countries.wsdl to resource folder as static WSDL file.
Remove DefaultWsdl11Definition bean.
Create a new SimpleWsdl11Definition bean as like
#Bean(name = "countries")
public SimpleWsdl11Definition orders() {
SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
wsdl11Definition.setWsdl(new ClassPathResource("countries.wsdl"));
return wsdl11Definition;
}
Now add another static URL mapping in ServletRegistrationBean. As it will be finally look like new ServletRegistrationBean(servlet, "/ws", "/ws/countries.wsdl");
This practice is good for development phase as you can publish easily the changed definition. But it is recommended to use static-wsdl for production environment. Details ** here
Just change
return new ServletRegistrationBean(servlet, "/ws/*");
for example to
return new ServletRegistrationBean(servlet, new String[]{
"/ws/v1/countries.wsdl",
"/ws/v2/countries.wsdl"
});

Play Framework & JSON Web Token

Is there a Scala implementation of JWT or at least an example with Play? After having posted this question I searched further on the Internet and found some intros to JWT. Any suggestion would be really appreciated.
I am using Nimbus-JOSE-JWT in a spray.io app and am quite happy with it. The object performing authentication extends HttpAuthenticator and if it finds a correct JWT it returns the token subject and related info, otherwise None (authentication fails). With Play2 you can implement HTTP Basic Auth with something like this. Regarding token setting/getting which I assume is of more interest to you:
First, create a private/public key pair (I used parts of this code). Create the authentication object that loads the keys on initialization from the filesystem.
Create a a com.nimbusds.jose.crypto.MACSigner and a com.nimbusds.jose.crypto.MACVerifier using these keys.
Whenever you want to set a key, FIRST encrypt it, THEN sign it. Encryption:
private def encrypt(subject: String) = {
val header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM)
val jwt = new EncryptedJWT(header, claimSet(subject))
val encrypter = new RSAEncrypter(publicKey.asInstanceOf[java.security.interfaces.RSAPublicKey])
jwt.encrypt(encrypter)
jwt.serialize()
}
The claimSet method predictably returns a set of claims:
def claimSet(subject: String) = {
val jwtClaims = new JWTClaimsSet()
jwtClaims.setIssuer(Config.JWT.issuer)
jwtClaims.setSubject(subject)
jwtClaims.setJWTID(java.util.UUID.randomUUID().toString())
jwtClaims
}
The publicKey property is the value returned from KeyFactory.getInstance("RSA").generatePublic.
Signing:
private def sign(jwt: String) = {
val jwsObject = new JWSObject(new JWSHeader(JWSAlgorithm.HS256), new Payload(jwt))
jwsObject.sign(Tokens.signer)
jwsObject.serialize
}
Given the above, when you receive a key you need to verify the signature first, then decrypt it. For verification, first you try to parse it with com.nimbusds.jose.JWSObject.parse(my_token) and as long as it doesn't throw a ParseException you call verify on the JWSObject that parse returns, using as an argument the MACVerifier that you created earlier. If verify returns true, you only need to call getPayload.toString on the same JWSObject to get the verified payload.
To decrypt the verified payload you call com.nimbusds.jwt.EncryptedJWT.parse on it, then something like:
val decrypter = new RSADecrypter(privateKey.asInstanceOf[java.security.interfaces.RSAPrivateKey])
jwt.decrypt(decrypter)
privateKey is the value returned from KeyFactory.getInstance("RSA").generatePrivate.
You can then get the claim set with jwt.getJWTClaimsSet.
Finally, with regard to setting the Authorization header, I'm doing this on my AngularJS client using principles also mentioned in this post.

Auto-generating a WebRequest

I am trying to consume a binary stream from a ServiceStack service, as described here:
How to consume a file with a ServiceStack client
I realize that I must use a custom WebClient, since I want direct access to the response stream. However, I would still like to avoid making this client by hand. Instead, I'd like to write something like,
var webClient = new JsonServiceClient(baseUrl)
.ConfigureWebClient(new MyRequestDto { Foo = "bar" }));
This way, I wouldn't have to assemble the URL and query string by hand; and when I change my request DTO, I wouldn't have to remember to change my custom WebClient setup code, either.
Is there a way to accomplish this, somehow ? I've looked at ServiceClientBase.PrepareWebRequest(...), and it does a whole lot of useful stuff that I don't feel like copy/pasting into my own code. I'd love to inherit ServiceClientBase and call that method directly, but it's private, so I can't. Anyone got any other ideas ?
All of ServiceStack's C# Service Clients have both a Global and a Local Request Filter allowing you to initialise the Request and Global and Local Response Filters allowing fine-grained access to the returned HttpWebResponse.
Initializing the WebRequest of all ServiceClients using a Global Request Filter:
ServiceClientBase.HttpWebRequestFilter = httpReq => ConfigureWebClient(httpReq);
Using the Local Request Filter:
var client = new JsonServiceClient(baseUrl) {
LocalHttpWebRequestFilter = httpReq => ConfigureWebClient(httpReq)
};
Although if you just want the binary response All Service Clients allow you to specify either a string, byte[], Stream or HttpWebResponse as your Generic Response type and it will return what was requested. See the Service Client wiki page for more examples of these.
Here's how you can retrieve binary responses:
byte[] responseBytes = client.Get<byte[]>("/poco/World");
var dto = responseBytes.FromUtf8Bytes().FromJson<PocoResponse>();
Or with a Stream:
using (Stream responseStream = client.Get<Stream>("/poco/World")) {
var dto = responseStream.ReadFully().FromUtf8Bytes().FromJson<PocoResponse>();
}
Or from the underlying HttpWebResponse:
HttpWebResponse webResponse = client.Get<HttpWebResponse>("/poco/World");
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
var dto = sr.ReadToEnd().FromJson<PocoResponse>();
}
You can change Open Source Software, you don't have to work around it
ServiceStack is Open Source software, there's no need to look for hacks or try to work around something that's not accessible or not available, make a pull-request to change what you want and if it's a valid request for a common use-case it will likely be accepted. Otherwise feel free to take a fork of the Source code and customize it as you wish.

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.