How to do verify domain in RESTFul with ASP.NET MVC 3? - asp.net-mvc-3

Currently, I building my website personal (using ASP.NET MVC 3).
I want to provide some services to public by using API, finished building everything, but RESTFul does not contain on Authorization, I read this article:
http://blogs.msdn.com/b/rjacobs/archive/2010/06/14/how-to-do-api-key-verification-for-rest-services-in-net-4.aspx
But I could not use the method with ASP.NET MVC 3!!
I want the following:
1- Send Api-Keys for those who want to use my service
2- verify Domain (owner api-key == OR != owner domain) !!!! Is this possible?

You could make it a requirement that they always send their key in the requests. Then you could subclass the AuthorizeAttribute to check if the key in the request matches something in your datastore. This attribute can then be decorated on your controllers.
You can get the domain making the request using Request.UrlReferrer

Related

Using role-based authentication in ASP.NET Core is ok with using Ajax?

I am using ASP.NET Core MVC. In my project I use Ajax in order to get some JSON data from an action on my controller. It requests data from the database, then return it as json. It works well.
I want to use role-based authentication in my ASP.NET Core MVC project.
This is my question: if I use a controller action restriction by something like [Authorize(Roles = "Admin")], will it allow anyone whose role is "Admin" to call this method? (I mean will it work without any other trouble just by logging in as Admin)
And will it disable accessing those data when the role is not "Admin"`?
I have not still add Identification to my new project and I'm new to using Ajax.
I have just tested it and it does as desired. It return 401 Unauthorized status code when the user is not authorized and 200 OK success status response code. Thanks guys for your responses.

How to secure a restful webapi core

I am working on a webapi core and have few methods within it. This is a restful web api.
I don't want a situation where people will grab my uri and start using it. I want only
authenticated users to have access to the webapi. I am new to this. I am using the webapi core.
A xamarin.forms app will be using this webapi.
I will appreciate some directions on how I can secure this.
I would suggest you below approach
User DB - either Identity or custom store
Authorize your web api controller
Use JWT for generating JSON web token and validating them.
Provide access if only JWT validates. Excellent support in ASP.NET Core API
Provide Login (token generator API endpoint), pass JWT for further API calls as Authorization header
I think this REST Security Cheat Sheet can be useful
https://www.owasp.org/index.php/REST_Security_Cheat_Sheet
https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/REST_Security_Cheat_Sheet.md

Simple Web Token (SWT) Authentication in Web Api 2 OData endpoint

Ok, the situation is this.
We already have an existing ASP.NET MVC 5 site with Custom Forms Authentication, Logon, Registration etc with a custom database for roles and profiles already implemented.
We now are adding some new functionality to the MVC site and we decided to use Web Api 2 OData 3 endpoint which lives in another domain. The Web Api currently doesn't include any authentication but we need to be able to map the requests to a certain user to get his roles etc from the backend. The MVC and API sites use the same backend.
What we would like to accomplish is, that when the user logs on in the MVC site, the MVC site calls the Web Api server-to-server with the user's credentials and receives a token that the client can then use to call the web service with.
When API receives a request with the token, it can then map the request with the user in backend and do authorization.
As far as I understand it, Simple Web Token (SWT) could pull it through. But considering the environment, .NET 4.5.1 / Web Api 2 / OData 3 with Entity Framework in Azure Web Role, I started thinking is this SWT something I should really use or if there is any NEW technologies recently published that could easily pull this through. I don't want to add any unnecessary 3rd party dependencies to the project if the .NET stack already contains something like it.
So, what would be the simplest way of pulling this kind of authentication through without adding unnecessary dependencier to the project.
The solution we are looking for, is only temporary meanwhile we redesign our authentication scheme. So we are looking for something really simple to implement that works with least dependencies that need to be removed later on.
I'm using this in a project I'm currently working on. I use the OAuth 2.0 OWIN Middleware component that ships with Web API 2.0 (if you add a new Web API project with Authentication enabled, it includes the base infrastructure).
You would use the Resource Owner Password Flow as defined in the OAuth 2.0 specification. Basically you request a Token from the Web API OWIN Middleware sending:
client_id - identifies your MVC endpoint
client_secret - identifier your MVC endpoint
username
password
And in response you get a bearer token. The token generating is based upon a claims principal, the OAuth middleware component has predefined hooks for adding claims. This token now needs to be added as authorisation header to each response. On the MVC side you might add this to session so that it's always available to make backend API calls in the context of the user associated with an incoming HTTP request. If you're using WCF Data Services Client, you'll need an authorisation service/manager or similar that you can hook into OnRequestSending and OnResponseReceived events, so that you can insert that bearer token into the HTTP headers.
You can customise the OAuth Middleware component as you need to quite easily, it took a bit of time to figure it out as it's not too well documented, but downloading the Katana source code did help a bit as the source code does have some good documentation.
The nice thing about it all is that you simply need to enable HostAuthenticationFilter and add Authorize attributes on the Web API side and it's ready to go. You can get access to the claims principal object and use claims as identifying pieces of information for your user - e.g. identity, roles, other attributes etc.
To get started, look at http://www.asp.net/vnext/overview/authentication/individual-accounts-in-aspnet-web-api
Also as a wrap, I did consider the use of JSON Web Tokens (JWTs) as there is an OWIN library available for generating and parsing these. The use case here would be that you authenticate, get a JWT back, and then use the JWT to get an OAuth 2.0 bearer token. The JWT is useful if you want to move authentication elsewhere, or if you want to get additional information about the user at the MVC side of things.

Is it possible to expose multiple endpoints using the same WebAPI controller?

I want to create a WebAPI service for use in my single page application but I also want it to be available for a mobile application too.
When users are using the SPA they are signed in using forms authentication and have a session cookie but if they're using the mobile application this wont be the case.
Is it possible to expose the same API controller as 2 different endpoints where one is authenticated using mutual SSL, a token or as a last resort basic auth and the other uses the session cookie?
For example take the following controller:
public class TodoController :
{
public IQueryable<TodoModel> GetTodos()
{
...
}
}
Can I add multiple routes that map to the same method?
https://myapp.example.org/api/todo
https://myapp.example.org/mutual-auth/api/todo
I want to configure IIS to use mutual SSL for the mutual auth endpoint and use forms authentication for the other endpoint.
Short answer: yes
This is a very broad question, so I won't go into excessive detail about every aspect. I think you should also take a look at BreezeJS because it makes things building these applications significantly easier.
DESIGN
Do you want to build in pure HTML and JavaScript or incorporate CSHTML? The decision is yours, but if you want to eventually create native-based applications using something such as PhoneGap Build, you'll want to stick to pure HTML and JavaScript so that you can compile the code later.
Do you want to use another JS library such as BreezeJS to make life a little easier when designing your controllers? Out of the box, your Web API controllers will be prefixed with api/{controller}/{id} in WebApiConfig. You may want to add {action} routing if you don't go with something like BreezeJS so that you can have more flexibility with your controllers.
Lastly, let's talk about the Repository Pattern and Unit of Work Pattern. This is a bit of hot-topic, but I find that usually creating a repository allows you a great deal of flexibility and it's great for dependency injection. Adding an additional repository layer to your controllers allows you to differentiate between different users or means of access such as a SPA or mobile application very easily. You can use the exact same controllers, but simply draw from different repositories.
SECURITY
You'll want to touch up a bit on [Authorize], [ValidateHttpAntiForgeryTokenAttribute], [Roles("")], and several other data annotations for starters. This is a huge topic which has a ton of reading material online -- invest in some research. Your controller can have multiple actions which have varying limitations on them, such as preventing CSRF on the SPA, but be less restricted on Mobile by either utilizing varying actions on the controller or drawing from separate repositories.
Can I add multiple routes that map to the same method?
https://myapp.example.org/api/todo
https://myapp.example.org/mutual-auth/api/todo
Yes, absolutely. You'll just have to do some extra work with your routing configuration files. With BreezeJS, you get access to not only /api/ but /~breeze/ which works very similarly.
You can secury your Web API using the way you want. For exemple, you can provide a custom Message Handler or a custom Authorization Filter to provide external authentication via token.
There's a full session from the ASP.NET Team that covers this, you just need to choose which one you will pick up:
Security issues for Web API.
Assuming you are hosting web API in IIS, if you enable the forms authentication, FormsAuthenticationModule establishes the identity. That is, if you look at HttpContext.Current.User or Thread.CurrentPrincipal after a successful authentication, the object of type IPrincipal will have the identity (which is FormsIdentity) and the IsAuthenticated property will be set to true. You can do the same thing for any other credential using a custom DelegatingHandler. All you need to do is to validate the credential (token, user id and password in basic scheme in HTTP authorization header or whatever) and set the HttpContext.Current.User and Thread.CurrentPrincipal to an object of type GenericPrincipal with GenericIdentity. After this, the same action method of a controller which is decorated with Authorize will work for both types of requests.

Repeating logic in each ASP.NET Web API request, where should that go?

I need to store some information in session(or in whatever in ASP.NET Web API) that I need to retrieve in each API request. We will have one api IIS web site and multiple web site binding will be added through host header. When any request comes in for example, api.xyz.com, host header will be checked and store that website information in session that will be used in each subsequent api request when making a call to database. Hope this is clear.
I found a way to handle session in ASP.NET Web API. ASP.NET Web API session or something?.
I know lot more about asp.net web forms where we can override PreRequestHandler. I am looking for similar in ASP.NET Web API where I can have my logic to get database id for api domain(for example, api.xyz.com) and store it in session which I want to access in each API GET/POST request.
Somebody will definitely say by adding session I am making it stateful but REST is stateless. But I wanted to save database trip for each api request. If I don't use session or something similar, I end up repeating the same logic for each api request.
Is there a better way to handle this situation? how?
thanks.
If that logic needs to happen for all requests, you better use an Implementation of delegating handlers.

Resources