using rest api in asp.net 4.0 - asp.net

Let's assume that client wants to be a new user(sing up) with using iphone/ipad application. I need to add this new user record in to MSSQL database in my host. This request should come to my asp.net pages, and then i need to reply to client. I was using this:
www.exampleWebSite.com/registerUser.aspx?newUserEmail=aaa#aa.com&newUserPassword=123
and then i can return result with JSON like this:
{
"processResult":"True",
"processMessage":"sign up is done"
}
it works like this but i know this is not good for security, right?
by the way, i can return all values(from mssql database) and all CRUD process from my asp.net web site. (.net 4.0) i must use this.
so first question, what is the best way for this? using rest api?
second question, how can i send the data? (client side is ios)
third question, how can i get the data? (host side is asp.net c#)
fourth question, can i develop rest api with visual studio 2010? or do i need higher version?
thanks!!

Several ways to do it but I can go over a few points
Make it a POST rather than a GET as you are doing it in the querystring. This is an idealistic approach, there's nothing stopping you from putting the username and password in the querystring but it's nicer if you put the registration info in the body.
Make it HTTPS and ensure, in the client, that you trust the certificate that the server presents. This allows you to maintain an SSL connection between the client and the server without someone snooping in on the body.
You may want to consider making your JSON response more meaningful. By virtue of it being a 200 response, you can imply that processing was successful. You can return a 401 or 500 if the processing was unsuccessful. The JSON response could simply return OK or a user token that the client stores and uses to communicate with your server.
The MVC Web API is a great framework for building RESTful web services in ASP.NET. See instructions here for VS 2010.
As for getting the data, you could use the generated token in each request to get user specific information; you would need to store that generated token upon user registration in a database against the user.
As a further topic, you may also want to, at least, read up on OAuth and implementing OAuth in your Web API. This would involve performing the login on your own website but giving the mobile client a secret token to use when communicating with your API; the token can also expire every, say, 30 minutes and you would keep reissuing new tokens for that user. However, depending on the nature of your audience and size of your application, you may not want to do this and just having a 'static' token for each user suits your purposes.

Related

Constrain clients to ones coming from the own app/website for unauthenticated web API

These are the criteria:
My users are unauthenticated.
My app is a single page web app (written in JavaScript) that uses RESTful web API endpoints to fetch data from my own server.
Objective: I'd like to constrain the web API to only allow requests from my own app, without requiring users to authenticate. Are there existing techniques for this?
The issue is that since the web app's code and the requests made by it are transparent to the client it can't hold a secret for authenticating with the server.
I thought about creating single-use access tokens on the server side, then use those from the client side for the API calls. Now this would make it harder to do requests from the outside, but still you could make requests if you fetch this token from the original website first (even if you'd have to do it for every request).
If it matters I'd implement this with an ASP.NET MVC website and ASP.NET Web API endpoints.
Similar to this question but not entirely the same.
Thanks in advance.
I asked pretty much the same question a couple of years ago, and for unauthenticated users, some kind of token is pretty much going to be your only option. It doesn't make it impossible to get unauthorized access to your API, but does make it a little more painful.
I took a slightly different approach in my solution, using 2 cookies to protect some anonymous GET requests. One of them was the anonymous identification cookie, which was used as an encryption salt for another custom cookie given to the page that delivered the javascript. Only when the API request received both of these cookies and the decrypted result was satisfactory did I allow the WebAPI to respond. But like I mentioned, this only makes it more painful to gain access outside of the javascript app, not impossible.
Here is a reference for using tokens in WebAPI: http://codebetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/

Authentication and authorization related doubts with asp.net web api

I have to start a new project to be developed in MVC 4 and Web API. I have prior experience with MVC 4 but with Web API this will be my first project. I understand that web api is there to be consumed by different platforms.
I have a few concerns related to web api. I am presenting them to you guys as following:
1) My first concern is related to user authentication. I looked into this SO question and followed the link1 and link2 given in the selected answer. I still have a couple of questions:
a) When we do user authentication through Form Authentication we create a cookie, that track if the user is authenticated or not, but with web api we do not store cookie, instead user credentials are passed in content header. I didn't get how user's logged in status is tracked in this case ?
b) My another concern is related to restrict unauthorized access, which I think I can find find out in link 1 and link2 provided above, if I am not wrong.
c) I looked at the Edward Brey answer (in the same SO question) as well for authentication but I didn't get the idea completely.
2) My second doubt is about mixing Form authentication and Basic Http authentication. Is it possible that for login I use forms authentication and then for consuming web api I use basic http authentication? If yes then please guide me.
My questions may sound inappropriate but please bear with me
1.a) Restful APIs are stateless, so you are not keeping track of user's logged in status, rather you are sending credentials which are verified for each of the requests
1.b) Yes, if not there are number of articles on web for that. Authorization Filters can help you in achieving this.
1.c) In short, he has mentioned simple logic to authorize user before executing any of the methods in your API. Call EnsureAuthenticated before executing any of the methods in a controller, or put that logic in you Authorize filter.
2) Yes you can do it. In Restful API's each call can be a new instance and you can pass in credentials with api requests whichever you are making.
If you go in discussion of Link 1 that you have provided, you will see:
In our specific case, the server generates the auth token by encoding
the concatenated username and password as Base64 (the reverse of what
is described in the article) and sending it back to the client via a
HTTP header when it performs their ‘log in’ action. The clients then
store this auth token and send it with each subsequent request that
requires it.
If the format of the auth token is well known (as it is in my case),
you could also just generate this yourself on the client and send that
without having the server do this work.
You can use your login to generate an authentication token for client, which you can use to send attached to your web api requests.

Token authentication and authorisation for a self-hosted ASP.NET Web API 2 REST service

I'm using VS2013 and Web API 2 to create a self-hosted (using OWIN), RESTful service over SSL using token authentication. Although I'm not a novice developer, this is my first time looking at ASP.NET technologies, so please keep that in mind.
I've got everything more-or-less working except for the authentication and authorisation parts. I fully understand the difference of authenticating a user (who is this user?) and authorising an already authenticated user to access a resource (can this user access this particular resource?).
A very simple overview of my auth process is as follows (makes some assumptions for brevity):
An unknown client connects to the API, e.g. GET api/values.
The server responds with a 401 and this response header: "WWW-Authenticate: Token".
Upon seeing this, the unknown client knows to connect to a different API endpoint here: POST api/auth (routed to the Login function), supplying the username and password.
The server will try to figure out if this is a valid user and can accept or reject the user depending on the validity of the credentials.
(Rejected) The server returns an error status code (403?). End of process.
(Accepted) The server creates a random token (e.g. a GUID) and stores it against the user record. Then it sends the token to the client.
The now authenticated client reconnects to the API, GET api/values, and this time also supplies the token.
The user returns the resource data to the client.
...
The user can log out by connecting to the same API as he used to log in: POST api/auth (this time, his request will be routed to the Logout function). This will remove the token from the server and the client will also have to remove its own token.
As you can see, this is a relatively simple process, but I can't find any concrete and simple examples to understand how best to achieve this with a self-hosted Web API 2.
I don't need to register users or do any password/roles management, etc. and there is no external authentication. All valid users have the same rights to access the resources and they're already created in the system by a separate process over which I have no control (I can only read their credentials for validation). Most examples I found are talking about security frameworks that I don't need, so I've ruled out using any of the following: Basic Authentication, Windows Authentication, Forms Authentication, Individual Accounts, ASP.NET Membership/Identity, OAuth, Thinktecture or any other security framework.
I've read articles about authenticating in a message handler and others about authentication in a custom Authorize attribute filter, while others even suggest I should use the new (in Web API 2) IAuthenticateFilter attribute. This is very confusing. Can you please advise on a very simple way to achieve my auth objectives? Any specific code examples will be greatly appreciated, even if they're just skeleton implementation or pseudocode. I just need some ideas to get me started.
After a lot of googling, I found this article on CodeProject: http://www.codeproject.com/Articles/630986/Cross-Platform-Authentication-With-ASP-NET-Web-API. While this is not Web API 2 or self-hosted, it has given me a number of ideas on how to proceed.
Someone also posted a comment to that CodeProject article referencing a NuGet package that may interest anyone looking for something similar: https://www.nuget.org/packages/WebApiTokenAuth. In my case, it is a bit much.
Finally, in addition to the authentication options mentioned in the question, there's also the option to write an OWIN middleware to do authentication if self-hosting using OWIN (as per the official MS recommendation). However, I plan to implement this particular form of token authentication with a message handler, as there's more support for this method available than for writing OWIN middleware.

Interacting with QuickBooks Online V3 API

I'm writing a web application (that is not to be published by Intuit on their App Center thing) to interact with QuickBooks Online (QBO) for syncing purposes, using VB.NET and ASP.NET. I'm having a hard time understanding how to do this exactly or where to start. What I understand this this:
User accesses your web application and the "Connect to QuickBooks" button (that Intuit requires for In-App authorization) is displayed.
Before the button is clicked you send a HTTP request to get OAuth request credentials using your consumer credentials.
Once the user clicks the button they get redirected to QuickBooks Online (QBO) where they can sign in and then authorize access to a certain company, giving you authorized request credentials.
QBO then redirects back to your site indicating you have authorized request credentials in which you send a HTTP request to get access credentials.
Once you have the access credentials you are basically free to interact with the QBO V3 API.
Using the access credentials you can then construct HTTP requests that send a particular HTTP method with XML/JSON in the body to perform a corresponding CRUD operation in QBO and QBO sends a response to indicate whether it was successful or not.
When your application is done interacting with QBO you simply make sure the access credentials are stored somewhere safe and let the user continue on with their life.
(Side Question: Is this correct or did I miss something or misunderstand something?)
My main question: Do you, as the app developer, even need to construct these HTTP requests or do you use their SDK or something completely different and I'm just not getting it?
I've tried to figure this out but it sounds like you're supposed to construct this all from scratch but then I look in their SDK and they have classes for all the different entity types but then their serializer doesn't serialize correctly and they talk about their DataService class and how you use that to send objects over and using some JavaScript files they host that I have only seen referenced but not explained by them, or anyone really, and information I do find seems to be outdated/deprecated and ya...
Maybe it's just that I'm new to web development and all this is way over my head right now, which very well could be.
(Off-topic-sorta: Is it me or is their site ridiculously broken? It just seems like a lot doesn't work correctly or things are just hard to navigate and find...)
Anyways, thanks for any help anyone can offer. If I need to give more details or ask a different question or something, just let me know. New to this and it's harder than I thought to ask things haha.
My main question: Do you, as the app developer, even need to construct
these HTTP requests or do you use their SDK or something completely
different and I'm just not getting it?
This is entirely up to you, the developer.
If you want to roll your own and construct your own HTTP requests, you certainly can. You almost certainly will still want to use a pre-packaged OAuth library, as OAuth is not trivial to implement.
However, you could also certainly use an existing code library/DevKit too, in which case the library/DevKit will construct the HTTP requests for you.
The DevKits should contain example code to show you how to actually do this stuff, so that might be your best place to start.
You are on right track.
First of all you need to register with IPP to get
ConsumerKey,ConsumerKey secret and Application ID.
https://developer.intuit.com/docs/0025_quickbooksapi/0010_getting_started/0020_connect/0010_from_within_your_app/implement_oauth_in_your_app
if user don't have access token then 'connect to quickbooks' button shows up otherwise you can make it hidden.
request code : https://github.com/IntuitDeveloperRelations/IPP_Sample_Code/blob/master/QuickbooksAPI/DotNet/WebForms%20application/QuickBooksApiDotNetWebFormsSampleApp/OauthGrant.aspx.cs
access code : https://github.com/IntuitDeveloperRelations/IPP_Sample_Code/blob/master/QuickbooksAPI/DotNet/WebForms%20application/QuickBooksApiDotNetWebFormsSampleApp/OauthHandler.aspx.cs
After getting accesstoken, accesskey secret and realmID (companyid) save that to your database.
make sure to encrypt.
so next time same user connect to quickbooks they don't need to go through all of the above steps.
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
ServiceContext context = new ServiceContext (appToken, companyID, IntuitServicesType.QBO, oauthValidator);
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/0150_ipp_.net_devkit_3.0/0002_synchronous_calls/0001_data_service_apis

Authenticate users syncing time out for 2 different sites

I have been puzzling over this and can't think of an good way of doing this. I am developing a website that would require the user to log in to use the system. I'm thinking of using ASP.NET MVC 4's built in authentication. That isn't much of a problem.
The user would be able to use tools on another server (our server would authenticate him and tell the other website, he is good to go, these messages are passed via HTTPS using XML). The other server, require us to create an authentication token for the user to use when the messages are passed between us.
We need to keep the token in our database to authenticate for every request/response with the other server. Which means that this "token table" knows nothing about the forms authentication time out on our server and vice-verse.
Now the problem, let's say the user uses the other server's tools. He would be on the other server for a long time, this would cause the authentication on our server to log him out, since there doesn't seem to be any perceived activity. The other server will not log him out since we are manually maintaining the token. This would be a troublesome for the user, because now, if he needs to use our service, he'll have to log in again even though he was "online" all the time.
Is there a way to "sync" the 2 authentications? At first I was thinking of getting our server to look up the "token table" (instead of using the built in authentication) so that if the last activity was x ago, the user will be required to log in again, this would solve the untimely logging out from our server. But I'm worried about the security implications.
What would be the best way to do this?
Thank you.
Desmond
If I've understood you correctly you are using Forms Authentication in an MVC4 application to authenticate users, but users will also use another web service located on a different server and so while they are using this other server you don't want the MVC4 application's authentication (for the user) to timeout. Is that correct?
If so, one idea that comes to mind is that your MVC4 application could have an API to the external world that would take in a username and use RenewTicketIfOld() to refresh the timer associated with the ticket. You could do this via the other web server making an HTTP request or by simply placing some AJAX on the page to call the API on every page.
There are, of course, security concerns with this method that you would need to consider. Without knowing more about your situation I'm not sure what solution would be best.

Resources