Amadeus api return 401 client Credentials are invalid - amadeus

Amadeus api returns 401 client Credentials are invalid. Please check the code below. I included symbols [ and ] into credential strings.
// here xxxxx are placeholders for real credentials (strings)
Amadeus amadeus = Amadeus.builder("[xxxxxx]","[xxxxxx]")
.setHostname("test").setHost("test.api.amadeus.com").setSsl(true).setLogLevel("debug").build();
//HttpHandler sh = new HttpHandler();
//FlightDestination[] des = sh.FlightDest();
//id = sh.id();
try {
FlightDestination[] destination1 = amadeus.shopping.flightDestinations.get(Params.with("origin", "LON"));
id = destination1[0].getOrigin();
name = destination1[0].getDestination();
email = destination1[0].getType();
}catch (ClientException e)
{
id=e.getMessage();
}catch (NetworkException e)
{
id = e.getMessage();
}catch (NotFoundException e)
{
id = e.getMessage();
}catch (ServerException e)
{
id = e.getMessage();
}catch (ParserException e)
{
id = e.getMessage();
}catch (ResponseException e)
{
id = e.getMessage();
}

You don't need the [ ] and you need to replace them by the API_KEY and the API_SECRET that you get following this guide.
You can find examples using the Java SDK here and here.
Amadeus amadeus = Amadeus.builder("API_KEY", "API_SECRET").build();
/* Find cheapest destinations from London */
FlightDestination[] flightDestinations = amadeus.shopping.flightDestinations.get(Params.with("origin", "LON"));
System.out.println(flightDestinations[0]);

Related

GoogleIdTokenVerifier.verify always returns null

I am trying to validate a JWT Token sent by Google to my application . I am using the below code to validate the JWT token but verifier.verify(token) always returns null even if the token is valid. I have tested the token in another NodeJS code i have and it works fine in NodeJS but in the below java code i am not able to validate the token . Any help in letting me know why verifier.verify(token) returns null is appreciated.
public static boolean isRequestFromGoogle(String audience, String token) {
//HttpTransport httpTransport = checkNotNull(Utils.getDefaultTransport());
//JsonFactory jsonFactory = checkNotNull(Utils.getDefaultJsonFactory());
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(httpTransport,
jsonFactory).setAudience(Collections.singletonList(audience)).build();
try {
System.out.println("token is " + token);
System.out.println("verifier is " + verifier.toString());
GoogleIdToken idToken = verifier.verify(token);
if (idToken == null) {
System.out.println("idToken is null");
return false;
}
Payload payload = idToken.getPayload();
String issuer = (String) payload.get("iss");
String proj = (String) payload.get("aud");
System.out.println("Issuer is" + issuer);
System.out.println("Project is" + proj);
return issuer.equals("https://accounts.google.com");
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}

Get missing auditlog from Management Activity API in Office365

Our application calls out-of-the-box Office 365 Management API to retrieve activities and events on files stored in SharePoint Online. However per our experiment, the application can’t seem to retrieve not enough logs.
Example: We upload 1000 files to document library in Sharepoint Online. We receive 8 subscriptiona. Each subscription, we only get maximum 100 logs. Total call API get logs to retrieve 600 logs. Not enough!
Here my code to get subscription
List<SubscriptionsContent> GetSubscriptionsContents(AuthenticationResult authenticationResult, ManagementAPI m, DateTime startDate, DateTime endDate, bool proxyRequired = false)
{
try
{
string jsonSubscription = string.Empty;
string url = string.Empty;
string logType = "Audit.SharePoint";
if (authenticationResult != null)
{
url = string.Format(UrlFormat, m.TenantId, string.Format("subscriptions/content?contentType={0}&startTime={1}&endTime={2}", logType, startDate.ToUniversalTime().ToString(DateFormat), endDate.ToUniversalTime().ToString(DateFormat)));
jsonSubscription = ExecuteRequest(url, HttpMethod.Get, authenticationResult);
//Log.Info("jsonSubscription:");
//Log.Info(jsonSubscription);
}
var listContent = Common.GetListSubscriptionsContent(jsonSubscription);
Log.Info("Common.GetListSubscriptionsContent(jsonSubscription); Count: " + (listContent != null ? listContent.Count.ToString() : "IS NULL"));
return listContent;
}
catch (Exception ex)
{
Log.Error(ex);
return new List<SubscriptionsContent>();
}
}
Here my code to execute Request
public string ExecuteRequest(string url, HttpMethod method, AuthenticationResult token)
{
var responseStr = "";
try
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(method, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
HttpResponseMessage response = client.SendAsync(request).Result;
Log.Info("ExecuteRequest(string url, HttpMethod method, AuthenticationResult token): response.StatusCode: " + response.StatusCode + " ; response.ReasonPhrase: " + response.ReasonPhrase + " ; response.RequestMessage: " + response.RequestMessage);
if (response.IsSuccessStatusCode)
{
responseStr = response.Content.ReadAsStringAsync().Result;
}
}
catch (Exception ex)
{
Log.Error(ex);
}
return responseStr;
}
Here my code to get audit log from each subscription
List<AuditLog> listAudit = new List<AuditLog>();
foreach (var item in listSubscription)
{
var jsonAudit = ExecuteRequest(item.ContentUri.ToString(), HttpMethod.Get, authenticationResult);
if (string.IsNullOrEmpty(jsonAudit))
continue;
var listAuditLog = Common.GetListAuditLog(jsonAudit);
}
Here my code to parser JsonString
public static List<AuditLog> GetListAuditLog(string jsonString)
{
try
{
return JsonConvert.DeserializeObject<List<AuditLog>>(jsonString);
}
catch (Exception ex)
{
Log.Error("public static List<AuditLog> GetListAuditLog(string jsonString)", ex.InnerException);
return new List<AuditLog>();
}
}
I think that you need to use the pagination header.
If the amount of data is too big, the API will return a header entry named NextPageUrl containing an address to be used to request the next page of results. This link (representing the query) will be available for 24 hours.
Ex.
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
NextPageUrl:https://manage.office.com/api/v1/{tenant_id}/activity/feed/subscriptions/content?contentType=Audit.SharePoint&startTime=2015-10-01&endTime=2015-10-02&nextPage=2015101900R022885001761
So, if the response contains this header entry, just use the value of NextPageUrl to request more data.
Repeat the process until this header entry doesn't exists anymore.
You can find more information in the Office 365 Management API reference

authentication in liferay without login hook

I have a problem, I get the user and password of a view and I check if this data is correct in the data of liferay, when it's correct my method return 1 if the validation is true, but I don't know how to make the successful login in liferay, this is my method:
try {
long companyId = PortalUtil.getDefaultCompanyId();
System.out.println(companyId + " id company");
User user1;
try {
user1 = UserLocalServiceUtil.getUserByEmailAddress(companyId, name);
long cmp = user1.getCompanyId();
Company company = CompanyLocalServiceUtil.getCompany(cmp);
int a = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), user.getId(), pass, null,
null, null);
if (a == 1) {
System.out.println("Log in successful");
}
} catch (PortalException e) {
e.printStackTrace();
} catch (SystemException e) {
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("algo salio mal");
}
This seems to be a case where you would need an auto-login hook. In Liferay 7, you just need components like in: https://www.e-systems.tech/blog/-/blogs/autologin-in-liferay-7
You can use an indicator within the user session, like a token, and check it in a custom logic:
#Override
protected String[] doLogin(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final long companyId = portal.getCompanyId(request);
final HttpSession session = request.getSession();
// code your logic here..
final String[] credentials = new String[3];
credentials[0] = String.valueOf(user.getUserId());
credentials[1] = user.getPassword();
credentials[2] = Boolean.FALSE.toString();
return credentials;
}
This solution is also valid for LR6, the difference is that you are not using OSGi there, so you have to create a hook through the SDK.

Reditect url from the method of notify_url of paypal in mvc

i am using paypal for payment. in paypal i found two type url -
return_url
notify_url
i wan to check the validity after transaction, save some data and then redirect buyer to receipt page with a unique value that is saved in db. that is why i m not using redirect_url
here is my code
[HttpPost]
public ActionResult TestPaypalIpn()
{
var response = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8).ReadToEnd();
var webClient = new WebClient();
string address = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_notify-validate&" + response;
System.IO.File.WriteAllText(#"D:\Streamstech\Content\requestAddress.txt", address);
try
{
string result = webClient.DownloadString(address);
System.IO.File.WriteAllText(#"D:\Streamstech\Content\response.txt", result);
if (result == "VERIFIED")
{
if (Request.Params["payment_status"] == "Completed" && Request.Params["business"] == Request.Params["receiver_email"])
{
var lisenceKey = Request.Params["transaction_subject"];
var userProductLisence = UserProductLisenceRepository.GetConditional(
l => l.LisenceKey == lisenceKey).FirstOrDefault();
if (userProductLisence != null)
{
if (userProductLisence.PaypalTransactionId == null)
{
userProductLisence.PaypalTransactionId = Request.Params["txn_id"];
userProductLisence.PayerEmailForPaypalTransaction = Uri.EscapeUriString(Request.Params["payer_email"]);
UserProductLisenceRepository.Edit(userProductLisence);
return RedirectToAction("Receipt", "Transaction", new { requestId = userProductLisence.LisenceKey });
}
}
}
return RedirectToAction("ShowError", "Transaction", new { errorname = "", errorMessage = "something went wrong, try again later" });
}
return RedirectToAction("ShowError", "Transaction", new { errorname = "verification Problem", errorMessage = "Transaction not verified" });
}
catch (Exception e)
{
System.IO.File.WriteAllText(#"D:\Streamstech\Content\error.txt", e.Message);
return RedirectToAction("ShowError", "Transaction", new { errorname = "Error..!!!", errorMessage = "something went wrong, try again later" });
throw;
}
return null;
}
here i can compare, save data to database.. but it is not redirecting to receipt page.. what is the problem here in code...??
or any suggestion how can i do it.. ?
Thank You..
Based on your requirement, you need to use return_url instead of notify_url. For notify_url, it's used for receiving message in system back end and you maybe can't receive it immediately after payment is done. refer to https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNPDTAnAlternativetoIPN/

Error when processing the authentication request in WSO2 Identity Server - NullPointerException

I'm having a trouble when authenticating with the WSO2 Identity Server.
I have a web page named avis.com, when I enter the page, click the login button, then the web page navigates to the login form of WSO2 Identity Server. But, when I enter use name and password into the form and click login. A error page appears as:
SAML 2.0 based Single Sign-On
Error when processing the authentication request!
Please try login again.
At the Apache Tomcat Log, errors appear:
Nov 07, 2013 3:12:32 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [SAML2ConsumerServlet] in context with path [/travelocity.com] threw exception
java.lang.NullPointerException
at com.travelocity.saml.sso.SamlConsumerManager.getResult(SamlConsumerManager.java:272)
at com.travelocity.saml.sso.SamlConsumerManager.processResponseMessage(SamlConsumerManager.java:246)
at com.travelocity.saml.sso.SAML2ConsumerServlet.doPost(SAML2ConsumerServlet.java:73)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
At the com.avis.saml.sso.SamlConsumerManager.getResult(SamlConsumerManager.java:272):
private Map<String, String> getResult(XMLObject responseXmlObj) {
if (responseXmlObj.getDOM().getNodeName().equals("saml2p:LogoutResponse")) //line 722{
return null;
}
Response response = (Response) responseXmlObj;
Assertion assertion = response.getAssertions().get(0);
Map<String, String> resutls = new HashMap<String, String>(); // line 72
/*
* If the request has failed, the IDP shouldn't send an assertion.
* SSO profile spec 4.1.4.2 <Response> Usage
*/
if (assertion != null) {
String subject = assertion.getSubject().getNameID().getValue();
resutls.put("Subject", subject); // get the subject
List<AttributeStatement> attributeStatementList = assertion.getAttributeStatements();
if (attributeStatementList != null) {
// we have received attributes of user
Iterator<AttributeStatement> attribStatIter = attributeStatementList.iterator();
while (attribStatIter.hasNext()) {
AttributeStatement statment = attribStatIter.next();
List<Attribute> attributesList = statment.getAttributes();
Iterator<Attribute> attributesIter = attributesList.iterator();
while (attributesIter.hasNext()) {
Attribute attrib = attributesIter.next();
Element value = attrib.getAttributeValues().get(0).getDOM();
String attribValue = value.getTextContent();
resutls.put(attrib.getName(), attribValue);
}
}
}
}
return resutls;
}
At the com.avis.saml.sso.SAML2ConsumerServlet.doPost(SAML2ConsumerServlet.java:72)
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException {
String responseMessage = request.getParameter("SAMLResponse");
if (responseMessage != null) { /* response from the identity provider */
Map<String, String> result = consumer.processResponseMessage(responseMessage);
if (result != null && result.size() == 1) {
/*
* No user attributes are returned, so just goto the default
* home page.
*/
response.sendRedirect("home.jsp?subject=" + result.get("Subject"));
} else if (request != null && result.size() > 1) {
/*
* We have received attributes, so lets show them in the
* attribute home page.
*/
String params = "home-attrib.jsp?";
Object[] keys = result.keySet().toArray();
for (int i = 0; i < result.size(); i++) {
String key = (String) keys[i];
String value = (String) result.get(key);
if (i != result.size()) {
params = params + key + "=" + value + "&";
} else {
params = params + key + "=" + value;
}
}
response.sendRedirect(params);
} else {
// something wrong, re-login
response.sendRedirect("index.jsp");
}
} else { /* time to create the authentication request or logout request */
try {
String requestMessage = consumer.buildRequestMessage(request);
response.sendRedirect(requestMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
At the com.avis.saml.sso.SamlConsumerManager.processResponseMessage(SamlConsumerManager.java:246)
public Map<String, String> processResponseMessage(String responseMessage) {
XMLObject responseXmlObj = null;
try {
responseXmlObj = unmarshall(responseMessage);
} catch (ConfigurationException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnmarshallingException e) {
e.printStackTrace();
}
return getResult(responseXmlObj); // line 246
}
Actually, I have two web pages, but here I mentioned one because they are the same. I'm doing a single sign on project that two service provider (web pages) are central authenticated at WSO2 Identity Server using SAML2.0 and OpenSAML
I don't know whether I miss some step when configure or not? Are there any important point I must keep in mind for my web page to authenticate successfully.
I was getting the same exception.Updating unmarshall method as below resolved my problem.
private XMLObject unmarshall(String responseMessage) throws ConfigurationException,
ParserConfigurationException, SAXException,
IOException, UnmarshallingException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
byte[] base64DecodedResponse = responseMessage.getBytes("UTF-8");
byte[] decoded = Base64.decode(base64DecodedResponse,0,responseMessage.length());
System.out.println(new String(decoded, StandardCharsets.UTF_8));
String s = new String(decoded,StandardCharsets.UTF_8);
Document document = docBuilder.parse(new InputSource(new StringReader(s)));
Element element = document.getDocumentElement();
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
return unmarshaller.unmarshall(element);
}