OKTA - not able to retrieve authorization code - oauth

I am trying to get the authorization code from the redirect URI using below endpoint but all all I am getting is an HTML Page as part of the response . I need to get the authorization code from the api response. When I use Postman, I could see the below value as part of response headers location.
https://oidcdebugger.com/debug/?code=H9QD-knUSRO-xqXI4AQA&state=IL'
But I am not sure how to get the above value from my code . Below is my code snippet, can someone help me on this.
Const options = {
followRedirect: true,
method: 'GET',
uri: 'https://dev-XXXXX.okta.com/oauth2/default/v1/authorize',
qs: {
client_id:'XXXXXXXXXXXXXXXX',
"response_type":'code',
scope:"openid",
sessionToken:"20111nGGrl17go5apfKtY-nwcFSemP1VdMJaqT5ceGQpbOIhJ1eq9US",
"redirect_uri":"https://oidcdebugger.com/debug",
"state":"IL",
nonce:"XXX"
},
headers: {
'Accept':"application/json" ,
'Content-Type': "application/json"
}
}
request(options)
.then(function (response) {
console.log("**********************response***************************************");
console.log(response);
})
.catch(function (err) {
console.log("**********************error***************************************");
//console.log(err.options);
console.log(err.response.req.path);
});

the "https://dev-XXXXX.okta.com/oauth2/default/v1/authorize" is a front end REDIRECT call. The endpoint redirects you to your redirect url "https://oidcdebugger.com/debug" so it is expected. you need to have supply a callback function/endpoint as your redirect URL so when the above endpoint it called the callback function will have the code.

Related

Post request returning 403 when trying to call IBM AppID management API /users

I'm trying to create a custom IBM AppID Management Api interface in my application.
In order to do that, I'm using IBM IAM Token Manager library to get an IAM access token.
const itm = require('#ibm-functions/iam-token-manager')
const m = new itm({
"iamApiKey": apiKey
})
m.getAuthHeader().then(token => {
console.log("this one won't work", token)
}
var headers =
{
'accept': 'application/json',
'Authorization': token,
'Content-Type': 'application/json'
};
var options =
{
url: replacedIssUrl+"/users",
method: 'POST',
headers: headers,
body: dataString
};
function callback(error, response, body) {
console.log(response)
if (!error && response.statusCode == 200) {
console.log(body); //returns "body: "Forbidden"
}
}
request(options, callback)
Whenever I try to pre-register a user with the library's generated token, the callback returns Status 403 - Forbidden, but if it gets the IAM Access token directly through ibmcloud shell (ibmcloud iam oauth-tokens), it works fine.
Does anybody have any clue why this is happening? I know for a fact that the IAM Token Manager library generated access token is working, because I'm using it to get the user ID on the same code.
When something is wrong with my Access Token, it usually returns "Unauthorized", not "Forbidden".
I have no clue why this is happening.
Thanks in advance.
When passing an IAM token in the headers, App ID expects it to be preceded by the "Bearer " string :
var headers =
{
'accept': 'application/json',
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
};

Javascript post request callback, redirect from .NET MVC controller

I'm integrating PayPal checkout with an e-com solution, where upon PayPal successfully creating PayPal order/payment, I carry out some server side processing which eventually returns a RedirectResult (with a URL for payment failed or success accordingly) from my controller, back to the client/frontend.
I have the following code below, and was expecting it to redirect automatically, but no redirect occurrs.
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
intent: "CAPTURE",
purchase_units: [{
amount: {
value: '5.20',
}
}]
});
},
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
return fetch('/umbraco/surface/PayPalPayment/process', {
method: 'post',
redirect: 'follow',
body: JSON.stringify({
OrderID: data.orderID,
PayerID: data.payerID,
}),
headers: {
'content-type': 'application/json'
}
});
}).catch(error=>console.log("Error capturing order!", error));
}
}).render('#paypal-button-container');
If I explicitly redirect with the code below, then the action carries out.
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
return fetch('/umbraco/surface/PayPalPayment/process', {
method: 'post',
redirect: 'follow',
body: JSON.stringify({
OrderID: data.orderID,
PayerID: data.payerID,
}),
headers: {
'content-type': 'application/json'
}
}).then(function () { window.location.replace('https://www.google.co.uk') });
}).catch(function (error) {
console.log("Error capturing order!", error);
window.location.replace('https://www.bbc.co.uk');
});
}
Basically, I'm wondering why fetch redirect does not follow the Redirect that is returned form my controller. Controller redirect for full completeness:
return new RedirectResult("/checkout/thank-you") ;
Let me try to rephrase your question
You want to know why the browser did not redirect after you made a fetch - even though fetch api response
was a RedirectResult
The reason is simple, you made a request in fetch, which means you are making ajax request (hence browser will not change)
you set the redirect to follow, which means after the first request (i.e after get response from
/umbraco/surface/PayPalPayment/process), it will follow to the url /checkout/thank-you
so, what you get in the then() will be the response of /checkout/thank-you
so overall, it did follow the response but maybe not the way you expected (follow within the ajax request, not browser changing the page)
If what you want is a redirect to specific page, after the success call to /umbraco/surface/PayPalPayment/process
Then do:
Modify your backend to return JsonResult of the url instead of RedirectResult
return Json(new {redirectUrl = "/checkout/thank-you"});
use then to redirect
// other code omitted
.then(function (response) { return response.json(); })
.then(function (data) {window.location.replace(data.redirectUrl)});

auth0 invalid token toward Rails API

I'm trying to set up authentication using the Auth0 lock along with a React single page app and a Ruby on Rails API.
import React from 'react';
import Auth0Lock from 'auth0-lock';
var Login = React.createClass({
componentWillMount: function() {
this.lock = new Auth0Lock('*************', '****.eu.auth0.com', {
allowedConnections: ['facebook']
});
this.lock.on('authenticated', this._doAuthentication.bind(this));
},
showLock: function() {
this.lock.show();
},
_doAuthentication(authResult) {
console.log('Bearer '+authResult.idToken);
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:3000/authenticate',
headers: { authorization: 'Bearer '+authResult.idToken } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
console.log(authResult);
this.setToken(authResult.idToken)
},
login() {
this.lock.show()
},
loggedIn() {
return !!this.getToken()
},
setToken(idToken) {
localStorage.setItem('id_token', idToken)
},
getToken() {
return localStorage.getItem('id_token')
},
logout() {
localStorage.removeItem('id_token');
},
render: function() {
return (
<div className="login-box">
<button className="btn btn-success" onClick={this.showLock}>Sign In</button>
</div>);
}
});
export default Login;
This code comes from the Auth0 documentation. I also configured knock on the Rails API. Still, whenever I click on the "Connect via Facebook" button, I get the following:
- my token is generated (It's a valid token)
- Request is sent, with the correct authorization header
- Rails returns a 401
I made sure Rails receives the header as "Bearer [MY TOKEN]", still getting a 401.
Did I miss something ? Is anything else required ?
Ok, finally found out: my secret was not 64base encoded, which means the JWT.base64url_decode in my knock.rb was not necessary. I removed it, and voila.

AngularJS sends nil parameters to API

I created a basic API with Ruby on Rails. Whenever I try to send data from a form in AngularJS, I get this message in the Rails Server:
Parameters: {"{\"content\":\"message\"}"=>nil}
So, it's creating null records in the DB.
This is the controller in AngularJS to send the data:
app.controller('postController', function($scope, $http) {
// create a blank object to handle form data.
$scope.message = {};
// calling submit function.
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:3000/api/v1/messages',
data : $scope.message, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) { ... }
});
};
});
You need to serialize the data when you send as x-www-form-urlencoded
Example copied from docs
.controller(function($http, $httpParamSerializerJQLike) {
//...
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
});
Or use the defaults of $http which sends JSON in request body as application/json:
$http.post(myurl, data).then(...;
change this line:
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
to:
headers : {'Content-Type': 'application/json'}
Also encode to Json if it isnt like this:
data : angular.toJson($scope.message), //forms user object
This way you will send the correct JSON formatted data to API, make sure your API accepts Json encoded data just in case.

Getting HTTP 405 Method not allowed error when calling Web API method from JQuery

I have the following method in my Web API controller
[HttpGet]
[ActionName("GetByModule")]
public Object Get([FromUri]int id)
{
//var dblayer = new Db(WebConfigurationManager.ConnectionStrings["ConnectionString"]);
var annDb = new ContactsDB(WebConfigurationManager.ConnectionStrings["ConnectionString"]);
return annDb.GetContacts(id).Tables[0];
}
Here i the Jquery code which i am using to call the method
$.ajax({
type: "GET",
contentType: "application/json",
url: link,
data: null,
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, err) {
alert("Error");
}
});
The URL which is getting called is
http://localhost:56834/api/Contacts/GetByModule?id=9
But i keep getting HTTP 405 Method Not Allowed on calling it from Jquery.
Any idea what i may be doing wrong.
Thanks in Advance
Can you make sure you are making a "GET" request? (maybe from Fiddler or browser's debug mode). I say this because you seem to setting the "contentType" property in your jquery, which ideally should not be present as you should not be sending body in a "GET" request. Could you share your full raw request(may be from Fiddler)?

Resources