Web Api Rest service Aunthentation for IOS - asp.net

I have implemented basic aunthentation from url http://www.asp.net/web-api/overview/security/basic-authentication. Now I have a question that how i send the basic aunthentation to user on login or on register action that is inside controller.
in short how i create a token and integrated in responsed header.
Kindly help me i have spent more then 4 hours on it.
Thanks

The token is created manually from the credentials users provide.
This means that you have to show a login form in your ios application, gather the username and password and then append the authentication header to each request.
The name of the header is Authorization.
The value is computed as follows. You take the username + ':' + password and encode such string to a byte array. Then you get base64 out of the array.
The value of the header is basic [base64ofusernamepassword] where the [base64ofusernameandpassword] is replaced by the base64 of the username and password you just computed previously.
The exact way of appending custom headers to requests can vary depending on the client technology but it should be easy, no matter which technology is used.

Related

How are authorization tokens stored / recreated by the browser?

I am Looking at the Network activity of this page: https://helm.csod.com/ux/ats/careersite/4/home?c=helm&lang=de-DE.
Specifically at the post request with the Name: "search". Its using an authorization token.
tldr: How is the following authorization token stored on the Client side?
Goal:
I would like to understand how the browser (client-side) stores this authorization token. I dont Need to get the data or know how to scrape with selenium or sthg. I would just be interested in the mechanics behind.
What i tried:
I find the token in the page source: view-source:https://helm.csod.com/ux/ats/careersite/4/home?c=helm&lang=de-DE.
It seems like there is an object csod created in /player-career-site/1.15.4/pages/home.js.
then the key is stored in csod.context.
Finally, csod.player.initialize(csod.context) is called.
Unfortunately, i failed digging in the Code and finding These function as there where too many Matches for initialize and my js are skills too bad.
As storage i am only Aware of the Cookies. It might be transformed / encrypted and stored in the cookies? But how is it then restored to the "original" token, before being added to the request Header?
This seems to be a CSRF prevent method.
The token is created with a key in the back end, it stores the original key in a session and sends the token to the client side.
When the client sends a request, the token is posted with the data as a header or with the data, then the back end gets the stored key in the session, generate the token with the same method and compare it with the posted token. If they are equal there is no problem, access granted.
It is not necessary to restore as you can't decrypt that depending on the algorithm (sha256, md5, etc)
And the browser don't do that, as it can be manipulated, there is no sense to.
The token sent here is JWT(JSON Web Token). This is a widely used standard authentication mechanism.
You can create your own token in any languages like JS, Java, PHP, Python, etc.
I am adding a basic authentication flow:
Let's say a user comes on a form. Enter his email & password.
Now an HTTP request is being sent to the server with credentials. The backend server checks the details and if successful, then returns a response containing the authentication token.
Most of the time this token is stored in localstorage and sometimes in cookies.
Now for every request the token is picked from the stored location and sent in the header.
On the backend, it is checked if the request header has the details or not. And then respond accordingly.
At last, whenever someone logs out then that token is removed from the front end.
I hope it helps! Let me know if you have any queries

how does ASP.NET validate anti-forgery token

I wonder how does ASP.NET check if an anti-forgery token is valid or not? Like where is ASP.NET storing those tokens? And how are they stored?
The short version is that a generated token is stored in 2 places: (a) cookie (b) hidden form value. When the form is submitted, these 2 values are compared against each other to determine if they are valid. For further reading:
http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-(csrf)-attacks
http://www.codeproject.com/Articles/793384/ASP-NET-Anti-Forgery-Tokens-internals
A stepwise explanation that is more clear than the accepted answer imho (from https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks)
The client requests an HTML page that contains a form.
The server includes two tokens in the response. One token is sent as a cookie. The other is placed in a hidden form field. The tokens are generated randomly so that an adversary cannot guess the values.
When the client submits the form, it must send both tokens back to the server. The client sends the cookie token as a cookie, and it sends the form token inside the form data. (A browser client automatically does this when the user submits the form.)
If a request does not include both tokens, the server disallows the request.
The above description is not all what is done, in case of AjaxRequest the antiforgery, specifically in get requests, will not usually send the Form with the hidden value for comparison, instead you will need to set a header value with the same content of the cookie via javascript.. the header name that you should set is by default X-XRF-Token header [related to angularjs] ... of course you will need to disable CORS or enable it for only specific domains to protect the APIs, SAMEORIGIN also need to be set to avoid clickjacking ..

OAuth access token and refresh token creation

I'm implementing my own OAuth authentication system (with refresh_token support) for an app and I have some questions about how to do it:
Client identification: The client is registered in the auth server and gets a client_id and a client_secret. How do I generate it? is there some kind of relation between both values?.
User authentication: The client sends the users_credentials (username+password for example) + client_id and gets a refresh_token and (temp?)access_token. That access_token is the one I should use in further request or I should use a accesss_token`=F(refresh_token,access_token,client_secret). In the second case what does the F function consist on?
Access token refresh: The client send client_id, refresh_token and gets a access_token (and a optional new refresh_token). Does the access_token need the same conversion (whatever it be), as in the point 2?
If I'm wrong, when and how is the client_secret used?
Complete answers and concrete examples will be "bountied".
The authorisation/authentication server generates these values when you create an account with them (for instance when you create a developer account with Facebook or Google). If you are doing these parts yourself, they should be cryptographically secure pseudo-random numbers or letters. Remember that the client ID is usually publically visible, so choose a reasonably large set of alpha-numerics (I use 30 characters). The secret is private and can be harder to guess so I chose 30 digits with letters, numbers and symbols. These are not related to each other, it is just that one is public and the other isn't.
The usual way this works is that there is a browser redirect to the auth server passing the client id in the URL (and redirect uri) and specifically NOT the user id and password. The whole point of OAuth2 is that the client system never sees the user name and password, only the auth server. After this redirect, the auth server verifies the client id, checks the username/password (for instance) and then returns to the redirect uri with a temporary code. This temporary code is passed back to the Auth server in order to obtain an access token. Since this call is made as a POST from the server, it also passes the client secret to verify that it really is the correct client system and not someone who stole the client id from somewhere else. At this point, the auth server will return an access token (and optional refresh token - you do not need to use them, I don't).
If the client system wants to log the user in without them having to type in their username and password all the time, it can use a refresh token, if available, to call back onto the Auth server and if the Auth server is happy that the refresh token is still valid and any other business rules are correct, it can give you back another access token directly without the user being involved.
I recommend reading the OAuth2 spec here: OAuth2 Spec RFC6749. It can take a while but if you delete the bits you don't need and reduce the amount of data, there are plenty of useful examples in it.
FIRSTLY, The client identifier can be any string that you want, but it should be unique for each client. It can even be the client's choice if you wish.
The client secret should be a cryptographically strong random string. Here is how you could generate one in C#:
RandomNumberGenerator cryptoRandomDataGenerator = new RNGCryptoServiceProvider();
byte[] buffer = new byte[length];
cryptoRandomDataGenerator.GetBytes(buffer);
string uniq = Convert.ToBase64String(buffer);
return uniq;
SECONDLY, The whole point of OAuth is to allow external apps to do things on your behalf without asking for your credentials. So, you need to implement an authentication server that does the logging in part for you. The user opens the app and gets an option to Log in using your website. You tend out access tokens and refresh tokens once the user has keyed in his credentials. The app can then simply use the tokens to perform actions on the user's behalf. I wrote an answer to How would an efficient OAuth2.0 server / provider work? that explains how access tokens can be constructed.
Remember, the need for refresh tokens and the lifetime of access tokens purely depends on how you intend to use them and what does your security framework look like.
LASTLY, The refresh token can also be an HMAC encoded string/a JSON object as I had explained in the answer to the linked question. You can have random refresh tokens and a large backend storage to keep it to verify the tokens in the incoming requests, or have HMAC encoded strings for added security/less storage requirements/latency to decrypt/encrypt tokens.
Also, do make sure that you go through all the flows and possibly the RFC too as mentioned by Lukos.

Prevent Password being sent over HTTP GET

I have come across a strange requirement during Security Review where I have to prevent username and password is being sent over HTTP GET in asp.net web forms.
Scenario is like this.
We have simple asp.net login form with user name, password and Submit button(POST method). During security review, the security tester changes the Form method to GET using some proxy tool(Burp Suite),then the user name and password is sent over as query string.
GET /Login.aspx?_LASTFOCUS=&_EVENTTARGET=&_EVENTARGUMENT=&_VIEWSTATE=''&_SCROLLPOSITIONX=0&_SCROLLPOSITIONY=0&__EVENTVALIDATION=%2FwEWCgKm973fCgKOieLQt9kH6PhK0wq%2FpfP8pXG%2FF&%24txtUser=abc#abc.com&txtPassword=1233&%24btnLogin=Login
As per the security testing team the GET (form method changed to GET using proxy tool) method should not pass the user password in query string.(as per my understanding GET will always pass value as query string even if it is password field)
An easy way to acheive what you need is to speficy server side to only look at the posted values server side and ignore the query string items, for example by using
Request.Form["foo"]
Instead of
Request["foo"]
Or
Request.QueryString["foo"]
There is no security reason for this, really you just want to be using SSL.

Access token implementaion in ASP.NET

How to use access-token concept that is used in facebook.
1)Can we implement same concept in ASP.NET based web application?
2)Can we use this concept in adding security to access in webservice ASMX and WCF ?
After long time I have found the answer I have posted.
If I am wrong please review my answer.
1) In Facebook server flow authentication when user is successfully authenticated Facebook generates authorization code parameter name as code.
2)In second step using all this parameter authorization code with client _ secret ,client _ id , redirect _ uri , state call Webrequest or call service if success then response have two parameter accessToken ,expires _ in.
3) This accessToken is used for getting userinfo like firstname,lastname,birthday etc with specified scope.
And this is general scenario that is used with WCF and ASMX webservice by storing valid accessToken to safe place or further use.
1) Access token is just a hash from some parameters, e.g.:
MD5(userName, userMail, someSalt, someOtherStuff)
So you can implement it for sure the way you like it. But better if it contains some secret information that can be retrived only by current user
2) Yes you can. As social networks like facebook do it:
there's some application secret key that is known on a server side (where your service runs), and some signature that can be retrieved from facebook api for some app and user and some other information.
Your facebook app gets that signature, it can use it to make hashsum with other parameters like userLogin, application scores or w/e else. Sends it to server.
On a server side you generate signature same way as your appliaction do based on parameters. If signatures are same request is valid. If know - someone is trying to do dirty things :)

Resources