I am using the Swagger Generator website to generate the code for an API in Java. The API specifications are public and available here. As you can see, seems like the JSON doesn't have any Authentication configuration in it, but the API actually uses an OAuth authentication using "Microsoft Identity Platform" as authority and using an Application ID and Secret to get a JWT. I can obtain the token in Java using external libraries, but I'd like to integrate the process in Swagger as much as possible.
By importing into the generator the previous JSON, obviously no Authorization is configured and all API calls fail. I modified the JSON and added these parameters:
"securityDefinition":{
"civnext_oauth":{
"type":"oauth2",
"authorizationUrl":"https://login.microsoftonline.com/............./oauth2/token",
"flow":"application",
"scopes":{
"write:protocollo":"Modify Protocolli",
"read:protocollo":"Read Protocolli"
}
}
},
And then, for every Path I added
"security":{
"civnext_oauth":[
"write:protocollo",
"read:protocollo"
]
},
I generated all the files and imported them correctly in my project, but I still could not manage to test an authenticated API call.
In particular:
I don't know if my changes in the JSON are correct and if it is the right procedure. Am I missing something? Am I doing something wrong?
I do not know the right way to handle the authentication and API calls in Java after generating the code. Right now I am doing like this:
String authority = "https://login.microsoftonline.com/............./oauth2/token";
ExecutorService service = Executors.newFixedThreadPool(1);
AuthenticationContext context = new AuthenticationContext(authority, true, service);
Future<AuthenticationResult> future = context.acquireToken(
"api_resource_path",
new ClientCredential(
"app_id",
"secret"),
null);
AuthenticationResult result = future.get();
OAuth authentication = new OAuth();
authentication.setAccessToken(result.getAccessToken());
ApiClient apiClient = new ApiClient();
apiClient.getAuthentications().put("oauth2", authentication);
apiClient.setBasePath("basepath");
apiClient.setAccessToken(result.getAccessToken());
ProtocolloApi api = new ProtocolloApi();
api.setApiClient(apiClient);
Call call = api.protocolloGetTipoPostaCall("1.0", null, null);
Response response = call.execute();
System.out.println(response.toString());
But since I am missing experience and documentation, this is just improvisation.
Can you help me?
Best regards,
Giammarco
Related
Hi Everyone I am trying to integrate authorization flow in OIDC implementation in one of my java applications. The problem is that as soon as I send my request to the authorization point I see my browser getting redirected to redirect_uri along with "state" and "code". However while I am trying to get this value programmatically in my Java class using connect2id(Nimbus library) I am getting null.
Can anyone please tell me what exactly I am missing? Also refer the piece of code that I am referring to:
https://connect2id.com/products/nimbus-oauth-openid-connect-sdk/examples/openid-connect/oidc-auth
[code sample used][1]
AuthenticationResponse response =
AuthenticationResponseParser.parse(
new URI(callbackuri);
AuthenticationRequest request =
new AuthenticationRequest.Builder(
new ResponseType("code"),
new Scope("openid"),
clientID,
callback)
.endpointURI(new URI("https://c2id.com/login"))
.state(state)
.nonce(nonce)
.build();
I'm trying to get my head around the OAuth2 Java library that Google provides.
I have everything I need to make the request to Google's token endpoint manually using Springs built-in WebClient. However, this is very verbose and feels like re-inventing the wheel. It got me thinking that there must be a way to get this data using the classes provided by the library. Right?
Currently I am using the com.google.auth.oauth2.UserAuthorizer class to build up a request for the exchange of information.
val userCredentials: UserCredentials = UserAuthorizer.newBuilder()
.setClientId(googleOauthConfig.clientId)
.setTokenStore(tokenStore)
.setScopes(googleOauthConfig.scopes)
.setTokenServerUri(URI.create("https://oauth2.googleapis.com/token"))
.setCallbackUri(redirectUri)
.build()
.getCredentialsFromCode(authorizationCode, redirectUri)
The internals of getCredentialsFromCode() parses the response and it contains all the tokens. Including the id_token but, it gets discarded when constructing the UserCredentials object further down.
return UserCredentials.newBuilder()
.setClientId(clientId.getClientId())
.setClientSecret(clientId.getClientSecret())
.setRefreshToken(refreshToken)
.setAccessToken(accessToken)
.setHttpTransportFactory(transportFactory)
.setTokenServerUri(tokenServerUri)
.build(); // no mention of id_token
Regardless, I want to get this value so I can know basic information about the user such as their name, birthday and email address from a single request.
There does exist a method called idTokenWithAudience() which returns a Google ID Token from the refresh token response. If I call this, I get a token back that doesn't contain all the data that was available in the identically named id_token mentioned earlier making it a no-go either.
You can use IdTokenCredentials to access the ID token like so:
var credentials = UserCredentials.newBuilder()
.setClientId("...")
.setClientSecret("...")
.setRefreshToken("...")
.build()
.createScoped("openid email");
var idToken = IdTokenCredentials
.newBuilder()
.setIdTokenProvider((IdTokenProvider)credentials)
.build();
idToken.refresh();
System.out.println(idToken.getIdToken().getTokenValue());
I'm using the WSRequest class to make requests to an external web-service in my Play web-application.
Here's a small snippet of the code I'm using to make SOAP calls:
WSRequest req = WS.url("http://mydomain.com/soap");
req.setHeader("Content-Type", "text/xml;charset=UTF-8");
Map<String, Object> args = new HashedMap();
args.put("countryCode", countryCode);
req.body(requestTemplate.render(args));
HttpResponse res = req.post();
Document document=null;
try{
document = res.getXml();
}catch(RuntimeException e){
System.out.println(res.getString());
throw e;
}
I'd like SOAP calls made to this endpoint to show up on the "External Services" page of New Relic. How can I instrument my code in order to accomplish this? I haven't been able to find much information about this in the documentation except for a Ruby example.
At this time, the New Relic Java agent only notices external calls made with the following methods:
HttpURLConnection
CommonsHttp
Jets3t
S3
AsyncHttpClient
The Play WS API is not among those and, at this time, there is no way to for the user to do anything to modify the behavior.
I would recommend contacting New Relic tech support with a feature request to add external call support for Play's WS API.
You can now implement custom network tracking:
https://docs.newrelic.com/docs/mobile-sdk-api/android-api#track-custom
I have succeed using openID and OAuth separately, but I can't make them work together.
Am I doing something incorrect:
String userSuppliedString = "https://www.google.com/accounts/o8/id";
ConsumerManager manager = new ConsumerManager();
String returnToUrl = "http://example.com:8080/app-test-1.0-SNAPSHOT/GAuthorize";
List<DiscoveryInformation> discoveries = manager.discover(userSuppliedString);
DiscoveryInformation discovered = manager.associate(discoveries);
AuthRequest authReq = manager.authenticate(discovered, returnToUrl);
session.put("openID-discoveries", discovered);
FetchRequest fetch = FetchRequest.createFetchRequest();
fetch.addAttribute("email","http://schema.openid.net/contact/email",true);
fetch.addAttribute("oauth", "http://specs.openid.net/extensions/oauth/1.0",true);
fetch.addAttribute("consumer","example.com" ,true);
fetch.addAttribute("scope","http://www.google.com/calendar/feeds/" ,true);
authReq.addExtension(fetch);
destinationUrl = authReq.getDestinationUrl(true);
then destinationUrl is
https://www.google.com/accounts/o8/ud?openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.return_to=http%3A%2F%2Fexample.com%3A8080%2FgoogleTest%2Fauthorize&openid.realm=http%3A%2F%2Fexample.com%3A8080%2FgoogleTest%2Fauthorize&openid.assoc_handle=AMlYA9WVkS_oVNWtczp3zr3sS8lxR4DlnDS0fe-zMIhmepQsByLqvGnc8qeJwypiRQAuQvdw&openid.mode=checkid_setup&openid.ns.ext1=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0&openid.ext1.mode=fetch_request&openid.ext1.type.email=http%3A%2F%2Fschema.openid.net%2Fcontact%2Femail&openid.ext1.type.oauth=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Foauth%2F1.0&openid.ext1.type.consumer=example.com&openid.ext1.type.scope=http%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F&openid.ext1.required=email%2Coauth%2Cconsumer%2Cscope"
but in the response from google request_token is missing
http://example.com:8080/googleTest/authorize?openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fud&openid.response_nonce=2011-11-29T17%3A38%3A39ZEU2iBVXr_zQG5Q&openid.return_to=http%3A%2F%2Fexample.com%3A8080%2FgoogleTest%2Fauthorize&openid.assoc_handle=AMlYA9WVkS_oVNWtczp3zr3sS8lxR4DlnDS0fe-zMIhmepQsByLqvGnc8qeJwypiRQAuQvdw&openid.signed=op_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle%2Cns.ext1%2Cext1.mode%2Cext1.type.email%2Cext1.value.email&openid.sig=5jUnS1jT16hIDCAjv%2BwAL1jopo6YHgfZ3nUUgFpeXlw%3D&openid.identity=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOawk8YPjBcnQrqXW8tzK3aFVop63E7q-JrCE&openid.claimed_id=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2Fid%3Fid%3DAItOawk8YPjBcnQrqXW8tzK3aFVop63E7q-JrCE&openid.ns.ext1=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0&openid.ext1.mode=fetch_response&openid.ext1.type.email=http%3A%2F%2Fschema.openid.net%2Fcontact%2Femail&openid.ext1.value.email=example%40gmail.com
why?
In the above code, you have added OAuth extension parameters with the Attribute Exchange extension parameters. But since OAuth and Attribute Exchange are different extensions, therefore you have to create a different extension message for OAuth parameters and then add it to Authentication request message.
But since there is no mechanism to add OAuth parameters to the Authentication message, therefore you'll have to create such a mechanism. You can get information about it in the following link
http://code.google.com/p/openid4java/wiki/ExtensionHowTo
You can then use the code provided in the following link to hard code this mechanism
http://code.google.com/p/openid4java/issues/detail?id=110&q=oauth
I can call NetDocuments SOAP API by C# as following:
// Authenticate to the NetDocuments directory service
ndDir.Directory ndDirectory = new ndDir.Directory();
ndDirectory.CookieContainer = new System.Net.CookieContainer(); // enable cookie handling
ndDirectory.Login( username, password );
// Connect to the NetDocuments storage service
ndStor.storage ndStorage = new ndStor.storage();
ndStorage.CookieContainer = ndDirectory.CookieContainer; // share cookies with the directory service
XmlNode searchRes = ndStorage.Search( criteria, attrList );
However, when I call NetDocuments SOAP API by java with Axis 1.4, I receive error: "No authentication session. The authentication session has timed out or was not established prior to this call."
DirectorySoapStub stubDir = new DirectorySoapStub(new URL("https://vault.netvoyage.com/ndApi/directory.asmx"), new DirectoryLocator());
StorageSoapStub stubSto = new StorageSoapStub(new URL("https://vault.netvoyage.com/ndApi/storage.asmx"), new StorageLocator());
stubSto.setMaintainSession(true);
stubDir.login(username, password);
javax.xml.soap.MimeHeaders mhds = stubDir._getCall().getMessageContext().getCurrentMessage().getMimeHeaders();
java.util.Iterator iterator = mhds.getAllHeaders();
while (iterator.hasNext()) {
javax.xml.soap.MimeHeader mhd = (javax.xml.soap.MimeHeader)iterator.next();
if ("set-cookie".indexOf(mhd.getName()) >= 0) {
stubSto._setProperty(mhd.getName(), mhd.getValue());
}
}
stubSto.search(criteria, attrList);
Is there similar thing of CookieContainer in Java? How can I call NetDocuments SOAP API by java with Axis 1.4?
I realise this question was posted a while ago, but I've been able to get this working in the past by using the JAX-RPC plugin that comes with NetBeans. The version of NetBeans I used was v6.8 (I think that the JAX-RPC plugin is not included in newer versions of NetBeans as JAX-RPC isn't widely used anymore). I remember struggling to get anything working when I tried to use Axis, though that was more than likely due to me not being familiar enough with it.
I can't remember all the steps necessary, but you can point the JAX-RPC plugin at the WSDL for NetDocuments and all the classes needed for calling the API are then set up for you.
To handle authentication correctly, it was necessary to set the SESSION_MAINTAIN_PROPERTY on the DirectorySoap_Stub and StorageSoap_Stub classes to true - this instructs them to maintain a session once you have logged in. See e.g. http://docs.oracle.com/cd/E19575-01/821-0177/fxybb/index.html for info on SESSION_MAINTAIN_PROPERTY
Additionally, when you login via the DirectorySoap object, if you then want to use the methods of StorageSoap you need to let the StorageSoap object know the cookie that you are using in the DirectorySoap session.
To do this I implemented a javax.xml.rpc.handler.Handler that stores the CookieJar from the DirectorySoap session (property "com.sun.xml.rpc.client.http.CookieJar" on the request MessageContext) and sets that CookieJar on the same property of requests of the StorageSoap session.
Hopefully that's useful to anyone with similar SOAP issues...
Cheers