I'm developing an application where backend is asp.net owin based.
In Startup.cs I have IAppBuilder.useCookieAuthentication() { ... }. After successfully authenticated, current user with its roles can be accessed via HttpContext in all my web api controllers.
My javascript client side needs a knowledge about these roles in order to know how to display specific items. For example: user having administrator role can see additional tabs.
My question is: what's the best way to 'transfer' these roles to client side. Is it by writing some endpoint which will return these roles, or any other way?
Thanks
I totally agree with #cassandrad !
But if you want to access it as plain text, than you have to provide your own implementation of TicketDataFormat in the CookieAuthenticationOptions
public class CustomAccessTokenFormat : ISecureDataFormat<AuthenticationTicket>
{
// If you want to do custom serialization and encryption
public string Protect(AuthenticationTicket ticket)
{
return "UserName|Role1|Role2|..."; // your raw text serialization goes here
}
// Deserilaize and decrypt the ticket
public AuthenticationTicket Unprotect(string strTicket)
{
return new AuthenticationTicket(null, null); // deserialize the plain text here into an AuthenticationTicket object
}
}
You don't need to pass information about roles or permission in “raw” state to the client-side. Instead, you should have AuthenticationTicket — the thing that holds all information protected and encrypted. So, if you are using correct implementation of OWIN middleware, there is no need to do something by yourself — middleware will add all the necessary data to your response(inside cookies), client only need to resend this information back to the server next time when he wants to access some resources on the server.
And yes, I'm implying that you shouldn't have any information about permissions on your client-side — it is not secure.
Related
Not sure if the title summarises my question well.
Basically, I am trying to authenticate routes such as checking if user exists etc. I only want to allow
requests coming from my frontend application to be approved, but, since no user is signed in there is no token to send.
Api request -
mywebiste/checkUser/email
This route is unprotected on my backend because no user is logged in.
BUT I want to protect this route, in such a way that it's accessible only from the frontend.
Some ideas I came up with were adding specific headers tag from the frontend and check them on the backend, but that could be easily replicated, is there something more secure like using tokens etc.
I am using React and Node.js
Same origin policy is going to give you some basic protection, but basically if an API endpoint is exposed publicly, it's exposed publicly. If you don't want that route to be publicly accessible you need to add access control.
If you use that route to check if a user is already registered, you could, for example, merge it with the user registration route and send a different error code if the user already exists (which is not a great idea because it leaks which emails are registered on your system).
You can verify that a request was originated by a user (by authenticating him) but you cannot verify that a request comes from a particular client because of these two reasons :
If you include some API key in your client (web page or other), it's easily retrievable by everyone (the best thing you could do is offuscate it which makes things slightly harder but still possible)
If you send an API key over the network it's easily retrievable as well
The only thing you could do is prevent other web pages from calling your backend on behalf of the user, by using CORS (which is actually active by default if you dont specify an Access-Control-Allow-Origin header)
I ended up creating a kind of working solution, so basically, I create a new base64 string on my frontend and attach that to the header while making a request to the backend. The base64 string is different every minute, so even if the header is copied, it differs every minute and is combined with your secret key.
I have made a package so that people can use it if they want - https://github.com/dhiraj1site/ncrypter
You can use it like so
var ncrypter = require('ncrypter');
//use encode on your frontend with number of seconds and secret key
var encodedString = ncrypter.encrypt(2, 'mysecret1')
//use decode on your backend with same seconds and secret
var decodedString = ncrypter.decrypt(encodedString, 2, 'mysecret1');
console.log('permission granted -->', decodedString);
I’m trying out the Authentication component in Firebase.
A) I have a situation where the web client javascript code firebase-app.js and firebase-auth.js 3.3.0...
firebase.auth().onAuthStateChanged and
firebase.auth().currentUser
... return different expected logged in user values, than the jvm
client [com.firebase/firebase-client-jvm "2.5.2"]. The JVM client
returns null user data.
My JVM client code is taken from Firebase’s QuickStart Guide. In
the JVM client, neither onAuthStateChanged handler is called, nor
does firebaseObj.getAuth() return any data.
I’m wondering where the discrepancy is. The web client was initialized
with “codepairio.firebaseapp.com”.
var config = { ... authDomain: “<my-firebase-app>.firebaseapp.com"
};
firebase.initializeApp(config);
B) The java client was initialized with “https://.firebaseio.com”. I’m using this URL as it’s specified in the guide and mentioned here. Also, if you try
to use “.firebaseapp.com”, you’ll get an error:
“IllegalStateException For a custom firebase host you must first set your authentication server before using authentication features!”.
So with that out of the way, we have...
new Firebase("https://<my-firebase-app>.firebaseio.com”);
Any ideas on how to get them to observe the same source of truth?
====> [EDIT]
Ok, I've gotten a bit further. It turns out that I was using an older firebase API (A) than the latest (B).
A) https://www.firebase.com/docs/android/guide/user-auth.html
B) https://firebase.google.com/docs/auth/server/
So if we look at Firebase's documentation for how to handle user's, we see this:
A Firebase User object represents the account of a user who has signed
up to an app in your Firebase project. Apps usually have many
registered users, and every app in a Firebase project shares a user
database.
A Firebase User instance is independent from a Firebase Auth instance. This means that you can have several references to different
users within the same context and still call any of their methods.
But i) the notion of FirebaseAuth.getInstance().getCurrentUser() doesn't make sense if our app is dealing with multiple users. And further, the FirebaseAuth.getInstance().getCurrentUser() method doesn't even exist. The FirebaseAuth class file (in com.firebase/firebase-client-jvm "2.5.2"), doesn't reflect the documentation.
$ javap -classpath ~/.m2/repository/com/google/firebase/firebase-server-sdk/3.0.1/firebase-server-sdk-3.0.1.jar com.google.firebase.auth.FirebaseAuth
Compiled from "FirebaseAuth.java"
public class com.google.firebase.auth.FirebaseAuth {
public static com.google.firebase.auth.FirebaseAuth getInstance();
public static synchronized com.google.firebase.auth.FirebaseAuth getInstance(com.google.firebase.FirebaseApp);
public java.lang.String createCustomToken(java.lang.String);
public java.lang.String createCustomToken(java.lang.String, java.util.Map<java.lang.String, java.lang.Object>);
public com.google.firebase.tasks.Task<com.google.firebase.auth.FirebaseToken> verifyIdToken(java.lang.String);
static com.google.api.client.json.JsonFactory access$000();
static com.google.firebase.auth.internal.FirebaseTokenVerifier access$100(com.google.firebase.auth.FirebaseAuth);
static {};
}
C) So far, using Firebase's Authentication service, on the server is very opaque to me at the moment. Can someone clarify the semantics of handling multiple users, getting lists of logged in users, verifying users with request tokens, etc. Where's the working API for all this?
I actually got an answer back, from Firebase Support, on this. Turns out that, based on the documentation, the capabilities available for the server side (nodejs and java) in terms of authentication are only i) creating custom tokens and ii) verifying ID tokens. As of now, handling users or getting the current user is not supported yet.
For the creation and verifying tokens in the server side, you can refer to this guide for more information. You can also check these posts for more information.
Firebase Java client with custom authentication
Is it still possible to do server side verification of tokens in Firebase 3?
https://firebase.googleblog.com/2013/03/where-does-firebase-fit-in-your-app.html
Hth
I'm building an app and would like some feedback on my approach to building the data sync process and API that supports it. For context, these are the guiding principles for my app/API:
Free: I do not want to charge people at all to use the app/API.
Open source: the source code for both the app and API are available to the public to use as they wish.
Decentralised: the API service that supports the app can be run by anyone on any server, and made available for use to users of the app.
Anonymous: the user should not have to sign up for the service, or submit any personal identifying information that will be stored alongside their data.
Secure: the user's data should be encrypted before being sent to the server, anyone with access to the server should have no ability to read the user's data.
I will implement an instance of the API on a public server which will be selected in the app by default. That way initial users of the app can sync their data straight away without needing to find or set up an instance of the API service. Over time, if the app is popular then users will hopefully set up other instances of the API service either for themselves or to make available to other users of the app should they wish to use a different instance (or if the primary instance runs out of space, goes down, etc). They may even access the API in their own apps. Essentially, I want them to be able to have the choice to be self sufficient and not have to necessarily rely on other's providing an instance on the service for them, for reasons of privacy, resilience, cost-saving, etc. Note: the data in question is not sensitive (i.e. financial, etc), but it is personal.
The user's sync journey works like this:
User downloads the app, and creates their data in the process of using the app.
When the user is ready to initially sync, they enter a "password" in the password field, which is used to create a complex key with which to encrypt their data. Their password is stored locally in plain text but is never sent to the server.
User clicks the "Sync" button, their data is encrypted (using their password) and sent to the specified (or default) API instance and responds by giving them a unique ID which is saved by the app.
For future syncs, their data is encrypted locally using their saved password before being sent to the API along with their unique ID which updates their synced data on the server.
When retrieving synced data, their unique ID is sent to the API which responds with their encrypted data. Their locally stored password is then used to decrypt the data for use by the app.
I've implemented the app in javascript, and the API in Node.js (restify) with MongoDB as a backend, so in practice a sync requests to the server looks like this:
1. Initial sync
POST /api/data
Post body:
{
"data":"DWCx6wR9ggPqPRrhU4O4oLN5P09onApoAULX4Xt+ckxswtFNH/QQ+Y/RgxdU+8+8/muo4jo/jKnHssSezvjq6aPvYK+EAzAoRmXenAgUwHOjbiAXFqF8gScbbuLRlF0MsTKn/puIyFnvJd..."
}
Response:
{
"id":"507f191e810c19729de860ea",
"lastUpdated":"2016-07-06T12:43:16.866Z"
}
2. Get sync data
GET /api/data/507f191e810c19729de860ea
Response:
{
"data":"DWCx6wR9ggPqPRrhU4O4oLN5P09onApoAULX4Xt+ckxswtFNH/QQ+Y/RgxdU+8+8/muo4jo/jKnHssSezvjq6aPvYK+EAzAoRmXenAgUwHOjbiAXFqF8gScbbuLRlF0MsTKn/puIyFnvJd...",
"lastUpdated":"2016-07-06T12:43:16.866Z"
}
3. Update synced data
POST /api/data/507f191e810c19729de860ea
Post body:
{
"data":"DWCx6wR9ggPqPRrhU4O4oLN5P09onApoAULX4Xt+ckxswtFNH/QQ+Y/RgxdU+8+8/muo4jo/jKnHssSezvjq6aPvYK+EAzAoRmXenAgUwHOjbiAXFqF8gScbbuLRlF0MsTKn/puIyFnvJd..."
}
Response:
{
"lastUpdated":"2016-07-06T13:21:23.837Z"
}
Their data in MongoDB will look like this:
{
"id":"507f191e810c19729de860ea",
"data":"DWCx6wR9ggPqPRrhU4O4oLN5P09onApoAULX4Xt+ckxswtFNH/QQ+Y/RgxdU+8+8/muo4jo/jKnHssSezvjq6aPvYK+EAzAoRmXenAgUwHOjbiAXFqF8gScbbuLRlF0MsTKn/puIyFnvJd...",
"lastUpdated":"2016-07-06T13:21:23.837Z"
}
Encryption is currently implemented using CryptoJS's AES implementation. As the app provides the user's password as a passphrase to the AES "encrypt" function, it generates a 256-bit key which which to encrypt the user's data, before being sent to the API.
That about sums up the sync process, it's fairly simple but obviously it needs to be secure and reliable. My concerns are:
As the MongoDB ObjectID is fairly easy to guess, it is possible that a malicious user could request someone else's data (as per step 2. Get sync data) by guessing their ID. However, if they are successful they will only retrieve encrypted data and will not have the key with which to decrypt it. The same applies for anyone who has access to the database on the server.
Given the above, is the CryptoJS AES implementation secure enough so that in the real possibility that a user's encrypted data is retrieved by a malicious user, they will not realistically be able to decrypt the data?
Since the API is open to anyone and doesn't audit or check the submitted data, anyone could potentially submit any data they wish to be stored in the service, for example:
Post body:
{
"data":"This is my anyold data..."
}
Is there anything practical I can do to guard against this whilst adhering to the guiding principles above?
General abuse of the service such as users spamming initial syncs (step 1 above) over and over to fill up the space on the server; or some user's using disproportionately large amounts of server space. I've implemented some features to guard against this, such as logging IPs for initial syncs for one day (not kept any longer than that) in order to limit a single IP to a set number of initial syncs per day. Also I'm limiting the post body size for syncs. These options are configurable in the API however, so if a user doesn't like these limitations on a public API instance, they can host their own instance and tweak the settings to their liking.
So that's it, I would appreciate anyone who has any thoughts or feedback regarding this approach given my guiding principles. I couldn't find any examples where other apps have attempted a similar approach, so if anyone knows of any and can link to them I'd be grateful.
I can't really comment on whether specific AES algorithms/keys are secure or not, but assuming they are (and the keys are generated properly), it should not be a problem if other users can access the encrypted data.
You can maybe protect against abuse, without requiring other accounts, by using captchas or similar guards against automatic usage. If you require a catcha on new accounts, and set limits to all accounts on data volume and call frequency, you should be ok.
To guard against accidental clear-text data, you might generate a secondary key for each account, and then check on the server with the public secondary key whether the messages can be decrypted. Something like this:
data = secondary_key(user_private_key(cleartext))
This way the data will always be encrypted, and in worst case the server will be able to read it, but others wouldn't.
A few comments to your API :) If you're already using HTTP and POST, you don't really need an id. The POST usually returns a URI that points to the created data. You can then GET that URI, or PUT it to change:
POST /api/data
{"data": "..."}
Response:
Location: /api/data/12345
{"data": "...", "lastmodified": "..." }
To change it:
PUT /api/data/12345
{"data": "..."}
You don't have to do it this way, but it might be easier to implement on the client side, and maybe even help with caching and cache invalidation.
This question has been asked to me in a interview. i search on web but can't find a thread that explains it in a way that makes sense to me.
Suppose is i had a web service which return a list of something and available
In public Domain(Any body can use That) For security User need A key to Access that web service.
How can i use That web service securely in Ajax.
Problem is if i use Ajax to access that web service any body can able to see my private key,
I suggest for a encryption but i have to pass that key in decrypt(as i get )in form
Than i suggest for a mediator file(at server side) on which i can call that web service but what if somebody directly access that mediator file (i know same origin policy )
i really want to know what are the possible solution to overcome to these problem and what is best practice to make a secure ajax call on rest
In fact, there is a dedicated security flow in OAuth2 for this particular use case called "Implicit Grant Flow".
You could have a look at these links for more details:
http://www.bubblecode.net/en/2013/03/10/understanding-oauth2/#Implicit_Grant
https://www.rfc-editor.org/rfc/rfc6749#section-4.2
If you don't use OAuth2, you can propose the user to authenticate and get back an access token. You could store it within the local storage of your browser but you need to be very careful with XSS. This question (and its answers) could provide you some hints regarding such issue: What are (if any) the security drawbacks of REST Basic Authentication with Javascript clients?.
Hope it helps you,
Thierry
We are using cookies for this. And like the Session we have stored the secure key on the Web-Server. With the Cookie we can get the secure key. So he just see the "key" of his key. There is no option to hide all information from the client. But you can show him information, he cant use directly.
But at all, there is the fishing problem. If someone fishes your cookies, he has your "key" of your secure key. Many others are doing it simular. E.g. Facebook.
This is not specific for Ajax calls, but since it works for both, normal GETs and AJAX Calls, it would be a solution.
If you do not have 100% control of both client side and server side, you may want to use client-side authenticate solution (e.g. Oauth 1 or 2).
If you do have 100% control of both client side and server side, easy way is to use basic authenticate + SSL.
What our project is :
- I have a restful service. We provide restful service in SSL.
- Only our partner companies can use it through internet.
What we did is:
- They have their username/password in their request (is a Ajax) in their internal application (not public-accessed web page)
- sample as following restful code (you can test by Postman):
// to inject request
#Context
private HttpServletRequest request;
#GET
#Path("/testAuth")
#Produces(MediaType.APPLICATION_JSON)
public Response testAuth() {
// TODO
// this is only a template for doing authentication in the near future
String returnString = "";
//check if authenticated
String authorization = request.getHeader("Authorization");
if (authorization == null || authorization.toUpperCase().startsWith("BASIC ") == false) {
//no authenticated
returnString = "{\"testAuth\", \"need authentication\"}";
return Response.status(401).entity(returnString).build();
} else{
String credentials = authorization.substring("Basic".length()).trim();
byte[] decoded = DatatypeConverter.parseBase64Binary(credentials);
String decodedString = new String(decoded);
String[] actualCredentials = decodedString.split(":");
String ID = actualCredentials[0];
String Password = actualCredentials[1];
String Result = userAuthenticate(ID, Password);
returnString = "{\"testAuth\", \"" +
" (" + Result + ") \"}";
return Response.status(200).entity(returnString).build();
}
}
i am getting remote JSON value into to my client app as below.
var $Xhr = Ti.Network.createHTTPClient({
onerror : function($e) {
Ti.API.info($e);
},
timeout : 5000,
});
$Xhr.open("GET", "http://***********.json");
$Xhr.send();
$Xhr.onload = function() {
if ($Xhr.status == 200) {
try {
Ti.API.info(this.responseText);
} catch($e) {
Ti.API.info($e);
} finally {
$Xhr = null;
}
}
};
My json URL is static. i would like to protect this URL from stranger eyes after creating APK file or publishing for iOS.
Also my server side support PHP. I have thouhgt MD5, SHA etc. but i didn't develop any project about this algortim.
Do you have any suggestion or approach?
Thank you in advance.
I would just say that it is not possible for you to "hide" the end point. Your url will always to visible to the user because otherwise user's browser wouldn't know how to actually post it to your server.
If you meant to only hide the json object, even that is not totally possible. If your javascript knows what the values are then any of your client smart enough to understand javascript will be able to decode your encoded json object. Remember, your javascript has decoded object and a user would have full access to it. There is no protection against that. At best, you can hide it from everyday user by encoding to with md5 or sha as you put it.
I you wish to restrict access to app user only, you will need to authenticate your users first.
Once they are authenticated, you should generate a hash by concatenating userid (or any user identifying data) and a key that you know (a string will do it), and hashing it using any hashing method, md5 would be enough for that kind of usage I guess, SHA is good anyway.
The next step would be to send this hash with every AJAX request to your server. consider it as an additional data.
Finally, server-side, before treating the request and fetching the data to be sent, just generate a hash the same way you did in your app, using the userid of the requesting user and the same "secret" key you chose. You can now compare both hashes and see if they're identical. If not, then it's probably that someone tried to forge a request from outside your app.
Note that it could be possible for someone authenticated to get his hash (which depends on his ID) and then use it in one of his applications, so it may be a good idea to track the requests server-side in order to check if there's any suspicious usage of your API. You could aswell change your "secret key" regularily (forcing an update of your app though) or define an array with a different key for each day of the year in both your app and server code, so that each individual hashkey will change everyday, recurring each year.