Recommendation stack for Restful + Spring Security + Mobile App - spring-security

I'm creating a mobile app and I would like to provide to the users the option to sign up/in using an email or via their facebook accounts.
I have read so many things in the last two days, but I still don't understand how to do it.
I have seen the example the following link, but it's a little bit confusing for me, and I would like to use Spring (boot) stack, with Java Annotation Configuration.
http://porterhead.blogspot.com.br/2013/01/writing-rest-services-in-java-part-4.html
The best example I found for rest authentication is this http://www.codesandnotes.be/2014/10/31/restful-authentication-using-spring-security-on-spring-boot-and-jquery-as-a-web-client/, but it is form based, which does not work for a mobile application.
The flow of the application in my head is:
Users try to access the app via Facebook (using mobile SDK);
Facebook returns a token, which is sent to my backend server;
Spring security checks if the token is valid. If it is valid, get the user's details (email, for example).
3.1. If that email is present in my database, logs the user in. Otherwise, create a new user.
The steps after that are a little bit obscure for me as well. After these checks, what should I return to the client? How do I validate its token for the following requests?
I've read a lot, but still cannot connect the dots. Any help will be really appreciated.
Thanks in advance!

Firstly when you are sending facebook-auth token to backend,it will checked by facebook library like spring-social,not by spring security. So just i am giving you a example of spring-social.
Facebook facebook = new FacebookTemplate(fbtoken, yourappname);
org.springframework.social.facebook.api.User facebookUser = facebook.userOperations().getUserProfile(); // throw exception if token is not authenticated
if(facebookUser.getId() != null){
return true;
}else{
throw new AuthenticationException(configProp.getProperty("invalid token"), HttpStatus.FORBIDDEN, HttpStatus.FORBIDDEN.value());
}
After verifying facebook auth token,you have to create a unique token for your app,you can create it by
String token = UUID.randomUUID().toString()
then this token you will save in database and return to client end. Further requests from client,you have send this token from client,and now this token it will be checked by spring security.
if(tokenValid){
//access your app
}else{
return "unauthorized user"
}
On logout you will delete it from database as well as from client side

Related

Passport & JWT & Google/Facebook Strategy - How do I combine JWT and Google/Facebook Strategy?

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.

Twitter access token and access token secret have been changed automatically?

So I was running my code which involves getting past tweets from a list of twitter users (i'm using application based authentication). I have been running it for around 2 days and now, it throws me an exception,
401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
I then found that the access token and access token secret for my application at https://apps.twitter.com/ has been changed. OAuth FAQ guide says "We do not currently expire access tokens" so I'm not sure what is really happening.
Below is the code snippet which does this (I'm using twitter4j library):
private static void getTweetsOfTheseUsers( List<String> usernames )
{
Twitter twit = TwitterAuth.getInstance();
for ( String user : usernames )
{
//get tweets for each user using twit.getUserTimeline();
}
}//end of method
EDIT:
I terminated the app and started again and it's working fine again with the same a/t and a/t/s. Can't really think what happned?

Failed to request access token for Fusion Tables API with Google Service Account

I have been successfully using Google API (via HTTP/REST, as well as using the .NET client library) with a Google Service Account to access the files in Google Drive.
Recently, I am exploring the Fusion Tables. I am able to use the API with user authorization via a web application. However, when I try to access it using Google Service Account under the same project, it failed with the below error, whenever I have https://www.googleapis.com/auth/fusiontables in the scope:
https:// www.googleapis.com/oauth2/v3/token
HTTP 401
{"error": "unauthorized_client", "error_description": "Unauthorized client or scope in request." }
The error goes away, when I remove https:// www.googleapis.com/auth/fusiontables and the same code block works fine with https://www.googleapis.com/auth/drive and other scopes.
I have checked and confirmed the "Fusion Tables API" is already enabled for my project at Google Developers Console. (Otherwise, my user authorization via a web application would not be working at the first place.)
Is there anything which I could have missed out? Any help would be greatly appreciated.
I just come across this:
Google drive service account and "Unauthorized client or scope in request"
Even though it does not seems to be related at the first glance, it is indeed the same issue.
Problem resolved after removing User = svcAcct, from the below code block.
ServiceAccountCredential credential;
credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(svcAcct) {
// User = svcAcct, *** removed ***
Scopes = new System.Collections.Generic.List<string>(scopes.Split(' '))
}.FromCertificate(certificate)
);
Hence, here is the general advise:
DO NOT call ServiceAccountCredential.Initializer with User = svcAcct unnecessarily.
Only do this when you are trying to impersonating a difference user
(with the condition that the appropriate setup has been correctly done
in Google Apps Admin Console).
Even though it may not produce any error under certain cases, there
are some unexpected behaviors when including an email address of the
service account itself in the JWT claim set as the value of the "sub"
field.

Understanding OAuth and client sessions

I'm learning about OAuth with the goal of allowing visitors to my website the ability to sign in with Twitter. I've been using the Python based oauth2 library as a learning tool, and I think I get most of it.
I understand that after the user authenticates with the service (Twitter in this case) the user is sent to the callback URL with the parameters oauth_token and oauth_verifier.
What I fail to understand is the proper way of storing this information in the users browser. How do I identify these values during subsequent requests? Am I required to create a session system as with a normal website, or is there some magic in OAuth that makes this unnecessary?
How you handle client sessions of people who visit your website is not covered by OAuth, that remains up to you (and the usual session management frameworks).
All OAuth does is tell you that the user really is the Twitter user he claims to be. You can then associate this piece of information with the user session on your site (just like you would if the login screen was on your own page).
there are two types of oauth_token and oauth_verifier in twitter API
first is request token that always come different on each process, that can be save into session using getRequestToken method
i m telling in PHP view , but logic are same in any language
/
* Get request token */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
/* Save request token to session */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
another is accesstoken: that is retrived via getAccessToken method
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
Array
(
[oauth_token] => 223961574-mEctH7SHai######
[oauth_token_secret] => G7Buyxn4okF31Ln3ulAh#####
[user_id] => 223961574
[screen_name] => ltweetl
)
these token are same which is in your registered application on twitter
and already given at below page...
http://dev.twitter.com/apps/{your_app_id}/my_token.

mgtwitterengine and oauth 401 error: Boggled

OK... so here is my code:
twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
[twitterEngine setConsumerKey:CONSUMER_KEY secret:CONSUMER_SECRET];
accessToken = [twitterEngine getXAuthAccessTokenForUsername:profile.twitterUserId password:profile.twitterPassword];
NSLog(#"Access token: %#", accessToken);
the console shows the access token returned just fine (so it seems to work)
eg. Access token: C8A24515-0F11-4B5A-8813-XXXXXXXXXXXXXX
but instead of accessTokenReceived method being called next on my delegate, it calls requestFailed with a 401. How can I be getting a 401 unauthorized and getting an access token back from the method call?????
xAuth, the process for exchanging a login and password for an access token, is a privilege for applications that verifiably meet Twitter's criteria: desktop or mobile applications that are otherwise unable to provide the entire three-legged OAuth flow. Out-of-band OAuth and custom URI schemes are still preferred over xAuth.
If you've exhausted other OAuth implementations and want to use xAuth, you can contact Twitter through api#twitter.com from an email address directly associated with the account owning the application. Include full details about your application, its user base, links to screenshots of it in action, and a detailed description on why this form of authorization is appropriate for your application. Inquires for xAuth are considered on a case-by-case basis and will not be granted to all applicants.
Implementors of xAuth must not store logins and passwords within their applications -- this is not a drop-in replacement for basic auth or a way to avoid implementing OAuth authentication.
Found the issue... for anyone else that has this problem... Getting your app approved for OAuth is only part of the process. Although it looks like you are done and the twitter page gives you your key and secret... there is one not-quite-so-easy-to-find next step. You must send an email to api#twitter.com and ask them to actually enable it.
That was fun figuring out. :)

Resources