Authentication for ASP.Net MVC 4 and WebApi - asp.net-mvc

I would like to set up a system that use both technologies at the same time. My MVC application generates and returns html/css/jaavascript files and then I do some work on the client side that get data through ajax request. Nothing new so far, but I would like also that the ajax endpoing could also be use as a pure REST service .
How can I have a uniform way to authentificate (web forms for MVC clients(that will then use the REST enpoints for the ajax requests) , something else for pure REST clients ).
Thanks

You could use the [Authorize] attribute (the System.Web.Http.AuthorizeAttribute one and not System.Web.Mvc.AuthorizeAttribute) on your Web API controller actions:
public class ValuesController: ApiController
{
[Authorize]
public HttpResponseMessage Get()
{
string username = User.Identity.Name;
...
}
}

Related

how to map this route from mvc controller to a web api controller?

We have a mvc project and we would like to move to a web api. The mvc project doesn't have any UI,so it was a mistake to use mvc controller other than a web api controller.
However, our customers access the mvc controller via url such as:
https://mysite.azurewebsites.net/indexes/unit/docs/search (both httppost)
https://mysite.azurewebsites.net/indexes/unit/docs/post (both httppost)
https://mysite.azurewebsites.net/indexes/unit/docs/get
the part unit/docs is actually dynamic (something we send to a database to do some query).
If we move this controller to web api, how can we handle the route as we need to be backward compatible?
in your WebApi controller, do the following:
[route("{controller}")]
public IndexesController : ControllerBase
{
[HttpPost("{unit}/{docs}/{search}")]//or whatever those variables should be
public async Task<IactionResult> Search(string unit, string docs, string search)
{
//Do your stuff
var result = _logic.DoStuff();
return Ok(result);
}
}
There's no reason to move away from MVC controller though. Just always return a JsonResult() and it'll behave exactly like a WebApi from the caller's perspective.

best way to consume Web API MVC by Website and Mobile device both

I am developing project in MVC with normal controller and Web API 2 controller.
I am using MVC 4 with Razor, Normal Controller for Website, WebAPI controller that will work as REST service for Iphone device or android device.i want to use normal MVC normal controller to take advantages of data annotations(required, regularexpression etc in Model) thats why i am using both API controller and Normal controller.
I am writing my all DB related operation ( Fetch, insert, update, delete) in WebAPI. so that same method can be used by Website request and Mobile device request.
To access the method of WebAPI , i am creating the object like this.
just like this.
WEBAPI Method
public class AccountAPIController : ApiController
{
[AcceptVerbs("Get", "Post"), ActionName("GetSingle")]
public UserProfile GetSingle(string email)
{
// return userpofile;
}
}
NORMAL MVC Controller
public class AccountController : Controller
{
[HttpPost]
public ActionResult Getsingle(string email)
{
AccountAPIController API = new AccountAPIController();
var data= API.GetSingle(email);
return View(data);
}
is this right way to consume WebAPI? please suggest the best way to consume web api both by website and Iphone or android device.

Adding authorization header with access token for every request using MvcHandler

I'm trying to implement OAuth 2.0 resource access for the resource server. I have acquired a token and want to pass that token to the resource server so that resource server could validate with the authorization server for every request, passing the token in the http header
(e.g. Authorization: Bearer mF_9.B5f-4.1JqM).
I'm using MVC 4, and I've been told MvcHandler should be used to achieve this However I'm not sure where to start. Can anyone point me to a general direction on what should be done? I already have bunch of actions and controllers and want to put this layer on top of those instead of going back to every action and changing and/or decorating each action.
Use Authentication filters
Authentication filters are a new kind of filter in ASP.NET MVC that
run prior to authorization filters in the ASP.NET MVC pipeline and
allow you to specify authentication logic per-action, per-controller,
or globally for all controllers. Authentication filters process
credentials in the request and provide a corresponding principal.
Authentication filters can also add authentication challenges in
response to unauthorized requests.
You just need to implement the IAuthenticationFilter for your needs register it and it's done.
public class YourAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
if (user.Identity.IsAuthenticated == false)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
If you want it to be global add it as a global filter in FilterConfig.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new YourAuthenticationAttribute());
}
More info:
ASP.NET MVC 5 Authentication Filters
ASP.NET MVC 5 Authentication Filters
AUTHENTICATION FILTERS IN ASP.NET MVC 5
FINALLY THE NEW ASP.NET MVC 5 AUTHENTICATION FILTERS!

Using Web Api in a MVC Controller

Is it possible to use/call my Web API methods inside a MVC controller?
I have a Web Api to use in mobile and others plattaforms and I´m developing a .NET Mvc Website.
Does that architecture makes sense?
Thanks
Yes it's possible although if you're expecting to consume your API from a number of different clients I would suggest you create your API as a separate application that can then be managed/scaled accordingly.
Essentially you are referring to "dog-fooding" your own API, making your own web application no different to any other client.
We do something similar and have our MVC application call our API (using HttpClient). We also have a lot of client side code within the same application that calls the API directly using CORS.
We've had this architecture running in production for 2 years now without any issue.
Here is How I call my Web API controller from MVC controller:
public class invoiceController : ApiController
{
private myEntities db = new db1Entities();
// GET api/invoices
public IQueryable<invoices> Getinvoices()
{
return db.invoices;
}
}
inside separate MVC controller:
public ActionResult ShowInvoices()
{
var webApi = new invoicesController();
//this must return strongly typed object
var myarray = webApi.Getinvoices();
return View(myarray);
}

Difference between ApiController and Controller in ASP.NET MVC

I've been playing around with ASP.NET MVC 4 beta and I see two types of controllers now: ApiController and Controller.
I'm little confused at what situations I can choose a particular controller.
For ex: If I want to return a view then I've to use ApiController or the ordinary Controller? I'm aware that the WCF Web API is now integrated with MVC.
Since now we can use both controllers can somebody please point at which situations to go for the corresponding controller.
Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.
here is the link
Quote:
Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.
ApiControllers are specialized in returning data. For example, they take care of transparently serializing the data into the format requested by the client. Also, they follow a different routing scheme by default (as in: mapping URLs to actions), providing a REST-ful API by convention.
You could probably do anything using a Controller instead of an ApiController with the some(?) manual coding. In the end, both controllers build upon the ASP.NET foundation. But having a REST-ful API is such a common requirement today that WebAPI was created to simplify the implementation of a such an API.
It's fairly simple to decide between the two: if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning json here and there - stick with MVC/Controller. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page.
To give a real world example: I'm currently working with an ERP system that provides a REST-ful API to its entities. For this API, WebAPI would be a good candidate. At the same time, the ERP system provides a highly AJAX-ified web application that you can use to create queries for the REST-ful API. The web application itself could be implemented as an MVC application, making use of the WebAPI to fetch meta-data etc.
Which would you rather write and maintain?
ASP.NET MVC
public class TweetsController : Controller {
// GET: /Tweets/
[HttpGet]
public ActionResult Index() {
return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
}
}
ASP.NET Web API
public class TweetsController : ApiController {
// GET: /Api/Tweets/
public List<Tweet> Get() {
return Twitter.GetTweets();
}
}
I love the fact that ASP.NET Core's MVC6 merged the two patterns into one because I often need to support both worlds. While it's true that you can tweak any standard MVC Controller (and/or develop your own ActionResult classes) to act & behave just like an ApiController, it can be very hard to maintain and to test: on top of that, having Controllers methods returning ActionResult mixed with others returning raw/serialized/IHttpActionResult data can be very confusing from a developer perspective, expecially if you're not working alone and need to bring other developers to speed with that hybrid approach.
The best technique I've come so far to minimize that issue in ASP.NET non-Core web applications is to import (and properly configure) the Web API package into the MVC-based Web Application, so I can have the best of both worlds: Controllers for Views, ApiControllers for data.
In order to do that, you need to do the following:
Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
Add one or more ApiControllers to your /Controllers/ folder.
Add the following WebApiConfig.cs file to your /App_Config/ folder:
using System.Web.Http;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Finally, you'll need to register the above class to your Startup class (either Startup.cs or Global.asax.cs, depending if you're using OWIN Startup template or not).
Startup.cs
public void Configuration(IAppBuilder app)
{
// Register Web API routing support before anything else
GlobalConfiguration.Configure(WebApiConfig.Register);
// The rest of your file goes there
// ...
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ConfigureAuth(app);
// ...
}
Global.asax.cs
protected void Application_Start()
{
// Register Web API routing support before anything else
GlobalConfiguration.Configure(WebApiConfig.Register);
// The rest of your file goes there
// ...
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// ...
}
This approach - together with its pros and cons - is further explained in this post I wrote on my blog.
Quick n Short Answer
If you want to return a view, you should be in "Controller".
Normal Controller - ASP.NET MVC: you deal with normal "Controller" if you are in ASP.net Web Application. You can create Controller-Actions and you can return Views().
ApiController Controller: you create ApiControllers when you are developing ASP.net REST APIs. you can't return Views (though you can return Json/Data for HTML as string). These apis are considered as backend and their functions are called to return data not the view
More Details here
Every method in Web API will return data (JSON) without serialization.
However, in order to return JSON Data in MVC controllers, we will set the returned Action Result type to JsonResult and call the Json method on our object to ensure it is packaged in JSON.
The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client. The same because it is MVC platform.
If you create a new web application in latest framework 4.7.2 you will both of them to be configured by default and can build you application on that
In Asp.net Core 3+ Vesrion
Controller: If wants to return anything related to IActionResult & Data also, go for Controllercontroller
ApiController: Used as attribute/notation in API controller. That inherits ControllerBase Class
ControllerBase: If wants to return data only go for ControllerBase class

Resources