Right now, we have csrf token per session. And adding this token jsp's using hidden field. following snippet gives only one per session:
token = (String) session.getAttribute(CSRF_TOKEN_FOR_SESSION_NAME);
if (null==token) {
token = UUID.randomUUID().toString();
session.setAttribute(CSRF_TOKEN_FOR_SESSION_NAME, token);
}
and for every request,
//calls the above snippet and this time token will not be null
String st = CSRFTokenManager.getTokenForSession(request.getSession());
String rt = CSRFTokenManager.getTokenFromRequest(request);
here, usings equals to compare the strings and returning either true or false.
my question is, what happens if I try to generate the token for every request without getting the token from session. And while comparing, I will get from the session and request. is this good idea or missing something?
Instead of using the above snippets, I will go with following
//for every request generate a new and set in session
token = UUID.randomUUID().toString();
session.setAttribute(CSRF_TOKEN_FOR_SESSION_NAME, token);
//get the token from session and request and compare
String st = (String) request.getSession().getAttribute("CSRF_TOKEN_FOR_SESSION_NAME");
String rt = CSRFTokenManager.getTokenFromRequest(request);
You'll want to flip around the flow that you stated above. After every compare you should create a new token.
One large drawback to token-per-request is if the user hits the back button in their browser:
User visits Page1 and stores TokenA in session.
User clicks a link to Page2, submitting TokenA. The app verifies TokenA in session and gives the user TokenB.
User hits the back button to go back to Page1, session information is not updated.
Page1 still only has information for TokenA, user clicks a link or submits a form to Page3 submitting TokenA, but the session only knows about TokenB
App considers this a CSRF attack
Because of this, you need to take great care of how and when the tokens are updated.
Apart from the solution suggested by Jay, I will suggest you to avoid caching of your web-pages by setting various cache-control headers in the response to client.
Related
I have my authorisation url - https://www.reddit.com/api/v1/authorize?client_id=xuJKekGTr1-V8Q&response_type=code&state=dfDfsd4gdf&redirect_uri=http://localhost:8080/redditimageuploader/callback&duration=permanent&scope=submit
But I don't really know what to do from here? I've found a few guides online but it's just a lot of jargon I don't really understand. When I click on the "allow" button, it takes me to the url that I defined as my redirect_uri, and appended to the end of the string is the state that I set, as well as code= and then a string - so I assume I need to do something with those, but I don't know what.
I was wondering if there is a super simple "explain like I'm 5" step-by-step guide on what to do from here?
It's a standard OAuth flow. From the doc :
When the user clicks the "Sign on with Reddit" button on your website, you must redirect the user to the authorisation URL at Reddit - the one in your question, starting with https://www.reddit.com/api/v1/authorize and enriched with the request params you specified. Reddit will then ask the user to sign in, and whether or not he wants to authorise your app access to the requested scope. See https://github.com/reddit-archive/reddit/wiki/OAuth2#allowing-the-user-to-authorize-your-application
If the user agrees, then Reddit will redirect the user to the redirect URI you specified as request param in the authorisation URL (in your case, http://localhost:8080/redditimageuploader/callback). Reddit will add a state request param: you need to ensure that this is the same as the one in your request.
Retrieve the access token with a POST request to https://www.reddit.com/api/v1/access_token, including the following data in your data: grant_type=authorization_code&code=CODE&redirect_uri=URI. Replace CODE with the value you received and URI with your same redirect URI as in the first step.
The response to this third step should return you an access token: store this for future requests on behalf of the user. See https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token
Extra steps are available and documented for error handling and access token operations (invalidation / renewal).
So, once you've correctly implemented the first step, all you need to do is create an endpoint (the one called when your redirect URI is redirected to) which will :
check the state request param
Retrieve the access token (third step) and store it
Let me know if this is clear enough.
I have to create an endpoint, which collects information and then it inserts to a BBDD. The problem is to access this information, the token must always be added to the query params and it expires every 20 hours.
To get the token, firstly I have to make it a call like this one
https://url/token.php?username=...&password=...
I'll get a response like this one
{"success":true,"token":"aaaa","expire":1589780649}
An example of the endpoint to gather information would be
https://url/information.php?token=aaaa&fields=a,b
I have to say that I am new to java spring (and java in general). Is there a way to create a microservice that, before collecting the information, obtains the token every 20 hours?
If you save token in DB, then you can check token on expiry after any request
For example:
if (token.getExpire > 20 hours) {
Token token = tokenRepository.findByToken(token);
if (token != null) {
generateNewToken();
remove and save new token or change old token in DB
}
}
We are using restFB 1.6.12. I am getting the facebook access token in two ways,
1. CLIENT_APP_ID = "XXXXXXXXXXXXXXXXXX";
CLIENT_SECRET = "XXXXXXXXXXXXXXXXXX";
REDIRECT_URL = "XXXXXXXXXXXXXXXXXX";
AUTH_CODE = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
SCOPE = "email,read_stream";
Redirect to facebook as the example. As a result I'll get an
authorization code
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream
asking for an access_token using,
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
this returns the access token like this,
access_token=CAAHWfjdHDKcBAIL0zHMeJKzJw8Ug7WrrrkNxpBnK7ubnFR1RGtIIZA7T3UPlhCSV0hPJXZAgTcKfBSfHZAyxsndc3RT72XMREjACxnGb0ZCGMZAUgDWH3FgOhnaoSBMgkaQBPDOCCEKcLnznMYSncWS7dVxl9IFrSzeFjF6LKOWB3NTynl5X1&expires=5125218
2. AccessToken accessToken = new
DefaultFacebookClient().obtainAppAccessToken(appid,appsecret);
String token=accessToken.getAccessToken();
It reurns the access token like this,
access_token=517312558337191|5oHY9T3cZICO_TCeK8OdXKg5Y08
If I use the first(1) one, it works fine for first access after then every access throws an error
Auth Token= {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}}
If I use the second(2) one, it works fine only for publicSearchMessages but when I access publicEvents or other searches it throws an error
com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#200) Must have a valid access_token to access this endpoint
at com.restfb.DefaultFacebookClient$DefaultGraphFacebookExceptionMapper.exceptionForTypeAndMessage(DefaultFacebookClient.java:766)
at com.restfb.DefaultFacebookClient.throwFacebookResponseStatusExceptionIfNecessary(DefaultFacebookClient.java:688)
at com.restfb.DefaultFacebookClient.makeRequestAndProcessResponse(DefaultFacebookClient.java:630)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:592)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:556)
at com.restfb.DefaultFacebookClient.fetchConnection(DefaultFacebookClient.java:219)
My question is, what is the difference between these two access token and how can I programmatically generate access code for first one to works publicSearchMessages, getPublicEvents and other searches?
Which one access token is used to works as expected?
Access_tokens allow users to interact with your apps in secure and social ways. While we are removing the use of the offline_access permission, through a migration setting in the App Dashboard, we are now allowing the option to use access_tokens with a long-lived expiration time that can be renewed each time the user revisits your app
When a user visits your site with an existing, valid, short-lived user access_token, you have the option to extend the expiration time of that access token.
extend the expiration time once per day, so even if a user revisits your site multiple times a day, the token will be extended the first time requested. You must make sure to call the new endpoint below before the short-lived access_token expires.
Using the new endpoint below, you will be able to extend the expiration time of an existing, non-expired, short-lived user access_token.
To get the long-lived user access_token simply pass your own client_id (your app_id), your app_secret, and the non-expired, short-lived access_token to the endpoint. You will be returned a new long-lived user access_token; this access_token will exist in addition to the short-lived access_token that was passed into the endpoint
In short Get a page access token – those don’t expire per default; and make sure to do so with a long-time user access token
You can access facebook doc here for more info
To get an extended Page Access Token, exchange the User Access Token for a long-lived one and then request the Page token. This "extended" token for Pages will actually not have any expiry time.
https://developers.facebook.com/docs/howtos/login/extending-tokens/#step1
resolve this by executing a curl request, and saving "Page access token" in your code manually
For example in gmail login, when we consider a login test, when doing it manually for the first time we'll get the login page, from next time onwards we'll be directly getting into the inbox page.
If you try to do the same thing in webdriver(Run login test twice), in all these attempts we'll get the login page as we didn't login from this machine earlier. What is happening in behind the scenes in maintaining the session with respect to cookies or session ?
Here is the description & code snippet from selenium docs to add or remove cookies:
Before we leave these next steps, you may be interested in
understanding how to use cookies. First of all, you need to be on the
domain that the cookie will be valid for. If you are trying to preset
cookies before you start interacting with a site and your homepage is
large / takes a while to load an alternative is to find a smaller page
on the site, typically the 404 page is small
(http://example.com/some404page)
// Go to the correct domain
driver.get("http://www.example.com");
// Now set the cookie. This one's valid for the entire domain
Cookie cookie = new Cookie("key", "value");
driver.manage().addCookie(cookie);
// And now output all the available cookies for the current URL
Set<Cookie> allCookies = driver.manage().getCookies();
for (Cookie loadedCookie : allCookies) {
System.out.println(String.format("%s -> %s", loadedCookie.getName(), loadedCookie.getValue()));
}
// You can delete cookies in 3 ways
// By name
driver.manage().deleteCookieNamed("CookieName");
// By Cookie
driver.manage().deleteCookie(loadedCookie);
// Or all of them
driver.manage().deleteAllCookies();
In a java web application,I want to check whether a user who signs in is a returning user. How can I check if there is already a cookie that has been set on earlier login.
On HttpServletRequest you have a getCookies() method that will give you an array of the cookies the client is sending with his request.
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getCookies%28%29
Set cookie when user performs log-in:
Cookie c = new Cookie("visit", "old")
c.setMaxAge(3600*24*365*1000); // 1 year (for example)
response.addCookie(new Cookie("visit", "old"));
Now you can check this cookie when user with new session comes to the system: request.getCookies(), then iterates over returned array and find "your" cookie. If cookie exists this is "old" user otherwise the new one.