I am working on customizing my spring boot authorization server. After login using username and password from the html page I have created I need to redirect back to /oauth/token endpoint ,in order to get the access token .
It is working fine while using postman. But when I give defaultsuccessurl as /ouath/token it shows me a default login page to enter username and password which the basic auth username and password from postman.
so, in order to get the access token from front end I need to add basic auth details as http header. I don't know where to add HTTP header and how to use that to get the access token after successful login using front end.
Any help appreciated
There are multiple ways to do it. One way is: along with html, you can use Javascript to set HttpHeaders and send the request. Below a sample code snippet (not complete though)
var user = "user1"; //ideally this should come from Input field in html page
var password = "MySecret";//ideally this should come from password field in html page
// var authorizationBasic = $.base64.btoa(user + ':' + password);
var authorizationBasic = window.btoa(user + ':' + password);
var request = new XMLHttpRequest();
request.open('POST', oAuth.AuthorizationServer, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');
request.send("<requestURL>");
Related
I am attempting to create my first PowerBI Custom Connecter to connect to the Vimeo API. I am stuck on the final step of the authorization flow - getting back an access token. When trying out the Connecter in PowerBI, it seems to authenticate properly when I hit the access token endpoint, but I get back a warning "[unsupported_grant_type] Unsupported grant type"
It appears I am not sending the grant_type properly in the request. Here are Vimeo's requirements of what is sent along in the header and body of the request:
Header
Set value to
Authorization
basic base64_encode(x:y), where x is the client identifier and y is the client secret
Content-Type
application/json
Accept
application/vnd.vimeo.*+json;version=3.4
"In the request body, send the grant_type field with the value authorization_code. You must also set code to the authorization code string that you just received and redirect_uri to the redirect URI that you specified previously — don't use a different redirect URI."
{
"grant_type": "authorization_code",
"code": "{code}",
"redirect_uri": "{redirect_uri}"
}
Here is a snippet of code from the Customer Connector I am building. It is within this TokenMethod function that I am trying to fulfill the requirements of the table above. I am getting the sense I am not correctly placing the JSON in the body of the request, but I am stuck on what to try next:
TokenMethod = (grantType, tokenField, code) =>
let
queryString = [
grant_type = "authorization_code",
redirect_uri = redirect_uri,
client_id = client_id,
client_secret = client_secret
],
queryWithCode = Record.AddField(queryString, tokenField, code),
authKey = "Basic " & Binary.ToText(Text.ToBinary("client_id:client_secret"),BinaryEncoding.Base64),
tokenResponse = Web.Contents(token_uri, [
Content = Text.ToBinary(Uri.BuildQueryString(queryWithCode)),
Headers = [
#"Authorization" = authKey,
#"Content-type" = "application/json",
#"Accept" = "application/vnd.vimeo.*+json;version=3.4"
],
ManualStatusHandling = {400}
]),
body = Json.Document(tokenResponse),
result = if (Record.HasFields(body, {"error", "error_description"})) then
error Error.Record(body[error], body[error_description], body)
else
body
in
result;
I'm wondering if someone could please point out where I might be going astray in the code and why I am receiving the [unsupported_grant_type] error.
Many thanks for your time!
I changed Content-Type to "application/x-www-form-urlencoded" and it worked!
Hi I want to use Apache HTTP Client Fluent to create a request to download a file. I need to add Autorization Basic Auth to the request to pass in a username and password which I can't find a good example of how to do.
I can see a addHeader method but can't find good examples of how to construct it. Thanks!
So far the code i have is:
String auth = username + ":"+ token
byte[] encodedBytes = Base64.encodeBase64(auth.getBytes());
String encodedAuth = new String(encodedBytes)
URL downloadFileURL = new URL (urlbuild)
Executor executor = Executor.newInstance();
executor.execute(Request.Get(downloadFileURL.toURI())
.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth )
.connectTimeout(1000))
.saveContent(new File(mobileAppPath + System.getProperty("file.separator") + mobileApp.name));
the problem was due to Java trying to validate the SSL certificate i used Java code below to trust all hosts before executing the request.
https://www.javatips.net/api/java.security.cert.x509certificate
I'm working on a REST API node/express app. For my 'signup' route, where a user uses the api to sign up for the service, it takes a POST'ed JSON object. Inside this function I want to check against the mongo db to make sure that this user doesn't already exist.
The problem is I need to get the username from the posted json information, but every attempt I have made has failed. The lines that attempt to log the req.body.username and req.body.password always return 'undefined'. What am I doing wrong?
Here's the code I have so far is below:
exports.signup = function(req, res) {
// todo: somehow verify that username, password, email and phone number are all provided.
// do not write into the collection unless we know all the information has been provided.
// maybe access the JSON elements to make sure they are not null
// todo: also make sure a record doesn't already exist for this uer
var user = req.body;
// need to get the username here somehow
var JSONuser = JSON.stringify(user);
// console.log('user: ' + user);
console.log('userJSON: ' + JSON.stringify(user));
console.log('username: ' + req.body.username);
console.log('password: ' + req.body.password);
db.collection('users', function(err, collection){
//if ( collection.findOne({}) ) { // make sure the user doesn't already exist here
collection.insert(user, {safe:true}, function(err, result){
if(err){
res.send({'error':'An error has occured'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
})
//}
});
}
By default in express, you don't have access to those variables through dot syntax. You would have to parse the response. Luckily, we have a package for that.
Use body-parser middle ware for easy access to post variables.
// install it
bash$: npm install body-parser
// require it in your project
bodyParser = require('body-parser');
// `use` it in your express app
app.use(bodyParser.urlencoded({ extended: true}));
// now you your post values are available on the req.body.postVariableName
I use this in almost all of my projects, it just makes it easy.
* EDIT *
I looked at your repo and everything actually looks fine as it pertains the reading of parsed values; however, they way you are console logging them may be where you are getting confused. I rewrote your signin route so I could explain better.
exports.signin = function(req, res) {
var user = req.body;
console.log('req.body: ' + JSON.stringify(user));
console.log('Signing In As User: ' + user.username);
console.log('Password: ' + user.password);
res.send('You just signed in!');
}
I tested this my opening up another terminal and curling a JSON post.
curl -H "Content-Type: application/json" -X POST -d '{"username":"testuser","password":"testpassword"}' http://localhost:3000/signin
As you can see it should work.
Some things worth mentioning. When you wrote console.log('req.body: ' + req.body);. You are not going to see the data you want. You are going to see req.body: [object] in the output because javascript is going to render this as req.body.toString() which is just the identifier. If you want to post the code, use JSON.stringify(req.body) or use console.dir(req.body).
Second, req.body will just give u access the body object.
// this is just user.toString() which is again [object]
console.log('Signing In As User: ' + user);
// You need to use the dot syntax to get user.username
console.log('Signing In As: " + user.username);
If you are stilling seeing issues, its because of the way you are making posts localhost, not because of your code.
I am new to nodejs as well as developing.
I am trying to get a set of data bat from a nutrition site in JSON format. If I formulate the url with my app and api keys along with criteria to paste into the browser I get a JSON data ok. When I try to send a POST request as the site asks for when the request comes back it says it cannot find the url. What it is doing is attaching ':443' to the end of the host url and like I said coming back as an error:
Error: getaddrinfo ENOTFOUND https://api.nutritionix.com/v1_1/search https://api.nutritionix.com/v1_1/search:443
What I would like to do is after the end of the url is append the 'postData'.
Here is my code:
var https = require('https');
var querystring = require('querystring');
var postData = { // Nutrionix required JSON formt
"appId":"MY_APP_KEY",
"appKey":"MY_API_KEY",
"query": "Lentils",
"fields": ["item_name", "nf_calories", "nf_serving_size_qty", "nf_serving_size_unit"],
"sort":{
"field":"score",
"order":"desc"
},
"filters":{
"item_type":"2"
}
};
console.log("This is header dta" + postData);
postBody = querystring.stringify(postData);
var post_options = {
host:"https://api.nutritionix.com/v1_1/search",
"port":"443",
method:"post",
"path":"/",
headers:{"Content-Type":"application/json",
'Content-Length': postBody.length
}
}
console.log(post_options);
var request = https.request(post_options,function(response){
return response;
});
I also am passing this data into the dev HTTP add-on in Chrome and getting back the proper response.
Any help would be appreciated.
Can you please take a look at this documentation?
It seems that you don't need to mention HTTPS
Take the port off, 443 is the default for HTTPS.
I would like to use a mail list to send SMS through a third party provider. Here is the code samples that they provide:
<%
' This simple ASP Classic code sample is provided as a starting point. Please extend your
' actual production code to properly check the response for any error statuses that may be
' returned (as documented for the send_sms API call).
username = "your_username"
password = "your_password"
recipient = "44123123123"
message = "This is a test SMS from ASP"
postBody = "username=" & Server.URLEncode(username) & "&password=" & Server.URLEncode(password) & "&msisdn=" & recipient & "&message=" & Server.URLEncode(message)
set httpRequest = CreateObject("MSXML2.ServerXMLHTTP")
httpRequest.open "POST", "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0", false
httpRequest.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpRequest.send postBody
Response.Write (httpRequest.responseText)
%>
I am not sure how to do this in GAS (I am an amateur programmer really...). From googling it seems that I will need to use something like "UrlFetchApp.fetch". Any help or relevant links would be appreciated. Thanks in advance.
The function below creates a properly formatted POST. Without valid credentials, I can confirm that it gets a 200 OK HTTP response, and the server reports 23|invalid credentials (username was: your_username)|. So it looks like it should work, with the right details filled in.
I've included application/x-www-form-urlencoded for the contentType, although this is not needed because it's the default.
If you get this working with a set of test values, then the next step would be to change it to accept and use parameters - I'll leave that to you.
/*
* Sends an HTTP POST to provider, to send a SMS.
*
* #param {tbd} paramName To be determined.
*
* #return {object} Results of POST, as an object. Result.rc is the
* HTTP result, an integer, and Result.serverResponse
* is the SMS Server response, a string.
*/
function sendSMS() {
var url = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0";
var username = "your_username";
var password = "your_password";
var recipient = "44123123123";
var message = "This is a test SMS from ASP";
var postBody = {
"username" : encodeURIComponent(username),
"password" : encodeURIComponent(password),
"msisdn" : encodeURIComponent(recipient),
"message" : encodeURIComponent(message)
};
var options =
{
"method" : "post",
"contentType" : "application/x-www-form-urlencoded",
"payload" : postBody
};
// Fetch the data and collect results.
var result = UrlFetchApp.fetch(url,options);
var rc = result.getResponseCode(); // HTTP Response code, e.g. 200 (Ok)
var serverResponse = result.getContentText(); // SMS Server response, e.g. Invalid Credentials
debugger; // Pause if running in debugger
return({"rc" : rc, "serverResponse" : serverResponse});
}
References
Google Apps Script documentation for UrlFetchApp and HTTPResponse
When are you supposed to use escape instead of encodeURI / encodeURIComponent?