Authorization/Authentication in asp.net web api - c#

I need to create a couple of simple methods using asp.net web api. I am very new to this so even the simplest thing is proving difficult for me. I want to decorate my api controller with [authorize] and [authenticate] for the obvious reasons.
My question is centred on how I call these methods from my ajax calls (which is how I'm intending to call them). I'm reading that I need to pass the user id and password with each of my calls but how do I do this using ajax? Or do I even need to do this manually or asp.net somehow does it for me (if that even makes any sense)? Because when I'm doing action calls that need to be authenticated/authorized using forms in mvc, I certainly don't do it expressly and I imagine somehow somewhere in the code it just gets done.
As is clear, I'm very lost. Any help is appreciated.

Related

Can Ajax access non-controller methods?

I’ve got a class that contains many helping functions, that make easy to do many things for my web app. I have attempted to use Ajax and access this class but it didn’t work.
Am I trying something impossible? Can Ajax only access controllers?
The short answer. Yes, you can make ajax calls into a class outside of controllers via custom routes in the RouteConfig class in the RegisterRoutes method. Setting certain routes (say to your helper functions) to be ignored by the handlers and letting traffic flow through.
The most correct answer for your situation. You shouldn't. Any ease of use of the helper functions would be quickly diminished with the work you would have to do because you are now responsible for handeling all http protocols coming in and going out of your helper classes for communications from client to server and back.
...and your coworkers (or anyone inheriting your code) will end up loathing you for breaking convention without a real need to do so.
Instead of reinventing the wheel just set up a Helper controller your project and make that responsible for fielding http requests back and forth and wrapping your helper functions. It can be a bare bones controller that doesn't return any actionresults and you dont have to build views, it can just be responsible for returning Json with nothing else built out. It won't break convention, you will be able to take advantge of years of knowledge and buildout for http handeling AND your fellow devs won't want to murder you in your sleep because you did something just because you could.

Build an API for Multiple

I'm building an API using WebAPI that will be accessed via AJAX calls. However, the API controller will need more than just one POST method. I understand I can specify {action} in my routing, but because I've seen that this is not recommended - am I using the right tool? So 2 questions:
Is Web API the best tool for this, or is there something else I should be using?
Why should I not use more than one POST method in a WebApiController? Is including {action} in my routing a good enough solution to this problem?
1. Is Web API the best tool for this, or is there something else I should be using?
I think WebAPI is a fine choice for you, regardless of whether you have one or many POST calls per controller.
2. Why should I not use more than one POST method in a WebApiController?
To remain RESTFul you'll want a controller per entity type. Without getting too deep into details, a POST against a specific type of entity should be the 'ADD entity' call, and why would you have more than one of those? Having said that, you don't have to be fully RESTFul... if your requirements suite a multi-POST model then go for it, you can always refactor later if necessary.
...Is including {action} in my routing a good enough solution to this problem?
Again, if your goal is to be RESTFul then this isn't a great practice. However, if you have needs that are best achieved using action routings then go for it. REST is not the only model.

Dealing with Async in MVC

I'm having trouble consuming an async service within MVC. The service returns data which is used on all pages. Hence my idea was to create a global action filter. As is well documented you can not make async calls in an MVC action filter.
My question is, what approach do people use to get around this limitation? I can't create a global action filter and I can't create a child action method for the same reason.
I'm currently considering creating a web API method and then using WebClient to make a synchronous call. This feels like madness so would welcome any suggestions.

REST based MVC site and/or WCF

I know there are actually a number of questions similar to this one, but I could not find one that exactly answers my question.
I am building a web application that will
obviously display data to the users :)
have a public API for authenticated users to use
later be ported to mobile devices
So, I am stuck on the design. I am going to use asp.net MVC for the website, however I am not sure how to structure my architecture after that.
Should I:
make the website RESTful and act as the API
in my initial review, the GET returns the full view rather than just the data, which to me seems like it kills the idea of the public API
also, should I really be performing business logic in my controller? To be able to scale, wouldn't it be better to have a separate business logic layer that is on another server, or would I just consider pushing my MVC site to another server and it will solve the same problem? I am trying to create a SOLID design, so it also seems better to abstract this to a separate service (which I could just call another class, but then I get back to the problem of scalability...)
make the website not be RESTful and create a RESTful WCF service that the website will use
make both the website and a WCF service that are restful, however this seems redundant
I am fairly new to REST, so the problem could possibly be a misunderstanding on my part. Hopefully, I am explaining this well, but if not, please let me know if you need anything clarified.
I would make a separate business logic layer and a (restful) WCF layer on top of that. This decouples your BLL from your client. You could even have different clients use the same API (not saying you should, or will, but it gives you the flexibility). Ideally your service layer should not return your domain entities, but Data Transfer Objects (which you could map with Automapper), though it depends on the scope and specs of your project.
Putting it on another server makes it a different tier, tier <> layer.
Plain and simple.... it would be easiest from a complexity standpoint to separate the website and your API. It's a bit cleaner IMO too.
However, here are some tips that you can do to make the process of handling both together a bit easier if you decide on going that route. (I'm currently doing this with a personal project I'm working on)
Keep your controller logic pretty bare. Judging on the fact that you want to make it SOLID you're probably already doing this.
Separate the model that is returned to the view from the actual model. I like to create models specific to views and have a way of transforming the model into this view specific model.
Make sure you version everything. You will probably want to allow and support old API requests coming in for quite some time.... especially on the phone.
Actually use REST to it's fullest and not just another name for HTTP. Most implementations miss the fact that in any type of response the state should be transferred with it (missing the ST). Allow self-discovery of actions both on the page and in the API responses. For instance, if you allow paging in a resource always specify in the api or the webpage. There's an entire wikipedia page on this. This immensely aids with the decoupling allowing you to sometimes automagically update clients with the latest version.
Now you're controller action will probably looking something like this pseudo-code
MyAction(param) {
// Do something with param
model = foo.baz(param)
// return result
if(isAPIRequest) {
return WhateverResult(model)
}
return View(model.AsViewSpecificModel())
}
One thing I've been toying with myself is making my own type of ActionResult that handles the return logic, so that it is not duplicated throughout the project.
I would use the REST service for your website, as it won't add any significant overhead (assuming they're on the same server) and will greatly simplify your codebase. Instead of having 2 APIs: one private (as a DLL reference) and one public, you can "eat your own dogfood". The only caution you'll need to exercise is making sure you don't bend the public API to suit your own needs, but instead having a separate private API if needed.
You can use RestSharp or EasyHttp for the REST calls inside the MVC site.
ServiceStack will probably make the API task easier, you can use your existing domain objects, and simply write a set of services that get/update/delete/create the objects without needing to write 2 actions for everything in MVC.

Writing Custom Attribute in C# like ASP.Net MVC Authorize attribute

I like ASP.Net MVC Authorize attribute, I can extend it and build my own logic and decorate my controller with it. BUT,
In my architecture, I have one common service layer(C# Class Library). End user can access my application via ASP.Net MVC web site or via my exposed REST WCF Webservice layer.
My asp.net MVC application and REST WCF service layer both in turn access my common service layer.
I want authorization to happen in this common service layer and not in ASP.Net MVC Controller or in my exposed REST Service layer.
Can I create ASP.Net MVC Authorize attribute like thing to decorate my methods in the common C# class library? This attribute will take parameters and will decide if the current user has access to perform that function or not?
Thanks & Regards,
Ajay
What you're looking for can be achieved using AOP library, like PostSharp (http://www.postsharp.org/). It's more complex than using Authorize attribute in mvc, but is still quite simple.
Another way to handle this is to use the [PrincipalPermission] attribute in your service layer. This can prevent callers from executing a method (or accessing an entire class) without the defined authorization.
No, AuthorizeAttribute works because the MVC framework explicitly invokes it before calling the method. A similar feature for your service layer would only work if your clients explicitly invoked it, as well. It would not be reasonable to presume that even a well-intentioned client would always remember to look for the attribute and invoke it. WCF has its own security. You should use that instead of writing your own.
This shouldn't be too hard to do - there are a couple of places that you could reflect out the attribute and handle it accordingly:
On application start in Global.asx you can customise routing and locations for views
Underlying ASP.Net request events still fire, so you could override one of them
Create your own base controller and override OnActionExecuting
Update following comment
Ahh, I see. In that case if you're making direct calls then you should check out Code Access Security, which I think covers what you mean.
Alternatively a custom attribute might make sense as long as you are using some kind of factory pattern - then the reflection call that gets the factory could check the attributes.
If you're not using reflection to retrieve your classes or call your methods (which is essentially what routing does in MVC) then you won't get the chance to check your attributes.

Categories

Resources