Autodesk-forge viewer: Access token - oauth

I was following forge tutorials to embed the forge viewer in an html page.
I ended up at this forge-made page, link: https://autodesk-forge.github.io/forge-tutorial-postman/display_svf.html
I understand how to retrieve an access token using cURL however I would like to modify that website so that I don't have to enter the access token myself.
I would like the access-token from the cURL response to be automatically imported as the access token for that website. How is this possible.
The code for the webpage is here: https://github.com/Autodesk-Forge/forge-tutorial-postman/blob/master/docs/display_svf.html
How can I add a function/method to automatically retrieve an access token when I hit submit on the webpage.
Any help is much appeciated!
Cheers!

The server side code you are looking for is:
app.get('/api/forge/oauth', function (req, res) {
Axios({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
data: querystring.stringify({
client_id: FORGE_CLIENT_ID,
client_secret: FORGE_CLIENT_SECRET,
grant_type: 'client_credentials',
scope: scopes
})
})
.then(function (response) {
// Success
access_token = response.data.access_token;
console.log(response);
res.send('<p>Authentication success!</p>');
})
.catch(function (error) {
// Failed
console.log(error);
res.send('Failed to authenticate');
});
});
Please refer the Forge 2-Legged Authentication tutorials for the code and more details. We also have more tutorials and workflow on Learn Autodesk Forge.

Related

Using Oauth 2.0 with Next js

I want to use Google OAuth 2.0 with my React/Next.js app. I've set up my OAuth Client IDs on the Google Developer console, and set up a route in my server.js node file. When I try to GET request https://localhost:3000/auth/google I get the Next js 404 Not Found page. It's obviously looking for a page called auth in my Next js pages directory. Tried using the next/Router, wrapping my button in an anchor element, fetch API GET requesting https://localhost:3000/auth/google, all failed.
I've managed to successfully implement passport user authentication, salting, hashing and sessions but it's just the Oauth that's giving me trouble.
If it were a standard node application https://localhost:3000/auth/google would redirect to the interface where users could login with their google credentials.
I've tried search the nextjs examples github for implementations of oauth but there doesn't seem to be any. Anyone know how I can use OAuth 2.0 with Next JS?
Route
server.get("/auth/google", (req, res) =>{
passport.authenticate("google", { scope: ['profile']});
})
Button that's supposed to take me to the google login/register page
<button className="btn btn-block btn-social btn-google" style={{'color': '#fff'}} onClick={() => Router.push("/auth/google")}>
<FontAwesomeIcon icon={faGoogle} className="google-social-button" /> Sign Up with Google
</button>
You can simply try this,
const app = next({ dev });
const server = express()
server.get('/auth/google/callback*',
passport.authenticate('google'),
(req, res) => {
res.redirect('/dashboard');
});
server.get('/auth/google*', (req, res) => {
return app.render(req, res, req.path, req.query)
});
server.get('/api/logout', (req, res) => {
req.logout();
res.send(req.user);
})
server.get('/api/current_user', (req, res) => {
res.send(req.user);
});
server.get('*', (req, res) => {
return handle(req, res)
});
Just make sure the google reqs are above the server.get('*') route as it catches all requests.
More help: https://github.com/zeit/next.js/blob/canary/examples/custom-server-express/server.js
Not sure if you're still looking for an answer here, but if are, you can do something like the following under the latest Next.js version (9+), https://nextjs.org/blog/next-9#api-routes
//--- PART 1: DEFINE YOUR GOOGLE OAUTH STRATEGY ALA PASSPORT
// This would be in its own passport.js file (the filename doesn't matter), the key thing being that you define your Google Strategy
import passport from 'passport'
import {
Strategy as GoogleStrategy,
} from 'passport-google-oauth20'
passport.use(new GoogleStrategy({
...getGoogleKeySecret(), // a utility for grabbing your secret keys
callbackURL: `/api/authorize/google/callback`,
passReqToCallback: true, // http://www.passportjs.org/docs/authorize/
}, async function(req, accessToken, refreshToken, profile, done) {
// Do any user lookup/mapping you need here
return done(null, profile)
}))
//--- PART 2: DEFINE THE END-POINT
// This would be in your pages/api/auth/google.js file
import nextConnect from 'next-connect'
import middleware from '../any/custom/middleware/stuff/you/may/have'
const handler = nextConnect()
handler.use(middleware)
handler.get(passport.authenticate("google", {
scope: ['profile', 'email', 'openid'], // tailer the scope to fit your needs
}))
export default handler
To try it out, direct a user to /api/auth/google via your UI or hit the URL directly, and you should be taken through the Google OAuth 2.0 flow.
Hope this helps - good luck!

invalid_grant on OAuth2 request when obtaining access_token from SSO in App

I have an iOS App with an Uber API integration where I use SSO to authenticate the user and then save the accessToken & refreshToken locally on my device. Then I'm calling my server who uses a javascript background function to call the node-uber (https://www.npmjs.com/package/node-uber) library to make a request to Uber.
So far, I'm trying to set up the uber client with my 2 local tokens from the SSO login like this:
var uber = new uberClient({
client_id: '...',
client_secret: '...',
server_token: '...',
name: 'My App',
sandbox: true, //optional
access_token: accessToken,
refresh_token: refreshToken
});
afterwards I want to call the uber.requests.getEstimatesAsync endpoint like this:
uber.requests.getEstimatesAsync({
"start_latitude": pickupLocation["lat"],
"start_longitude": pickupLocation["lng"],
"end_latitude": dropoffLocation["lat"],
"end_longitude": dropoffLocation["lng"]
})
.then(function(res) {
console.log(JSON.stringify(res));
})
.error(function(err) {
console.error(err);
});
})
Though every time I get an "invalid_grant" error 400 while doing this. Did I make a mistake authenticating myself or setting up the Uber client wrong? Is it even possible to use my SSO accessToken & refreshToken then on the uber client, which does a OAuth2 authentification? I thought that both access and refresh token should probably be the same what Uber sends back to be for SSO & OAuth2.
I'm using a Developer account for doing this, therefore I should actually have all the required permissions for the request endpoint, but I also obtained them previously in the App correctly.
This thread on the official uber documentation explains potential reasons but I guess they don't really apply to my case, do they? https://developer.uber.com/docs/riders/guides/authentication/introduction#common-problems-and-solutions
Any security expert here who can help?
Best regards,
Matt
P.S.: I also posted this question on the Uber library I'm using for making those requests, but nobody seems to be able to help me there so far. https://github.com/shernshiou/node-uber/issues/70
Edit: The following picture shows my authentication setup so far:
I found a solution. I think was a problem with the library itself. Because once I made the request with http with the "request" library (https://github.com/request/request) it worked. Include for that at the top of your code:
var request = require('request');
Both OAuth2 and SSO accessToken worked. You should give the method a pickupLocation with latitude and longitude and your obtained accessToken from Uber like this:
function getAllAvailableUberProducts(pickupLocation, accessToken){
var lat = pickupLocation["lat"].toString();
var lng = pickupLocation["lng"].toString();
var options = {
uri: "https://api.uber.com/v1.2/products?latitude="+lat+"&longitude="+lng,
method: 'GET',
headers: {
"Authorization": "Bearer " + accessToken,
"Accept-Language": "en_US",
"Content-Type": "application/json"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body).products);
} else {
console.log(error);
}
});
}
I hope this helps someone.

Dont understand Google Drive oAuth 2.0

I need oAuth2 on google drive . But i cant get token. Which parameters is wrong ? Google documentation API cant help me for understanding what is wrong .
I do fetch request.
const options = {
method: 'post',
client_id: '{EXAMPLE}deajshot.apps.googleusercontent.com',
redirect_uri: 'https://drive.google.com/open?id={EXAMPLE}',
scope: 'https://www.googleapis.com/auth/drive.metadata',
prompt: 'none',
mode: 'no-cors',
response_type: 'token'
};
fetch('https://accounts.google.com/o/oauth2/auth',options)
.then(function (response) {
console.log(response);
})
Now i have error - 400. That’s an error.
Error: invalid_request
Required parameter is missing: response_type;
By your code example , you first need to get a code and then request a access token.try to follow this tutorial: https://developers.google.com/identity/protocols/OpenIDConnect#authenticatingtheuser
You have there a request for example:
https://accounts.google.com/o/oauth2/v2/auth?
client_id=424911365001.apps.googleusercontent.com&
response_type=code&
scope=openid%20email&
redirect_uri=https://oauth2-login-demo.example.com/code&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oauth2-login-demo.example.com/myHome&
login_hint=jsmith#example.com&
openid.realm=example.com&
hd=example.com
After this , with your 'code' parameter you get you could make request to get a access token (you have there also a example of this request )
Good luck

Fetch API call with Zapier + Prosperworks

I'm trying to call the Prosperworks API through Code by Zapier. I can do this easy through curl, but for the life of me cannot get this POST call to work using fetch. Below is what I've got...any help appreciated. Thanks
fetch('https://api.prosperworks.com/developer_api/v1/people/fetch_by_email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-PW-AccessToken': 'API_TOKEN',
'X-PW-Application': 'developer_api',
'X-PW-UserEmail': 'EMAIL'
},
body: JSON.stringify({'email': input.email})
}).then(function(res) {
var people_id = res.id;
return res.json();
}).then(function(body) {
callback(null, {id: 1234, rawHTML: body});
}).catch(function(error) {
callback("error");
});
I'm the lead engineer on the ProsperWorks developer API. sideshowbarker is correct; we do not accept cross-origin requests from Zapier. Given that we offer Zapier integration, though, perhaps we should. I'll bring it up with the dev team and see if we can get that onto an upcoming release :)

Sencha Touch 2 & Spring Security cross-domain login

I need use API of some server from Sencha Touch 2 app . For using this API I need authenticate on server.
So I already implemented login functionality :
Ext.Ajax.request({
url: 'http://192.168.1.2:8080/spring-security-extjs-login/j_spring_security_check',
method: 'POST',
params: {
j_username: 'rod',
j_password: 'koala',
},
withCredentials: false,
useDefaultXhrHeader: false,
success: function(response){
var text = response.responseText;
Ext.Msg.alert("success", text, Ext.emptyFn);
},
failure: function(response){
var text = response.responseText;
Ext.Msg.alert('Error', text, Ext.emptyFn);
}
});
But how I can call API , because after authentication I try call API but they already want authentication. Probably I need save JSESSIONID and added it to another request, but I don't know how I can do it.
I can't use withCredentials: true , so I need to find another solution.
How I can get Set-Cookies from response HTTP Header ?
I see in Chrome console, that JSESSIONID present in response header , so , i need get it.
Please, help me find any solutions.
You can use requestcomplete & beforerequest events to read response headers and to write request headers respectively. Here is sample code :
Ext.Ajax.on('requestcomplete', function(conn, response, options, eOpts){
var respObj = Ext.JSON.decode(response.responseText);
Helper.setSessionId(options.headers['JSESSIONID']);
}, this);
Ext.Ajax.on('beforerequest', function(conn, options, eOptions){
options.headers['JSESSIONID'] = Helper.getSessionId();
}, this);

Resources