Just want to know is there a way to destroy all sessions for a rails application from the server side. At the moment we have a auto redirect if someone is logged in. I want to stop that for users that are logged in. I was thinking of resetting the security token (in application_controller) then deploy. However I see that from the documentation it raises a exception. Is there a cleaner was to do this in Rails 3.2.0?
Thanks
I will just change the session token, in config/initializers/secret_token.rb:
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
MyAPP::Application.config.secret_token = 'ABC123'
Related
Starting from the point where an user has given permissions to the app, and the access token is stored in session. Following Google's web server app example, I'm just checking whether an access token exist.
However, the token might expire, or the user might remove it manually on his account page. How do I check that the token is still valid, before executing a request?
Or maybe that approach is wrong, and the correct design includes that I should handle the error after executing the action, and if it's an authorization error then show the user a way to authorize it once again?
The latter is the recommended approach. By assuming failure and dealing with it routinely, your app is much more robust. The only downside is that an access attempt takes a bit longer because of the need to fetch a new Access Token and retry. If that's a problem (it shouldn't be normally), then you can always note the expiration time of the new Access Token and set up a background process to renew it with say 5 minutes to spare.
I have an application in rails which is heavily based on facebook oauth2. At a glance - user signs in with FB connect and can list it's pages (and do some stuff with that data but that's not important right now. Let's just focus on signing-in and getting pages list).
After a sign-in, i'm saving user access_token and expires_at in the db. Then, each time i need to make a request to facebook api as a user (to obtain his pages list), i'm checking if expires_at is not past and if it is, i'm renewing user token using a following snippet:
def refresh_facebook_token
# Checks the saved expiry time against the current time
return unless facebook_token_expired?
# Get the new token
new_token = facebook_oauth.exchange_access_token_info(
old_access_token)
# Save the new token and its expiry over the old one
self.facebook_auth = {
uid: uid,
access_token: new_token['access_token'],
expires_at: Time.now + new_token['expires'].to_i
}
save
end
This works most of the times but, from time to time, my code throws:
type: OAuthException, code: 190, error_subcode: 460, message: Error validating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons. [HTTP 400]
in line with exchange_access_token_info.
That error is thrown fo my own user and i can say that i didn't changed the password so i'm not sure what's that caused by nor how can i deal with refreshing the tokens by backend in a bullet-proof way.
Any help much appreciated!
First of all, I would recommend you go through this link and decide which configuration makes sense for your application - using short-lived or long-lived or what.
Now, am not too sure but I think that you are considering the method exchange_access_token_info as the token refresher. If so, this is NOT the case! Once a token is expired, it's useless.
exchange_access_token_info method simply takes the short-lived token (which is currently active) and convert it into the long-lived token using app id and secret.
Just understand that-
The user access token cannot be extended infinitely again and again without any user's interaction with your app for 60 days.
So the flow is very simple-
you get the short-lived token when user authenticates your app (user engagement on front-end)
on server-side you extend the token's validity to 60 days.
want to extend the token validity again? - repeat the steps.
Hope that helps!
I have a single-page web application that uses OAuth bearer tokens to authenticate users. We do not use cookies, and there is no support for sessions. It simply makes calls to an ASP.NET Web API to access protected resources with an access token. We also support refresh tokens to obtain a new access token.
How would I implement a sliding expiration? I only see three options:
Issue a new access token on every request using the refresh token. This defeats the whole purpose of refresh tokens.
Track when the last request was in the client app. Each request would see when the last one was, and if it was after a set period, log them out and bring up the login screen. If not and their access token has expired, issue a new one and let them continue. This seems kind of messy and insecure to me.
Forget refresh tokens. Store access tokens in a database with the expiration date and update it on every request. I prefer to not do a DB operation on every request.
Is there another option or do one of these actually sound acceptable?
You said there is no session support. But this is pretty much what sessions are for, and ASP.NET and IIS support them with quite a few options for how they are managed, with or without cookies and with or without a database if I recall right. If sessions are not available in your case...
There is also the option of using an encrypted token, which contains session identity and timeout info. Then the server merely needs to know the key for decrypting the token. The server decrypts the token on each request, updates the time and sends a new encrypted token back with the new response. You can send the token as a header, cookie, part of url, take your pick. But cookies and headers are designed for this use pattern and take less work in my experience.
A token that does not decrypt is treated as an unauthorized request. Timeout is handled as you normally would, e.g. using the refresh token to get a new authentication.
If you have a server farm, only the key for decryption has to be shared between the servers. No need for a session in a database or shared cache.
You can elaborate this to expire keys over time. Then servers only have to infrequently check with a directory service, shared cache, or database, message or queue to get the most recent keys. If you generate them properly and expire them faster than someone can brute force hack them, you win! (joke) Windows has apis to support you on the encryption and key management.
I did this for a project years ago with success. It is, in effect implementing sessions without server side state. And as with all session methods and all authentication methods it has vulnerabilities.
But without some special reason to the contrary, I would just use sessions for their intended purpose. If I want each browser tab to have separate authentication I would use header based session tokens. If I want browser tabs in a browser session to share authentication I would use session cookies.
Or I would use your option three, maybe with a shared cache instead of a database, depending on performance requirements and infrastructure. I suspect that IIS+ASP.Net may even do that for you, but I have been away from them too long to know.
I'm using Sinatra and Omniauth (specifically, google oauth2) to serve a website. I'm somewhat confused over what data is safe to store in the cookie and what isn't.
I'm inclined to say that I should simply store an authorized => true field in the cookie, once I have confirmed that the AuthHash contains an access token. The cookie is protected using Rack::Sesssion::Cookie and :secret => "some-really-long-and-strong-password". Is this thinking correct?
Furthermore, if someone wants to hack the site (i.e. login without actually logging in), all they need to do is successfully break the cookie's secret and make a fake cookie with authorized => true, right?
I don't see any value in storing the actual access key stored in the credentials portion of the Omniauth::AuthHash, since this seems to be the sensitive information...
I'm somewhat confused over what data is safe to store in the cookie and what isn't.
In general, this is the worst scenario if someone steals a user cookie:
Hijack the user's session
Steal all data contained in the cookie
Gain unauthorized access
I think what you want to use is a form of authenticity token that you can pass back and forth to verify the authenticity of the user and their requests.
References
Cross-site Request Forgery on Wikipedia
I'd check out the sections Example and characteristics and Prevention in particular.
I'm trying to make a web service secure.
It's not for a bank or anything of that sort, but the organization using it may lose some money if the service will be used by someone not authorized (it's hard to tell exactly how much..).
The purpose is not to allow unauthorized applications to use any method (other than "GetChallenge". for users authentication there is a different mechanism which checks for username and password. I actually combined the two, but they serve different purposes):
So here's what I do:
I send a (ASP.NET) session key (for everyone to read. ASP.NET's session Is 15 randomly generated bytes, it lives for 20 minutes unless prolonged, and ASP.NET will not receive any request without it).
In my SignIn method, apart from username and password (which anyone can acquire, since it's a part of a public site), I receive a third parameter - the session key hashed by md5 algorithm with 6 bytes as salt.
And only if the hash is correct (I'm hashing and comparing it on the server side) - I let the users sign in.
From then on in every method, I check if the user is signed in.
Added: The username and password are sent as clear text, and that's not a problem (not the one I'm addressing at least). The problem is for someone (other than the company we're working with) writing an application which uses my web service. The web service should only be used by an authorized application.
Also, the session id is sent back and forth with every request and response (as a part of ASP.NET session mechanism. That's how ASP.NET knows to "track" a session specific for a user). Sorry for not clarifying that from the first place.
(irrationally thought it was obvious).
How strong and effective is that security strategy?
Thanks.
Updated based on your edit and comment
It's pretty secure and is very similar to the approach used by Google, Facebook and others for their API keys. Except...
Session ID plain text potential issue
I would recommend against using Session ID as part of a security mechanism.
The one issue is with passing the session key in plain text across the network. There is potential that this could open up some Session hijack and other attacks.
From the Microsoft Docs:
The SessionID is sent between the server and the browser in clear text, either in a cookie or in the URL. As a result, an unwanted source could gain access to the session of another user by obtaining the SessionID value and including it in requests to the server. If you are storing private or sensitive information in session state, it is recommended that you use SSL to encrypt any communication between the browser and server that includes the SessionID.
As you are using the Session ID as part of your security mechanism I would say that is sensitive data.
One way to ensure someone doesn't get hold of your session key is to run your service on HTTPS. Personally I would avoid using the Session ID in this way and generating a non-related value instead.
Recommended change
Follow more closely the model used by Google and the like. Generate a new GUID for each application, store the GUID in a database on the server, pass the GUID in each request to your server from the client.
Benfits:
Identifies the client application uniquely, allowing you to track and manage usage per client nicely
Easily disable any client by removing the GUID from your data store
No sensitive data on the wire
I would still run the service on HTTPS as it's easy to setup and gives the added benefit of protecting any other data you send to your service.
The purpose of encryption is not to
allow unauthorized applications to use
any method
Wrong. The purpose of encryption it to prevent the understanding of data whilst either in transit or stored. It prevents data being 'useable' by those that do not have the means to decrypt.
What you are describing is something similar to a public/private key system. You're making your session key available to everyone. Then only after they've md5 with the correct salt (as per your server side comparison) you're then trusting that source.
You've got NO authentication here except for username and password. Also your data isn't encrypted during transit. I fail to see how this is at all secure.
I think you're best bet is to use an SSL certificate (so your web service is running over HTTPS) along with the username and password. If you want to be doubly secure you might want to go down the route of checking source IP ranges and login locations as an additional check. Perhaps a forced password change interval will help in the case that consumers are passing credentials to a third party + audit how the web service is actually being used.
As a side note if you want to hash something don't use MD5, its broken.
From a web services perspective the ideal way to use authentication or provide security to your service is something like this: Web Service Authentication (Token and MD5 Hashing to encrypt password).
The way you describe it, it does not seem secure at all.
What is the point of letting the SignIn method accept a hashed session key, if the session key is public ("for everyone to read")?
Plus: "in every method, I check if the user is signed in. " How do you check that?
A common (and reasonably secure) strategy would be to generate a (unique, sufficiently long and random) session ID server-side, and send it to the client after it has authenticated. Then check every client request and only accept it if it contains the session ID. To do this, either embed the ID into all links on every page, or set it as a cookie, depending on what's easier for you.
On logout, just delete the session ID on the server.
That way, no one can invoke any method without a valid session.