I've been following a series of videos on how to create a web API using MVC 4. The sixth video describes the authorization process, but it is both too complex for what I want, and it somehow redirects to a form (which makes no sense to me, but then I'm new to this stuff).
I've used API's from other sites, and they usually use one of 2 methods:
a token in the url (http://myurl/api/service/?token=[bunch of characters here]
a username or password (or token) in the header
I'm leaning towards the second method, as it means I wouldn't have to add a parameter to each of my methods.
If I use this approach, do I need to add code to the beginning of each method to check the headers (request.headers?) for username/password (then find them in our database and see if they have permission to access this method)...Or is there a simpler way of doing this?
You can mark your Controller class with attribute which is derived from AthorizationFilterAttribute.
http://msdn.microsoft.com/en-us/library/system.web.http.filters.authorizationfilterattribute(v=vs.108).aspx
In this case you will not need to write authorization checks in every method, but only in one place.
This approach is well described under the following link:
http://www.tugberkugurlu.com/archive/api-key-authorization-through-query-string-in-asp-net-web-api-authorizationfilterattribute
Related
I have an asp.net application that I'm attempting convert the front end to Angular. Getting header information is important to the view. I'm used to getting the header information like so in C#:
httpContext.Request.Headers["USERID"]
How can I do the same thing in an angular controller?
In asp.net each request runs in its own independent context and hence the header access as you have shown in your code make sense.
This does not hold good for angular or in fact any client side framework. You can always get the headers for any request or response made using angular $http but the question is which request? During the lifetime of the app you would make many such requests.
Let's say you want to get the current userid, you can create a service that returns the logged in user. There are two ways to implement such a sevice
create a method on server to return this data. Invoke this method from service and cache results
on the client side assuming there is a login request made through angular, implement a success callback method which can update the service with the logged user id.
You can look at $http documentation here to understand how to access headers.
I've watched and viewed lots of pages on securing asp.net web api's - including: http://weblogs.asp.net/jgalloway/archive/2012/03/23/asp-net-web-api-screencast-series-part-6-authorization.aspx and http://weblogs.asp.net/jgalloway/archive/2012/05/04/asp-net-mvc-authentication-customizing-authentication-and-authorization-the-right-way.aspx - however, I've not yet seen a KISS type example.
If I have a web api, which returns a list of cars for example - and I am working with a 3rd party (ie. not my own website or server/domain) who wants to query (get) and insert (post) lists of cars by a type, into my database, how so I authenticate them (via https)?
Do they simply add (into their JSON GET/Post) something like:
[
{"username":"someusername","password":"somepassword",
{
"carTypeID":12345,
"carTypeID":9876}
"carTypeID":2468}
}
}
]
I can then grab the username and password, and check against my membership database in .net, and "IfUserAuthenticated" go on to process the rest of the JSON?
Or is there a better way of doing this? I've heard of adding details to headers etc - but I'm not sure if that's for a reason, or over complicating it. I've also heard of setting tokens which are sent back to the 3rd party - if that's the best method, what instructions do I give them got building their side of the app that will use my API?
Thanks for any advice/pointers,
Mark
If you want to keep it simple you can use Basic authentication. Over SSL it's quite secure. It simply involves adding a header to the request:
Authorization: Basic <username:password encoded as base64>
You can find a way to implement it here.
You can use HTTP Basic authenticaiton along with SSL. Its very simple to implement using message handlers and is supported out of the box on many platforms.
See my blog for an example (it is very easy to integrate with membership provider of your choice)
http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/
I've written something similar for the Web API:
http://remy.supertext.ch/2012/04/basic-http-authorization-for-web-api-in-mvc-4-beta/
It's in use at a few places now and we've been using it since about 2 month in production. Seems to work fine.
I want to submit a form using AJAX to a MVC 3 Controller.
The form and the controller are on two different domains, which is why i want to use CORS.
I have read that the following code should do the trick in ASP.NET:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
from http://enable-cors.org/#how-asp.net
Should this code go directly in the controller that takes the form data?
As far as i know, there has to be some exchange of data between the client posting data and the server, to determine wether CORS is enabled/supported or not, so i figure that the one line of code has to go somewhere else?
Thanks
This could go in the controller. Actually I would probably externalize it in a custom action filter to avoid repeating it in every controller action that needs to be invoked from a cross domain AJAX call. There are no additional steps necessary. Just make sure that your browser supports CORS because if it doesn't adding this line will have strictly no effect whatsoever.
My back-end server is built using the Microsoft WCF REST Starter Kit Preview 2. I want to add some request processing to all requests, except for those methods I explicitly disable by marking them with an attribute. I have over a hundred service methods and there are only a few I want to exclude from this extra processing. I'll tag them all if I have to, but I'm trying to avoid disrupting what's already written.
I haven't seen anything I can add to WebInvoke, and adding an interceptor won't let me examine the method that the request is routed to.
I am asking for an explanation of how to register HttpOperationHandler object(s) so I can do my extra request processing (i.e. authorization based on information in the request headers) before it is handed off to the method it was routed to. Can someone please explain how to do this, without rewriting my existing codebase to use Web API?
You can't use an HttpOperationHandler with WCF REST Starter Kit. However the Web API is very compatible with ServiceContracts that were created for WCF REST Starter kit. You should be able to re-host them in a Web API host relatively easily. You may have to change places where you access WebOperationContext, but it should not be a huge change.
I solved my problem by adopting another method. It authenticates all requests. I can't control which method it applies to, but I was able to work around that.
I created a custom ServiceAuthorizationManager class to process the Authorization header. The CheckAccess() method returns true to allow the request through or false if the user is not authenticated or not authorized to perform the service. I hooked it up to the ServiceHost for my services by creating a custom WebServiceHostFactory class and assigning an instance to the Authorization.ServiceAuthorizationManager in its CreateServiceHost() methods.
Although I can't directly check method attributes for the service being executed, the Message.Headers member of the object passed to CheckAccess() has a To property that contains the URI of the service being called. If necessary, I could examine it to determine what method the request would be routed to.
The ServiceAuthorizationManager applies to all requests, so no web methods or classes must be marked with any special attributes to enable it.
I have some functionality in the code behind, which after executing needs to forward the request to another page. I want to pass along data like you would by setting a request attribute in Java (i.e. - I don't want it in the query string of the redirected response). Is this possible with ASP.NET (c#)?
You can use Server.Transfer if you want to forward the request and keep all of the Request variables, or you can use Session.
Are you using ASP.NET Webforms or MVC? The following will redirect your request to a new page. You'll have to test and see if it forwards post data (I'm not sure). Now that you mention it, I don't think ASP.NET has a built in "forward:" request like java does. I think it just has "redirect" for security reasons. (Someone correct me if I'm wrong).
In Webforms:
try Response.Redirect("mynewpage").
In MVC:
at the completion of your action method return Redirect("mynewpage")
I don't know your use case, but it is generally not good practice to pass post data to a different page/request. Typically the posted action will take care of persistence, and then a GET request will be issued to the redirect page. If the redirected view needs access to the posted data, it should go to the persistence mechanism (DB) to retrieve it. This method is more secure, and generally better practice. This is a very general guideline, so use it as your needs allow.
HTH
Yes - See the reflection code at:
HttpModule to add headers to request
However - the question is - do you really want to use request headers? probably not. its a hack to use them. If you simply want to pass information, use the Context.Items dictionary to transfer your items between requests with Server.Transfer.
Depending on what you are doing and where your events are, you can also make use of Cross Page Postback.
See http://msdn.microsoft.com/en-us/library/ms178139.aspx
Otherwise, I'd go with vcsjones answer of Server.Transfer