Angular Auth Token and Visible data client side - c#

I have come across a concern on an API project currently. I am newer to angular, so bare with me please. The data is storing in a static file our cient_id and secret key. You can view this in developer tools. Now I know there is no safe way to store data client side and hence encrypting takes a key to pass etc. Also should use tsl and so on.
My question (and is based around lack of knowledge of oauth and tokens) is would it be possible or reasonable to handle a situation like this in the manner below:
User Login request sent
Server validates and returns auth token to api controller
Prior to returning to UI JS side we encrypt in code behind.
Only the encrypted value is stored in client side.
Any request needing the AUTH token hits a anonymous api, then decrypts in code behind to get your client key, secret and other data.
At this point if valid then continues to targeted api call, does its work, returns data to UI again.
Does this concept make sense or no due to again my lack of knowledge in this arena?
Thanks in advance!

Related

Best practices for consuming WebAPI backend from MVC WebApp

I'm creating a WebAPI based SaaS application. This WebAPI can be used alone without the need for a user interface, requires a basic authentication sent with every request made to the WebAPI and returns some objects when the methods are called and authenticated.
Now I'm facing a big problem: I'm creating a WebApp in MVC (but it could be any language) and I can't figure out how to call my WebAPI endpoint without the need to keep username and password in order to authenticate the WebAPI request every time I call a method.
What are the best practices in this particular case?
I can't seem to find any suitable solutions...
So far I have tried to create a custom cookie with the help of a custom implementation of the HttpContext.Response.Cookies.Add method, where I store in the userData of the Cookie the pair of username and password encrypted. In this way I can call the WebAPI methods specifying each time the BasicAuthenticationCredentials with the correct username and password, but this seems to me a very unmaintainable way to do the job in the long run.
I also wanted to try the OAuth2 way, but I can't find a well written guide on how to implement an authentication server based on a custom user table from SQL Server (and the first five pages of the Google result list didn't help me, they did actually make me even more confused about this topic, the whole OWIN and Katana thing...).
I can provide further information in case someone is willing to help me out.
Thanks in advance,
Stefano.
Here's a good tutorial about how to implement your own OAuth2 server:
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
The main idea behind using OAuth is that you'll only need a username and password for your first request, and after that, you'll get an access token that will be used to get access to the API. This access token will have a lifetime, and once it has expired, the user will need to request a new access token (either by sending the user credentials again, or by using a refresh token that will be used as a credentials substitute).
The nice part behind this approach is that since the access tokens have a lifetime, even if one of those tokens gets compromised, you can just revoke it (or wait until it expires, for example, you can create tokens that will be renewed every 5 minutes or even less. It's up to you), the client will automatically ask for a new one, and that will be the end of the story. On the other hand, if you were always receiving the user credentials and those credentials got compromised, the user will need to change them and the risk will be there until the user finally changes his credentials (and here's a manual process where the user needs to be aware about this problem, while the OAuth approach is just refreshing those tokens all the time).
Also, remember to keep all the communication over HTTPS, since the tokens are sensitive information, and you don't want an eavesdropper getting the access token or even worse, the refresh token by just intercepting the communication. If he's able to do something like this, then even tokens refreshing every minute will be a useless approach against someone getting every token that you send.

How to handle Authentication tokens

I have a API mobile service that handles users' login and verification. If a user is verified then it produces an authentication token. On my end I have a Web client that receives that token and uses it to call different Api controllers. How should I go about keeping a user logged in status constant?
Can I store the token on a cookie? would it be exposed to abuse if I do so? would a session work better? What is the best way to handle this issue? Sorry for the noob question, but I have never done this type of setup before.
The token can be stored relatively securely on the client as a cookie. Here's an example using Forms Authentication. It can be made even more secure by requiring SSL.
You can also consider using HTML 5 local storage like this:
http://www.princesspolymath.com/princess_polymath/?p=396
...which can be more efficient, as you manually use the token when making AJAX calls that require it instead of sending the cookie on every single request.

Handling security in an ASP MVC application that uses JS to a REST API

I have an ASP MVC4 web site. Originally, most of the content was served via controllers as one would expect. I have moved the data storage from SQL Server to MongoDB. I have also added a lot of ajax to update data client side, without a full refresh. This is working fine, but my controllers now have lots of methods that take json and return json. I was able to build a Node.js server that hits the database and exposes exactly the same functionality, without lots of going to and from C#.
My javascript client-side is now calling a Node.js REST API, this works great. My 'secure' code (like adding a new user) hits the same REST API from the server side.
My question is this: How can I handle security properly with this? I have three scenarios:
GET api/messages: No need for security, I want to expose my site's messages to anyone who is interested via a Json REST API.
GET api/my/messages: I need to allow access to this only if the user is logged in (it gets the user's messages).
POST api/users: This is a function that should only be called from the server, and nothing else should be able to use it.
As the user is already logging in to my ASP website, how can I use their logged in credentials to authenticate them with my REST service? While the user is logged in, the pages client side will hit it regularly for updates.
Is there any sensible/standard way to do this? The core idea is that the client side code uses a REST API that is at least partially open to the public, and that in fact that API offers all of my business logic - only parts of it (like creating a user) are locked down to super-admins only.
Thanks in advance!
Create two authentication middleware handlers. One you add to all your "my" routes and another which you add to your POST routes.
The "my" authenticator takes the asp.net auth cookie that is present in the request and makes a http call to your asp.net mvc site with it.
You'll need an action which either returns a 401 if the cookie is invalid otherwise it returns some info about that user's permissions perhaps.
If the request into node doesn't have a cookie, return a 401 again.
In addition, to prevent excessive calls to your mvc site to check the cookie, you could use the cookiesession middleware to set a cookie on the client with a flag of authenticated. That will result in 2 cookies for your client, but that shouldn't be an issue. Just make the node one expire before the aspx one.
The POST authenticator middleware can use any shared secret you like between your node and mvc server. e.g. a special header in the request.
If the user is required to login you can use [Authorize] on your controller actions. Autorization will be handled like any other webrequest.
Furthermore you might consider to add a key to your api requests which you can provide in the initial page load. A autorized user will have a GUID which he will sent with the api call. You can check if this key was issued by your app to a valid user.
As you said all the secure calls already go through your MVC server code which in turn calls the Node.js code, am I right? Basically you need a way to block calls to this Node.js from other clients that are not your MVC code.
Thinking out loud, these are the ideas that pop into my mind:
Use SSL only between MVC and Node. You can set up client and server certificates so that the Node code will only respond after authentication (I don't know how Node handles SSL so you will need some documentation here
If you want, the Node server could also check the call origin and so you can filter based on IP and only allow IPs where your MVC code is sitting
Use an encrypted authentication token on the secure methods on the Node code. Again I'm not really a Node expert but I can imagine it has ways of decrypting a token, or you can simply base it on a random number with a common seed... If noone has access to your server code ideally noone should be able to guess this token. Again, SSL will help against traffic sniffing
I am quite sure that people will come up with other ideas. For me, the most basic thing is anyway ensure that the secure methods are only accessible through an SSL connection and on this connection you can exchange all the info (token, passwords, etc.) you desire.

How to implement HMAC Authentication in a RESTful WCF API

We are building a RESTful API using WCF (currently .Net 3.5, but will be moving to .Net 4 soon). We have a functional framework in place, but it is currently unsecured. It will need to be accessible from .Net applications as well as iOS, Android, and web applications.
We would like to use an HMAC Authentication scheme as described here and here, but both examples seem to fall apart when describing how to validate the hash. The first example fails to describe the UserKeys object (hashtable?) and the second example is missing the GetUserKey methods on the client- and server-side.
Can anyone provide an explanation of how the "User Key"/token is generated/stored/retrieved/used in those examples or provide a better example (with source code, if possible) of how to use HMAC Authorization in a RESTful WCF service?
Edit:
After more research, we determined that we needed more of an "Authorization" technique rather than an "Authentication" technique (semantics?). We implemented Basic Authorization and secured the API behind SSL. The Basic Authorization uses the same "Authorization" header from the web Request as the HMAC Authentication scheme, but passes a username:password string encoded in Base64 instead of a token. This allowed us to custom-validate a user against our database to determine if the user is licensed for and has appropriate security rights to access the desired API method.
We're certainly open to hearing other options on how to accomplish custom username/password validation and other methods for securing the API.
Retrieving the user key is just an implementation detail you can do any way you like but on the server it is often stored in a database along with the user name.
The basic approach is real simple.
Somehow the server and the client exchange a shared key for the user to use. This can be done any way you like, including sending an old fashioned dead tree style letter. Quite often this is just the password the user entered.
When the client wants to send a request he builds the complete request and then using the secret key computes a hash over the complete message body (and optionally some of the message headers if required)
Next the client add the computed hash and his username to the message in one of the headers and sends it to the service.
The service retrieves the username from the message header and searches the private keu for that user in its own database.
Next he computes the hash over the message body (and selected headers) using the key to generate its hash.
If the hash the client sends matches the hash the server computes the server knows the message was send by the real client and was not altered in any way.
Really the only tricky part is sharing a secret key with the user and keeping that secure. That is why some services allow for generation of shared keys with a limited life time so you can give the key to a third party to temporarily work on your behalf.
Implementation for HMAC we can find at
https://github.com/cuongle/WebAPI.Hmac

How to prevent just anyone sending a request to my web service

I have an app in C# which serializes an object into xml into a http stream to my server. The server has some php which runs a stored procedure in mysql with the xml data as its only parameter.
The problem is that someone could very easily just send up an xml of the same format with a whole lot of entires that would ruin the database with crap data. What are my options to prevent this from happening?
I'm pretty new to web requests so I don't even know where to start.
We require a username and password to be supplied to all input parameter lists which is validated against our back-end user login system before a request is processed. Low tech, but works for us.
You should use some form of authentication and authorization. In SOAP based services there's the WS-Security extension. Here's another article on MSDN that explains how this works. However I have no idea what is the support for those standards on the PHP side. If you are using some custom protocol you could simply require a username/password to be sent along with the request and verified on the server side.
Are you planning on having this client out-there in public hands on the internet? If so it may be impossible to prevent people using different software as they could always reverse engineer the application to find out what security mechanism you are using. As a result your only defence will be to validate the data thoroughly on the server.
You might get around this by modifying the client to require a user name and password that gets sent with data to your server using HTTPS, that way at least you know who did the damage. If however you have a more closed audience you could use some kind of client certificate system or IP filtering.
Our solution (and we're hopelessly naive in this respect) is that we generate a unique key per session on the server in a non-uniform manner (ie. it is difficult to predict what the "next" value would be), and give that to the client code as part of its login process. It is then required to pass that value back to use for each request as the first parameter.
This ensures that:
Logging out invalidates the authentication key
Username and password is not sent in cleartext for the web service requests
This does not ensure that:
Only our application code can talk to the server (the user might intercept the request, copy the key, and generate his own requests, as long as the key is still considered valid.)
What you're going to find is that as long as code on the users machine is talking to your server, you have no control over the code on that machine, only the code on that server. So if the users machine is sending you requests originating from a different program, that looks just like they would and should if your code generated them, you're going to have a hard time figuring out that this is what is happening.

Categories

Resources