Issue in binding social accounts with local account in web app - javascript

App description:
User can sign up with credentials and get authorization and refresh token from a server, they're saved respectively in session and local storage. Axios is configured to intercept 401 status response and then make a new request to separete endpoint with refresh token as a payload. Server verify refresh token and respond with new authorization token that is set as a default header to every axios request. User can also login with social accounts (fb, g+, github) which are implemented using passport lib.
Task description:
As a logged user I can connect my current account with my social account. This case is included in passport documentation.
Problem description:
Requests to route specified in documentation:
app.get('/connect/twitter',
passport.authorize('twitter-authz', { failureRedirect: '/account' })
);
can be done only by redirection with <a href='/connect/twitter'>,
XMLHttpRequest is not possible due to CORS error (eg. example). And this is a problem, I can't send auth token using simple redirection so server can't decode token and get local user info and so can't add updated user data (with social account data) to database..
Source code
Http address
PS. Sorry for bad english, I will appreciate any help!

Related

automatic login google for Youtube API with email & password from setting

note : i have only 1 account gmail / channel
im creating page index.html for upload video to youtube with this ref : https://developers.google.com/youtube/v3/code_samples/javascript .
and running well ..
and the problem is : before uploading video , i must login google for auth .. which is the account is based from my browser ..
question : i need auto login / set email + password. (no prompt from google , because i wanna setting this for upload into 1 same channel / 1 account gmail) for index.html.
so, if PC-A , PC-B or PC-C , access http://example.com/index.html .. they can upload video without login with their accounts.
Thanks.
For offline access, you can setup a backend server accessible from PC-A, PC-B & PC-C which will store a refresh_token with the scope https://www.googleapis.com/auth/youtube, check this documentation about OAuth2.0 for Web server. You can test with Oauth 2.0 Playground.
This refresh token will be used to request a new access token. With this access token, you can request Google API such as upload video depending on the scope you specified (in this case https://www.googleapis.com/auth/youtube)
Then, you will have 2 options :
the client request an access token, the server generates one, and send the access token back to the client browser so that it performs request in client side
the client upload video to your server, the server generates an access token (or reuse one) and make the Google API request from server side
Note that the access token periodically expires, when an access token becomes invalid (eg call return status code 401), you have to refresh it, see this

JWT: handling token auth on a multi-domain-level

Currently I'm facing the following problem:
I'm building an application with a standalone login view.
Let's assume they both run on different domains. My login view communicates with a REST service on the server that issues a JWT token.
With this issued token the user should now be able to view (be forwarded to) the application. But this application - as mentioned - runs on another domain (or subdomain, maybe).
In my mind I tried the following:
Token is issued by the server. A hash is stored in a database and the hash is issued to the user. The hash is transferred to the application via URL and the applications checks the hash.
Token is issued by the server. The token is transferred to the user. When the user now opens the application (or is forwarded to...) the token should be transferred there, too. I have no clue how to do...
Both are not ideal ways, i know. But I really don't know how I can achieve that...
I hope anyone is able to help me with my thinkings?
If anything is unclear, just comment.
Thanks in advance!
Facebook, Twitter, Google, etc. offer OAuth by redirecting (302 Redirect Request). Basically your app starts if user has a valid token everything is fine, else it will open the Login-Page from the Identity Provider (e.g. Google) and return the token, if the login was successful.
This graphic shows the general steps:
https://www.soapui.org/soapui/media/images/stories/oauth2/oauth2flow.png
Hope this helps.
Lets assume you have two services in 2 different domains. One is your identity provider which generates tokens and holds the token <--> user assignment (we call it: idp.my.company). The other one is any application that does stuff but needs to login via idp.my.company (we call it app.my.company).
You have two scenarios:
1. Login without having a token aquired before.
2. Login with token.
Request GET: app.my.company
Response 302: Moved to: idp.my.company
Take a look which redirection type follows your needs (307 maybe)
https://en.wikipedia.org/wiki/URL_redirection
You need to add an information where to redirect back. In this case app.my.company.
[This happens automatically because of the Redirect] GET: idp.my.company/login.html.
Response 200 OK: idp.my.company/login.html
The User will now see the Login-Page of your IDP-Service and perform a Login.
Request POST: idp.my.company/login.html (or whatever)
The User posts his credentials to aquire a token
Response 302 Redirect: If login is successful, return token and now redirect to the origin site (app.my.company) which you provided earlier.
Request GET: app.my.company/afterlogin.html
The header contains a valid token
Response 200 Ok: Now the app.my.company service needs to check if the token is valid and if true return 200 Ok otherwise redirect again to IDP (start over at step 2).
This should be it. There could be errors but you should have a consistent picture of the process and get a grasp on how to implement it. Those steps cover scenario 1 and 2.

Facebook Same Window Authentication

I am trying to do Facebook authentication in same window of my web application's login page.
I am using following code when user clicked login button to go to authentication page.
function loginUsingOAUTH()
{
top.location = 'https://graph.facebook.com/oauth/authorize?client_id=839846246064537&scope=email&redirect_uri=http://www.olcayertas.com/testqa/result.html';
}
1) After authentication Facebook redirects me to my redirect url and returns a parameter "code".
At this point I want to access Facebook user information but I don't know how to do that.
What is this "code" parameter for?
2) Is there any other way to access user information?
3) Do you have any other advice facebook authentication with same window login?
Thank you in advance for your help
When you get the code you should make a server side request to get an access token and than pass the access token to user. It is explained in Facebook Developer page:
Exchanging code for an access token
To get an access token, make an HTTP GET request to the following
OAuth endpoint:
GET https://graph.facebook.com/v2.3/oauth/access_token?
client_id={app-id}
&redirect_uri={redirect-uri}
&client_secret={app-secret}
&code={code-parameter}
This endpoint has some required parameters:
client_id. Your app's IDs
redirect_uri. This argument is required and must be the same as the original request_uri that you used when starting the OAuth login
process.
client_secret. Your unique app secret, shown on the App Dashboard. This app secret should never be included in client-side code or in
binaries that could be decompiled. It is extremely important that it
remains completely secret as it is the core of the security of your
app and all the people using it.
code. The parameter received from the Login Dialog redirect above.
Response
The response you will receive from this endpoint will be returned in
JSON format and, if successful, is
{“access_token”: <access-token>, “token_type”:<type>, “expires_in”:<seconds-til-expiration>}
If it is not successful, you will receive an explanatory error
message.

Token based authorization in nodejs/ExpressJs and Angular(Single Page Application)

In my application,while registering the users i am saving username,password and jwt generated token with these fields in MONGO DB.When user tries to login with correct credentials then i will send the response with stored token.Then at client side(In my controller) i am using the localstorage to store the token so that i can send the same token for each and every request sent by the client.But I found some issues regarding this procedure:
I am generating same token for one user every time.So if any third person is able to get the token then he can access the restricted page.
Am i wasting space in db by storing the generated token in MONGODB
Can Anyone access the token stored in localstorage other than the user.
for each and every request in my single page application,I am again querying mongodb to get the token for that user and validating.Here,I am checking both client side and server side.
I am using jwt to generate tokens,Node,Express,Mongoose in my application
Am i following the good procedure.If not,can you please provide the solution for my approach or any new approach.
I have searched many sites for token based authorization and session based authorization,But nothing worked for me.
Note:I am beginner for Nodejs,AngularjS
You should store token in advanced key-value cache tool like: Redis
That would improve performance remarkably.
You will get token from database for 1st time then it should be stored in Redis. I used to set token as key and username as value. Next request , the token will be given from cache. with Redis you can set expire for token.
When a user registers, you would need to generate a JWT like you're doing now. That's OK. You don't need to save it to the database however. You didn't ask but I assume that the password should not be stored in clear text. You can use something bcrypt to encrypt before saving it to the database.
When user tries to login with correct credentials then i will send the response with stored token
Yes, that's correct way to do.
Then at client side(In my controller) i am using the localstorage to store the token so that i can send the same token for each and every request sent by the client.
Yes, on the client side, you can save the JWT to local storage and send it in subsequent requests to the server.
Now your bullet points:
So that you won't have the same JWT each time, you can include an "exp" claim in the payload (I'm assuming you're using something like jwt-simple to generate a JWT). Something like:
var payload = {
sub: account.username,
exp: moment().add(10, 'days').unix()
};
var token = jwt.encode(payload, "secret");
You don't need to store the JWTs in the database. In some cases, the token issuers (the authorization servers) are not the same as the resource servers. The resource servers only receives the JWTs in a request but there's no way for the resource servers to touch the database used by the authorization servers. Side note: If you eventually need to support refresh tokens, i.e. the JWTs that you hand to the clients will need to eventually expire, then you can store the refresh token in a database. Refresh tokens are not the same as JWTs (access tokens). The complexity to support refresh tokens will increase.
Local storage is not where you store passwords, but it can be used to store JWTs. For that very reason, a JWT must and should expire after a certain time.
Not sure what you mean by saying you check both client side and server side. When the client needs to access a resource (again it's fair to assume that the resource server might not be the same as the authorization server), the only thing that the resource server is passed is the JWT. Anyone can decode a JWT. For example, try to paste your JWT on this site http://jwt.io/. That's why a JWT should not contain any sensitive data. But if the resource server knows the secret that the authorization server uses when it encode the JWT, the resource server can verify the signature. Back to your third bullet, that's why it's OK to store the JWT in local storage of the client.
Update I'm updating this to answer to some of your questions in the comment box.
User clicks on 'Login' button triggers the Angular controller to post a request to the server, something like:
$http.post(url, {
username: $scope.username,
password: $scope.password
}).success(function(res) { ... })
Server receives the POST request, it checks username/password, then it generates a JWT, and sends back to the browser. Note that it does not have to save the JWT to the database. The code would be something like
var payload = {
sub: account.username,
exp: moment().add(10, 'days').unix()
};
var token = jwt.encode(payload, "secret");
res.status(200).json({
token: token
});
Back on the client side, in the success() callback above, now you can save the JWT in local storage:
.success(function(res) { $window.localStorage.setItem('accessJWT', res.token) })
The user is now authenticated. Now when user wants to access a protected resource, user don't have to provide username/password. With the JWT which can be retrieved from local storage, the client can now put the JWT in the Authorization header of the request using the bearer scheme, and sends the request to the server. In code, it would like:
headers.Authorization = 'Bearer ' + token;
The server receives the request. Again, this server receiving this request does not have to be the same as the server which generates the JWT above. The 2 servers can be in 2 different continents. Even if you save the JWT above, that does not do any good to this server which can not access the database where the JWT is stored. But this server can pull out the bearer token from the header of the request, validates the token and carries on with the normal tasks.
Hope this helps.
You do not want to store the JWT in mongoose because it appears in headers when logging in. You first generate a token then hash it using a module like crypto.
There are different ways to do this and they all use Passport which handles the tokens. Here's an example project Satellizer
I would recommend you generate the angular-fullstack project. Then go through the server/auth folder and the client/account folder. You will see how to securely handle authentication in a MEAN based app.

Facebook login with Parse client site, use user object with Express js

I am trying to create a login procedure with the Parse and Facebook Javascript SDK. The authentication works without a problem on the client side, but I need to access the user object (created by Parse SDK) on the server side too. How can I do this the most elegant way? I thought when I log in into Facebook via Parse a cookie is set and so I can access the user object from the server. Or should I do the login process server side? Any recommendations?
I'm facing the same problem. Turns out that you can use either server-side auth or client-side auth. You cannot mix-and-match the two. Have a look at their official blog post about sessions.
var parseExpressCookieSession = require('parse-express-cookie-session');
// In your middleware setup...
app.use(express.cookieParser('YOUR_SIGNING_SECRET'));
app.use(parseExpressCookieSession({ cookie: { maxAge: 3600000 } }));
// Making a "login" endpoint is SOOOOOOOO easy.
app.post("/login", function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function() {
// Login succeeded, redirect to homepage.
// parseExpressCookieSession will automatically set cookie.
res.redirect('/');
},
function(error) {
// Login failed, redirect back to login form.
res.redirect("/login");
});
});
Also, I came across this when digging through the doc:
You can add Parse.User authentication and session management to your
Express app using the parseExpressCookieSession middleware. You just
need to call Parse.User.logIn() in Cloud Code, and this middleware
will automatically manage the user session for you.
You can use a web form to ask for the user's login credentials, and
log in the user in Cloud Code when you receive data from this form.
After you call Parse.User.logIn(), this middleware will automatically
set a cookie in the user's browser. During subsequent HTTP requests
from the same browser, this middleware will use this cookie to
automatically set the current user in Cloud Code.
...
When you work with user data, you should use HTTPS whenever possible.
To protect your app and your users, the parseExpressCookieSession
middleware requires you to use HTTPS. For your convenience, we also
provide a parseExpressHttpsRedirect middleware for redirecting all
HTTP requests to HTTPS.

Categories

Resources