Using the Rally API to pull user profile - rally

I am trying to use the Rally web service API to get some data. Code as blow. On IE it will pop out a login window, after entry login name and password, I am about to get some data. But when I use chrome, it response 401, not sure what I missing. I know there is SDK available, but due to some limitation, not able to use it. Any suggestions please?
var url = https://rally1.rallydev.com/slm/webservice/v2.0/users;
$.ajax({
url: url,
type: 'GET',
heards: { zsessionid: apiKey },
success: function(json) {
console.log(JSON.stringify(json));
}
},
error: function( req, status, err ) { console.log( 'something went wrong', status, err );
}
});

I'd love to know more about why you can't use the SDK. Anyway, in this case your config likely needs headers instead of heards to pass the api key.

Related

Facebook js api - "unsupported get request" error

I'm trying to get some (I think allowed) information in my app. I have an access token that has the following info:
App ID: <my app id> : iHOUSEListingPoster - Test 001
Type: User
App-Scoped User ID: <user id> : Joe Webb
Valid: True
Scopes: email, pages_show_list, pages_read_engagement, pages_manage_posts, public_profile
I'm trying this:
FB.api( "/me",
"GET",
{fields: 'name'},
function(get_fb_info_response) {
console.log("Here: ", get_fb_info_response
});
And getting this error:
"Unsupported get request. Object with ID 'me' does not exist, cannot be loaded due to missing permissions, or does not support this operation"
I have tried with both "/me" and "/me/". And while I want name, picture and email, I tried limiting it to just name, and still. What am I missing here?
Try this:
FB.api('/me?fields=name', function(response) {
console.log('me', response);
});
I'm not sure if api function from FB does have this signature you're using.
Edit
After searching at Facebook docs, found that the signature you were using is valid as well. Then, I went to do some tests here. And I was able to reproduce the same error you have mentioned when calling the function like this:
FB.api("/<123>/", "GET", { fields: 'name' }, function(response) {
console.log('response', response);
});
To fix it, you need to remove < and >, for example:
FB.api("/123/", "GET", { fields: 'name' }, function(response) {
console.log('response', response);
});
Calling /me and /me/ endpoint returned no error in my test.
In this screenshot you can see the tests I have run directly at my browser's console.
Ok, I finally figured out what the problem is/was here (sheepish face). We have a couple of Facebook accounts here at the company. One is the container for my app and it's test app, the other is a more general company account. I was logged into the general company account. When I tried my app, it grabbed some random app from that account, which wasn't the app that matched the access token (which I think is possible wrong on Facebook's part), therefore this error was thrown.
Once I logged into the correct Facebook account, all works as expected.

API mocking in cypress intercept

I am new to cypress.
Problem: I am not able to intercept url for API mocking, when there are multiple APIs are appearing in console-> network tab
Description: My requirement is as follows:
login a website, after getting the landing page,go to a particular webpage, select multiple test cases check boxes
open console-> network tab , and click run
watch multiple APIs are coming
I selected one API url among them. I want to mock this particular one.
'GET'method , url (say: https://externalAPIurl) are copied in the following code
//verify landing page is reached
cy.contains("this is landing page").should("exist");
//after login open testcase page
cy.visit(
"https://example.com/testcases"
);
//go to test suite tab test suite
cy.get("#testsuiteid")
.click();
//click test suite name
cy.contains("testsuitename").click();
// select all test cases
cy.get(".testcasecheckbox")
.click();
cy.intercept(
{
method: "GET",
url: "https://externalAPIurl",
},
{
headers: {
authorization:
"AABBXXYY",
},
},
{
statusCode: 200,
body: [
{
status: 200,
result: true,
combination: [
//same data...
],
},
],
}
);
cy.get("#run_button").click();
});
Where am I wrong?
I checked in postman, the URL, with Get method and Header-> Authorization key with proper Authorization key value (as collected from network console Headers) giving correct response, but the cy.intercept is throwing error
How to solve this?
Whenever in a website we click a button, multiple external API s are visible in console-> network. If I take any one of them -> check the URL, method, header and getting the same response in postman as in the network console, I should be able to mock the same request URL.
I tried the same when one single API is appearing in network console. It was fine. But when I select one among multiple the result is an error.
Please note: I have included the header authorization, may be the format is wrong. But if I give or do not give the authorization, the result is the same error.
If you want to intercept a 'GET' and stub the response with predefined data. I would first use dev tools network tab to capture the api response you want. Copy the response and save as a json file in your fixture folder (you can edit this file as you see fit to fake the data how you wish). From there you can do the following:
cy.fixture('apiResponse.json').as('fixture data')
.then( (data) =>{
const raw = JSON.stringify(data)
cy.request( {
method : 'GET',
url : 'api url here',
headers : {
authorization : 'AABBXXYY',
},
body : raw
})
.then( (response) => {
cy.log(response.body)
expect(`Response.status = ${response.status}`).to.eq('Response.status = 200')
})
})

Why does the browser ask me to log in with ASP.NET Core 3.1

I've created a website in ASP.NET Core 3.1, MVC, with API. There are 2 parts to the website. An classic static website (with a home, about, contact page etc) and a SPA app. You need to login to use the SPA application.
I believe my approach to auth is quite 'standard'. (There are no different permissions or roles).
The user logs in, and an HTTP Only cookie is created. They are redirected to the Web API part of the website
Any API calls to the C# Web Api, and the front end reviews the return status code (such as code 200 or 500 etc).
If the return is 401, it will assume the JWT has expired or has never been created. The front end then makes another call to the Web Api to retrieve a new Json Web Token. If the JWT is returned, the program attempts the original request again, with the valid JWT. Otherwise, it deals with the situation by alerting the user about the issue
The ajax code looks like
function toDatabase(type, url, data, successDelegate, failDelegate, errorDelegate, tryAgainIfUnathorized) {
$.ajax({
type: type.toUpperCase(),
url: url,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + bearerToken.get()
},
data: data,
dataType: "json",
success: function (response) {
successDelegate(response);
},
error: function (e) {
if (e.status === 401 && tryAgainIfUnathorized) {
const callback = function () {
toDatabase(type, url, data, successDelegate, failDelegate, errorDelegate, false, false);
};
bearerToken.refresh(callback);//try to get the updated token, then retry the original request
}
else {
if (e.status !== 200)
errorDelegate(e.statusText);
console.log("Error in ajaxCall.js. Expand for call stack:");
console.log(e);
}
}
});
This works fine on my local computer.
The problem is, seemingly randomly and not that often, on my production site, Google Chrome occasionally presents a log in dialog. My code does not create this dialog. I don't even know the javascript to create it :)
I don't understand. If I click cancel, then I can continue as I'd like (meaning I am authenticated).
I read up, and it seems that this happens because the browser detects the 401 and tries to be helpful!
I've tried to get round this issue by returning a 499 instead of a 401 but that caused even more headaches with this code
jwtBearerOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
context.Response.OnStarting(() =>
{
context.Response.StatusCode = 499;
return Task.CompletedTask;
});
return Task.CompletedTask;
}
};
How do I prevent this dialog from showing (or is my approach to using JWT incorrect)

Unable to get access Token linkedin Oauth

I know some will put comment like this post is duplicate of so many questions, but I've tried many ways to achieve Access Token in linkedin Oauth. Explaining what i tried.
1) I'm following it's official doc's Linkedin Oauth2
2) I'm successfully getting Authorization code from step 2 and passing that code to step 3 for exchanging Auth code for getting Access Token. But i'm getting following error
{"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired","error":"invalid_request"}
3) According to some links i need to set content-type in the header.Link which tells to set content-type is missing
4)Then i tried calling https://www.linkedin.com/uas/oauth2/accessToken this service instead of POSt to GET. And passing data as queryParams.
5) Some link says oauth code expires in 20 sec, So i've checked, i'm making call for access token in less that 1 sec.
6) And if i pass data in Body params like as below and used url as https://www.linkedin.com/uas/oauth2/accessToken
var postData = {
grant_type: "authorization_code",
code: authCode,
redirect_uri: 'https%3A%2F%2Foauthtest-mydeployed-app-url',
client_id: 'my_client_id',
client_secret: 'secret_key'
};
7) With Get call my url i tried
https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code='+authCode+'&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&client_id=my_client_id&client_secret=secret_key
Still i'm getting Error even though status code is 200, i'm getting that error(with GET api)
and If POSt by passing postData in body i'm getting bad request 400 status code
Not understanding why m I not getting access code. I've read many solutions.
Sharing code as requested.
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast"
], function (Controller, MessageToast) {
"use strict";
return Controller.extend("OauthTest.OauthTest.controller.View1", {
onPress: function (evt) {
var sPath =
'https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=my_client_id&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&state=DCEeFWf45A53sdfKef424&scope=r_basicprofile';
window.location.href = sPath;
var oRouter = new sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("View2", {
"username": "Test"
});
MessageToast.show(evt.getSource().getId() + " Pressed");
},
//after user allows access, user will be redirected to this app with code and state in URL
//i'm fetching code from URL in below method(call is happening in max.569ms)
onAfterRendering: function () {
var currentUrl = window.location.href;
var url = new URL(currentUrl);
var authCode = url.searchParams.get("code");
if (authCode !== undefined && authCode !== null) {
var postData = {
grant_type: "authorization_code",
code: authCode,
redirect_uri: 'https%3A%2F%2Foauthtest-mydeployed-app-url',
client_id: 'my_client_id',
client_secret: 'secret_key'
};
/* var accessTokenUrl = 'https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=' + authCode +'&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&client_id=my_client_id&client_secret=secret_key';*/
var accessTokenUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';
$.ajax({
url: accessTokenUrl,
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
},
data: postData,
success: function (data, textStatus, jqXHR) {
console.log(data);
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
alert('error');
}
});
}
}
});
});
Help will be appriciated..!!!
Finally I am happy to post my answer after so much search.
Every step I did is correct only, but one thing I was missing here like, Linkedin API doesn't supports CORS.
I tried implementing Javascript SDK, that works like charm. But API wasn't.
Then I found very helpful Link which says I need to implement Rest API from backend by allowing CORS, not from front end.
Make sure to follow all the points which I mentioned above in my post.
And for Allow CORS follow this link. You will get data but only basic profile of user according to LinkedIn Terms data can be accessible
Hope this post may help someones time to search more

Invalid CSRF when logging in to keystone

I'm entirely new to coding. I've looked around a bit, but not found anything relevant.
When logging into keystone to view our mongoDB database I get an error message saying:
Something went wrong; please refresh your browser and try again.
Doing that does not help. Neither does deleting the browser history or attempting from another lap top.
Looking at the javascript console in the browser, the error states invalid csrf.
I think this is the relevant source code in the keystone folder:
handleSubmit (e) {
e.preventDefault();
// If either password or mail are missing, show an error
if (!this.state.email || !this.state.password) {
return this.displayError('Please enter an email address and password to sign in.');
}
xhr({
url: `${Keystone.adminPath}/api/session/signin`,
method: 'post',
json: {
email: this.state.email,
password: this.state.password,
},
headers: assign({}, Keystone.csrf.header),
}, (err, resp, body) => {
if (err || body && body.error) {
return body.error === 'invalid csrf'
? this.displayError('Something went wrong; please refresh your browser and try again.')
: this.displayError('The email and password you entered are not valid.');
} else {
// Redirect to where we came from or to the default admin path
if (Keystone.redirect) {
top.location.href = Keystone.redirect;
} else {
top.location.href = this.props.from ? this.props.from : Keystone.adminPath;
}
}
});
},
How can I go about solving this / debugging the error? Thanks for any help!
This usually happens when session affinity fails. Are you using default in-memory session management? Maybe, try using a database for maintaining session state.
If you use MongoDB, Try the following config setting
'session store': 'mongo',
See 'session store' section under http://keystonejs.com/docs/configuration/#options-database for more details.