How to authenticate Jquery Ajax call made to api in MVC web API - asp.net-mvc

I have an Asp.net application hosted on one domain say abc.com and I have another MVC Web API hosted on a different domain say api.abc.com.
Now from the web application(abc.com), I am making a javascript ajax call to my web api endpoint(api.abc.com/getproducts) which is not the same domain. So what are the different mechanism i can use to authenticate the API calls made to api endpoint? The goal is to secure api so can avoid unauthenticated calls and also avoid unnecessarily complex structure.
Is it good practice to make web API call from javascript? via Ajax request.

This is a very broad question, here are some links from what I can gleam from your question. My suggestion for the future is to include code, and make the question more specific.
Security and Authentication in MVC applications: https://learn.microsoft.com/en-us/aspnet/mvc/overview/security/
CORS: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
.NET Core: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/?view=aspnetcore-3.1
Similar Question: Cross-domain authentication ASP.net MVC

Related

Separating Web Api and Web Site

i'm new to asp.net web api, owin, and everything related to it.
I'm trying to find the best way to do this scenario:
1 - Web api to have all the connections and rest service
2 - Web site to show data to user on a browser using the restful service
3 - An mobile app that have some functionalities like the web site and access the restful service to get all the information
My doubt is: what's the best practice related to the login? I'll use owin/oath2 with Identity to login, but since it's going to be implemented on the web api, the login/register/forgot password should be on the web api directly (like the project template does) or should i move most of the functionality to the web site? Of course its easier to leave in the web api, but if i do it, i must duplicate my razor templates just to call the login part. Can someone give me a path to follow?
Thanks!
the answer is not, your web api should not have any html or js or css file, only the services that your need, the web api exposes the functions to register the user, next when you have to do request, you must Send a token, you can obtain the token using the URL that you have configure in owin, the URL is like /token and Send the username and pass.
Regards,

How to share authentication between ASP.NET MVC and ASP.NET WEB API applications?

I am building an AngularJS MVC application, I need some guidance in terms of authentication. I am thinking of building the Authentication using the MVC authentication pipeline. AngularJS code will reside in the MVC application and the root SPA view would be a Razor cshtml. Here is my scenario -
Login page will call a Authenticate API that would return a token
AngularJS has the logic to get the bearer and pass to each of the API requests
There will be multiple ASP.NET WebAPI projects that will be hosted as subdomains.
I also need to call complex dynamic razor templates, this would need the authentication for the MVC controller that will return the razor views. Since MVC follows cookie based authentication, the token gives a 401 status code. How would this work wherein the authentication is shared between MVC and WEB API apps.
I think you would need to get your token from the API project, not the MVC in order to be able to securely call the API.
If you want to share identities across both the API and MVC projects, have them use the same database.
When getting the token from the API, you can get the identity details of the current user from your MVC application. At least, that is how I have done it in the past.
I blogged something along these lines here: http://blogs.msdn.com/b/martinkearn/archive/2015/03/25/securing-and-working-securely-with-web-api.aspx however this does not cover the step of using the creds from your MVC login and passing that to the API to get the token.
Hope that helps.

How does web API and MVC work together?

How does MVC and web API work together in an application?
Are you supposed to use javascript binding (with knockout.js and ajax calls) and just use MVC for the actual container page?
Or do you call web API from the MVC controller (like a WCF service layer)?
The integration of MVC and web API just isn't clear to me.
Should I use Web API if I regulary require HTML to be returned (i.e. I want to work with Partials)?
I'd like to use web API so I can scale my app though (return HTML from one side, but remain with an API that can return/process XML)!
Thanks for clearing it up :)
This picture below from the link explains clearly how MVC and Web Api work together:
Technically, you can call from MVC to Web API, but it is not really the best practice since:
Calling from MVC to Web API will across the network (distribution), this makes your application more complex.
Web Api is REST Api, it is not like WCF which is heavily SOAP Api (although WCF support REST Api). So, from JavaScript you can call the Web Api easier using ajax.
Here's how I set up my latest MVC and Web API application: There's the regular model layer (*M*VC) and I have created a service layer for the business rules. The controllers of my MVC application call the service layer to process data from and to the views.
My Web API application is a external interface to the methods on the service layer, therefore both the controllers on the MVC application and on the Web API application call the service layer. I hope this helps.

Difference between ASP.NET MVC 4 Web Api and REST classic services

I saw that ASP.Net MVC4 WebApi exposes services as a Rest ones.
But what is actually the difference between normal Rest and ASP.Net MVC4 WebApi?
I'm not sure what you mean by normal Rest.
REST is a paradigm.
HTTP is a protocol that follows that paradigm.
ASP.NET Web API allows developers to write ASP.NET applications that can be accessed via HTTP and adhere to the REST paradigm. While you could create a REST API without Web API, Web API provides a ton of features that will remove a lot of the pain associated with creating a truly RESTful API in ASP.NET.
apigee has many great resources for REST API best practicies.
Are you asking about the general REST standard or the way that REST has been done traditionally on the Microsoft platform prior to the MVC4 Web API? I am thinking you are approaching this as the second one.
The updated approach in MVC4 gives you more REST capabilities without the WCF model. Here is a recent post on the subject: http://mattmilner.com/Milner/Blog/post/2012/02/28/WebAPI-or-WCF.aspx.

Creating REST API for existing MVC based website

I have a website developed using ASP.NET MVC3.
I now want to expose a REST API for others to use which will expose the same features as the website.
In the website, once a user has logged in and credentials validated against a DB, the session manages the logged-in state of the user.
How would I do the equivalent with the REST API, where many of the methods exposed require the user to be logged in (or at least have valid username and password)?
In addition to this, would the best approach for the website be to use the REST API also (presuming the API covers all the functionality required by the site)?
How well is ASP.NET MVC3 suited for this - of course taking into account that the site already exists using this framework?
I wrote up a blog post on how to [Build a RESTful API architecture within an ASP.NET MVC 3 application] years ago and ended up having to let the site go. :( It might be a good start if you want to take on building the REST API into your MVC application.
See answer by #tugberk on using WebAPI for a good solution.
ASP.NET MVC is very well suited for this. Although you can use other approaches (like WCF) I would stick with MVC since you already have a working site that needs to be exposed for other consumers.
See also my other answer:
Which is better for building an API for my website: MVC or Ado.net data services?
Note:
WCF Web API is now ASP.NET Web API and has changed a lot. The beta
version is now available. For more information: Getting Started With
ASP.NET Web API - Tutorials, Videos, Samples
I would go with WCF Web Api to do that. ASP.NET MVC is also nice and capable of exposing your data but WCF Web Api is more capable if you consider exposing your data to your users. It is easy to use and integrate REST Web APIs to your system.
For the authentication, API Key is always the best way for this type of scenario. Here is a good example on how you can implement API Auth with WCF Web API :
http://weblogs.asp.net/cibrax/archive/2011/04/15/http-message-channels-in-wcf-web-apis-preview-4.aspx
Note:
They just released the preview version 5 couple of weeks ago and
Message Channels has been changed to Message Handlers as far as I
know. But the above article should give you an idea.
For security implementations, the below might help as well :
wcf Authentication Token Implementation - How to do
ASP .NET MVC is a great choice for this. I have created several ASP MVC that act as RESTful services as well as websites.
To summarize the design paradigm I use, each controller has an action that emits a JSON representation of the requested data. Said data is loaded in a view model on the server, and the built in JSON serializer takes care of the server side, while a jQuery view nicely loads the data back in for my actual webpages to consume.
The site itself has index actions on each controller that emit that necessary markup, but not the data. jQuery document.ready methods on the pages load in the data from what is essentially my rest api, but build right into the site.
Checkout Nerd Dinner for great sample code. http://nerddinner.com/
Concerning security, I think my experience will differ from yours. ASP MVC integrates very nicely with active directory if your users are all in the same domain and have AD credentials. This is the only method I have used, and with ease, success, and satisfaction.
I have had coworkers interact with other APIs that hand out a token upon calling an authorize method. The received token would then be the clients responsibility to store and hand back on each request, but I cannot talk you through implementation details, as I have not person experience on that front.
I would go with a WCF web service based implementation as follows.
Wrap all your business logic into a separate dll project named as yourproject.businessservices for example
Create a authentication webservice which will generate a non-repeatable token per user login
This login stores the essential details of the user along with the token in a Cache like MemCache which should have a sliding expiration
If the user has not accessed the cache for let's say an hour, the cache expires and the user is logged out
If the user is using it the cache keeps getting extended.
On the wcf services side,
Create APIs to return the token on authentication
All the wcf methods will have this session id which needs to be validated
The advantage is that the wcf methods can be exposed to return xml or json format and can also be used as normal web services.
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/MyModule/XML/GetData/{customerSessionId}")]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/MyModule/JSON/GetData/{customerSessionId}")]

Resources