I would like to create a link that could POST data.
Actually, I have a front in vuejs and a backend in rails.
I already have my own authentication system with Devise gem.
And I would like a user (who is already logged in) to be able to connect to other omniauth services (github, google...).
The problem is that as soon as I go on the link /auth/github (for example) my backend tells me that I didn't send the user's authentication token because i don't know how to send it.
That's why I would like to send datas (here, the auth token) directly from the link
Thanks
Like #Eyeslandic pointed out, your title is misleading, you have an OAuth or OAuth2 problem not a link problem.
If I can guess correctly you are getting a Get response (the token is in the link) and you want it to be a post response (the token in the request body) ... Are you using passport.js ? Must be a matter of configuration.
There is nothing wrong with receiving the token in the link, OAuth protocols are secure enough, whether it's a Get or a Post response.
If you want to read the token from the link, check this answer.
login.get('/p', function(req, res) {
const token = req.query.theReturnedTokenNameInTheLink
res.send("My token is " + token);
});
And the token is just a key that give you access to the host (github, google, facebook ...) Api, you should make another request to those API's, in order to get the user data, you could use a library like passport.js to simplify things, here is one of the tutorials, I found on how to use passport.js
Good luck.
Related
We have an inquiry from our client, to enable Autodesk Model Viewer from within our App. The first step is to implement OAuth2 authentication (2 legged). I followed Forge Autodesk tutorials, but this is completely new to me, and I cannot configure that to work. I do http request (using jQuery) from our App, passing client_id and client_secret, grant_type and a scope. When looking on the developer menu (F12) - I can see that request is hitting their server and returns with the access_token, expire time, authorization "Bearer" with the status 200. So far so good.
I understand that now I need to make a call back to the API and pass this access_token I received. And here is where I lost: console shows me error, Cross origin ... And the success part of http request is not fireing (in http request success part I'm trying to redirect user to the Model Viewer url + access_token we just received). But it is never fires. Was digging forums and tutorials but can't find any good sample or explanation what I'm doing wrong. Below is my code example:
$.post("https://developer.api.autodesk.com/authentication/v1/authenticate",
{
client_id: 'here_is_a_client_id',
client_secret: 'here_is_a_client_secret',
grant_type: 'client_credentials',
scope: 'viewables:read'
},
function(data, status){
console.log("Data: " + data);
window.location.href = 'https://viewer.autodesk.com/id/here_is_a_long_id_number&Authorization=Bearer&' + data;
});
Any help highly appreciated. Also, I was trying to follow Autodesk tutorials using Node.js, but again, after seeing that access_token get back from their server, can't make a callback and attach this access_token to it. New to all these Authorization/Authentication/Tokens so can't figure out the way it works. Thanks in advance.
I could advice you how to avoid this Cross Origin error, but it is critical not to and very dangerous to authorise your application on the client side. Exposing you client secret key will give everyone the right to access your account and spend cloud credits on your behalf. And access all your content. That is the reason you do should not have that approach.
You should never expose the client secret, neither an read/write scoped access token on a client, those should resides on the server, and server only. The only access token you could eventually see on the client should be a viewables:read scoped token only. And even when using a viewables:read token, I prefer to use a proxy instead myself (see here).
I don't understand the use of JWT token..
Can anyone explain it to me ?
Because currently i'm working on an app (rails + react), and I want to use devise + jwt for authentification and React for frontend.
Actually, I understood that :
1/ If a user want to login: he completes the form, React get Data from form and make a post request of these infos to Rails API.
2/ Rails API get theses infos check in the db if infos match with a registered user, if it is then Rails API will create a JWT token and will send this token to React.
User is now logged in because Rails API found a matched user.
3/ React receive the JWT token. ( ?? what the usage of this token ?? )
thanks
My response is not specific to Rails/React, but rather to all web technologies using JWT tokens:
What you said is correct. From point 3 forward, all the requests made from React to the Rails backend will have to contain the header Authorization: Bearer <token>.
When Rails sees that header, it is able to:
checks the token is valid, by checking its signature
decode it and extract any info stored in it.
Remember that JWT tokens can contain any info the backend wants to store in it. And the client is not able to tamper it, because it is signed cryptographically and it would invalidate its signature.
The above properties (the fact you can store anything in it, that the frontend sends it with every request and that nobody can tamper it) help any web application being able to:
have a shared nothing architecture - because the session is stored completely on the UI, so any backend worker/machine can handle any request
store more info in the session than if they'd use signed cookies for sessions.
Since you are return api . And react is consuming it.
Jwt help to return data you might need to persist in your frontend in react tho. Data like user name or email.
Example : making the header of your website show a user is logged in.
Since you are return api . And react is consuming it.
Jwt help to return data you might need to persist in your frontend in react tho. Data like user name or email.
Example : making the header of your website show a user is logged in.
The main aim of jwt in frontend is basically auth.
Apart .
If you are using a monolith app u deal with session for user
In react case jwt stands in as the session
The main aim of jwt in frontend is basically auth or other.
Apart . If you are using a monolith app remeber u deal with session for user In react case jwt stands in as the session
This question is for anyone who is familiar with
Node.js
Express
Passport
JWT Authentication with passport (JSON Web Tokens)
Facebook OAuth2.0 OR Google OAuth2.0
I have been doing some online courses and understand how to do the two following things:
Authentication using Passport Local Strategy + JWT Tokens
Authentication using Passport Google/Facebook Strategy + Cookie/sessions.
I am trying to combine the content from these two courses basically. I want to use Google Strategy + JWT Authentication. I want to use JWT instead of cookies because my app is going to be a web/mobile/tablet app, and I need to be accessing the api from different domains.
There are two issues I am having with this:
To kick off the Google/facebook OAuth pipelines, you need to call either '/auth/facebook' or '/auth/google'. Both Oauth flows work basically the same so when I say '/auth/google' from now on, I am referring to either. Now the issue I'm having is: On the client, do I call the '/auth/google' route with a href button link or an axios/ajax call? If I use the href or axios/ajax approach I am still getting problems with both solutions.
The href approach problem:
When I assign an <a> tag with a href to '/auth/google' the authentication works perfectly fine. The user gets pushed through the Google Auth flow, they log in and the '/auth/google/callback' route gets called. The problem I have now is how do I correctly send the JWT token back to the client from '/auth/google/callback'?
After a lot of googling I have seen that people have simply passed the the JWT back to the client from the oauth callback in the redirect query param. For example:
res.redirect(301, `/dashboard?token=${tokenForUser(req.user)}`);
The issue I have with this is that now the the ability to authenticate is saved in my browser history! I could log out (destroying the token saved in localStorage), and then simply look at my browser url history, go back to the url that contains the token in the query param, and I would automatically log in again without having to go through the Google Strategy! This is a huge security flaw and is obviously the incorrect way to approach it.
The axios/ajax approach problem:
Now before I explain the problem with this issue, I know for sure that If I get this working, it will solve all issues I was having with the previous href problem. If I manage to call '/google/auth' from an axios.get() call and receive the JWT in the response body, I will not be sending the token as url param, and it will not get saved in the browser history! Perfect right? well there is still some problems with this approach :(
When try to call axios.get('/auth/google') I get the following error:
How I've tried to solve the problem:
I installed cors to my npm server, and added app.use(cors()); to my index.js.
I took a stab and added "http://localhost:3000" to the "Authorised JavaScript origins" in Google developer console.
Neither of these solutions solved the issue, so now I really feel stuck. I want to use the axios/ajax approach, but I'm not sure how to get past this cors error.
Sorry for such a long message, but I really felt I had to give you all the information in order for you to properly help me.
Thanks again, looking forward to hear from you!
I solved this in this way:
On Front-End (can be mobile app) I made login request to Google (or Facebook) and after the user selected his account and logged in I got back response that contained google auth token and basic user info.
Then I sent that google auth token to backend where my API sent one more request to the Google API to confirm that token. (See step 5)
After successful request comes you get basic user info and e-mail. At this point, you can assume that user login via Google is good since google check returned that it's okay.
Then you just signup or login user with that email and create that JWT token.
Return token to your client and just use it for future requests.
I hope it helps. I implemented this multiple times and it showed like a good solution.
Though there is good answer, I wanted to add more information with example.
Passport's google/facebook strategy is session based, it stores user info in cookie which is not advisable. So we need to disable it first
To disable session we need modify our redirect router. For example if we have redirect path /google/redirect like following, we need to pass { session: false } object as parameter.
router.get('/google/redirect', passport.authenticate('google', { session: false }), (req, res)=> {
console.log(":::::::::: user in the redirect", req.user);
//GENERATE JWT TOKEN USING USER
res.send(TOKEN);
})
So where does this user come from? This user comes from passport's callback function. In the previous snippet we have added passport.authenticate(....) This middlewire initiates passport's google-strategy's callback which deals with the user. For example
passport.use(
new GoogleStrategy({
callbackURL: '/google/redirect',
clientID: YOUR_GOOGLE_CLIENT_ID
clientSecret: YOUR_GOOGLE_SECRET_KEY
},
(accessToken, refreshToken, profile, done)=>{
console.log('passport callback function fired');
// FETCH USER FROM DB, IF DOESN'T EXIST CREATE ONE
done(null, user);
})
)
That's it. We have successfully combined JWT and Google/Facebook Strategy.
The solution I found was to do the OAuth flow in a pop-up (window.open), that makes use of a pre-defined callback to pass the token to the front-end upon successful authentication.
Below are the relevant code samples, taken from this tutorial:
https://www.sitepoint.com/spa-social-login-google-facebook/
Here is the pre-defined callback and initial open method, called from your front-end:
window.authenticateCallback = function(token) {
accessToken = token;
};
window.open('/api/authentication/' + provider + '/start');
And here is what your OAuth Callback URL should return, upon successful authentication (which is the last step/page inside your pop-up):
<!-- src/public/authenticated.html -->
<!DOCTYPE html>
<html>
<head>
<title>Authenticated</title>
</head>
<body>
Authenticated successfully.
<script type="text/javascript">
window.opener.authenticateCallback('{{token}}');
window.close();
</script>
</body>
</html>
Your token would now be available to your front-end's pre-defined callback function, where you could easily save it in localStorage.
I suppose though, you could do the OAuth flow in the same window then (sans pop-up) and return an HTML page (similar to the above) that just saves the token and redirects the user to a dashboard immediately.
If your front-end domain was different from your api/auth server, however, you would probably need to redirect from your api/auth server to your front-end with a single-use, time-sensitive token (generated by your api/auth server), that your front-end could then use to call and receive (with axios) your actual token. This way you wouldn't have that browser history security problem.
I have a Rails 5 API only app and an Angular JS Frontend app and would like to integrate with Asana API. I'm using the ruby-asana, omniauth and omniauth-asana gems.
I start the request using Asana's JS library like so:
var client = Asana.Client.create({
clientId: 172706773623703,
clientSecret: '<client_secret>',
redirectUri: '<redirect_url>'
});
client.useOauth({
flowType: Asana.auth.PopFlow
});
And the above does redirect me to Asana where I can login. On the redirectUri I'm giving a backend route (Rails 5 API only) which should handle the remaining on the authentication (using the JS only I get only a temporary token that cannot be self renewed meaning the user will have to authenticate every time the token expires. This is if I understood the documentation correctly).
So, on the controller I've created to handle the route, I have the following (from an example on Asana's documentation):
require 'omniauth-asana'
use OmniAuth::Strategies::Asana, <secret>, <secret>
creds = request.env["omniauth.auth"]["credentials"].tap { |h| h.delete('expires') }
strategy = request.env["omniauth.strategy"]
access_token = OAuth2::AccessToken.from_hash(strategy.client, creds).refresh!
$client = Asana::Client.new do |c|
c.authentication :oauth2, access_token
end
Now, the above doesn't work because 1) there's no request.env as this is an API only app, so I've followed the instruction on Omniauth and have added the following to my config/application.rb:
config.session_store :cookie_store, key: '_interslice_session'
config.middleware.use ActionDispatch::Cookies # Required for all session management
config.middleware.use ActionDispatch::Session::CookieStore, config.session_options
Now, in the request.headers I have _interslice_session which has some numbers. How can I create a Asana client with the above?
Any ideas?
OK, I think I see what you're attempting to do here; I think the best way forward is to start with how OAuth's Authorization Code Grant happens in general, then move into specifics for OmniAuth.
You send the user to a URL that Asana owns; that is, your goal is to get the user to visit a particular url. For Asana, this is https://app.asana.com/-/oauth_authorize. (Note that we respond with an error if you don't sent a correct client_id param, but feel free to check that link if you want). Do not send the client_secret during this request - it is intended to never be involved in client-side code, as this is insecure.
If they agree to give access, Asana sends back a redirect request to the user's browser with a short-lived code. That then means that your server will be called from the user's browser with this code as a parameter, so has to handle a new incoming request from the browser to whatever you specified as your redirect URI. Also, this location must be accessible by all users of your integration wherever they are.
You send this code from your server as a POST request to https://app.asana.com/-/oauth_token with your client_secret to Asana for a refresh token. This is where your application actually asks for credentials; the token given in the previous phases simply acknowledges that for a short time, the user has given your app permission to ask for these credentials, and your client_secret assures Asana that, for this server-side request, your app really is yours (it's like your application's password).
We send back an access_token which represents (approximately) a client-user credential pair that is valid for an hour.
You use these credentials to access our API on behalf of this user. We also send back a refresh_token which is long-lived, and used to get new short-lived access_tokens after they expire in a very similar way.
OK, so how this works with OmniAuth if I grok it correctly is that it expects to handle almost all of it. I'll be working through our omniauth example in our ruby-asana client library here: https://github.com/Asana/ruby-asana/blob/master/examples/omniauth_integration.rb
You set up OmniAuth with your client id and client secret
use OmniAuth::Strategies::Asana, <client_id>, <client_secret>
A request comes in, and you don't have credentials for it.
get '/' do
if $client
...
else
'sign in to asana'
end
end
The user clicks the sign in link, which (code omitted) sends them to the sign_in endpoint. This endpoint issues a redirect to /auth/asana
The browser requests /auth/asana from our server. If you look at that example, it's not implemented in our code. That's because the /auth/:provider is magically handled by OmniAuth.
This is where all the magic happens. OmniAuth handles the entire login flow above: send browser to our oauth_authorize above, then receive the callback and sticks the relevant params in the environment such that it knows "we just got the short lived code". By the time these lines get hit:
creds = request.env["omniauth.auth"]["credentials"].tap { |h| h.delete('expires') }
strategy = request.env["omniauth.strategy"]
you are inside a callback that OmniAuth has intercepted, gotten the needed creds, and set the creds in the environment. You shouldn't have to handle the oauth callback and token exchange manually.
Now, with the code you provided, I notice a few things right off:
You are causing the popup cycle to happen client side. It may be (and I strongly suspect) that this won't work with OmniAuth - it expects to handle the whole OAuth flow.
Based on the code snippet you provided, you aren't serving this out of a request-response cycle in the controller, rather, it appears that this is in the controller body and not out of an instance method. It may be a typo, but this needs to be in a method that is called back to outside of Rails (that is, a route must point to this a controller method that Asana can use to handle the browser request).
You shouldn't have to look at request.headers, I think - I'm not sure what the issues might be with request.env, but I suspect they may be unrelated to the API-only nature of your app. Are you sure that this is because it's API-only? After adding in the middleware, did you double-check that you can't access request.env? My hunch would be that persistent data in request.env will still be there, only it would require on the middleware being added in to do this. The instructions on OmniAuth simply say that you need to have a session store for your API - which makes sense to me, because APIs don't necessarily need to store state across requests, OmniAuth is telling you to put a session store back in.
I know this is a lot of info, but hopefully it helps you get on the right track. Cheers!
I have been trying with the simple REST Client as well as the REST Plugin for Mozilla. I am getting
"HTTP/1.1 401 Unauthorized" response with
"{"error":"unauthorized_client","error_description":"the client is not authorized"}" in the body.
I have been successful in getting the auth code, and the below is the POST request for access token, (Scope is r_fullprofile)
https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=AQTQeBxBzbU2aNWaQM6Ff3Z3bUd8Gyg10W9G2DdqXgWiP0q7-M55c5PLtppP7Ni3Y-6A9C8yDkj9K4VfJ7QkRUFjuV-3AknA5jAahpsFJv3wYfr8XD8&redirect_uri=https://www.google.com&client_id=75wl6j5zndvfkp&client_secret=secret
The redirect_uri=https://www.google.com is the one used for getting auth code as well.
Do we need to perform any URL encoding before making the POST request?
When I log into the linked in to my app, it has the below tokens,
OAuth User Token: c3ae4cee-1b23-xxx-9d2a-206f578dee4d
OAuth User Secret: 76bc48cc-c94f-xxx-bf9d-a663f7003383
I am not sure where it is used. we are using API & secret key to get auth code.
Thanks in Advance.
This is a 2-step process.
First, go to:
https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=YOUR-API-ID&scope=r_basicprofile&state=STATE&redirect_uri=YOUR-ENCODED-REDIRECT-URI
Then, within 10 secs of receiving the response, go to:
https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&redirect_uri=YOUR-ENCODED-REDIRECT-URI&client_id=YOUR-API-ID&client_secret=YOUR-API-ID&code=THE-CODE-OBTAINED-IN-FIRST-STEP
The response of the second request will have the actual access token you need to use.
When I followed the two steps I faced an issue where I got an error as
{"errorCode":0,"message":"Access to posting shares denied","requestId":"TYWULO2WPZ","status":403,"timestamp":1497353538016}
So I had to remove the &scope=r_basicprofile since it was preventing reading all the Default Application Permissions
I faced a similar problem and the problem was with the initial authorization code. You should mention the scope=rw_company_admin or whatever it is that you want to authorize to while doing the initial redirect URL call. Something like this -
https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=your_client_id&redirect_uri=https%3A%2F%2Fwww.google.com/&state=12345&scope=rw_company_admin%20r_emailaddress%20w_share%20r_basicprofile