5

I know that this question could receive some downvotes, but I'm searching on Google for three days, with no really usable results.

I've created a default ASP.NET Core 1.0 RC1 project in Visual Studio, with Individual User Account authentication/authorization. Everything is easy and simple this way, because the project is scaffolded using Microsoft.AspNet.Authentication.Cookies, and VS 2015 does all the heavy lifting.

However, we want to expose an API from the same project (using the same database, users, claims and so on), that will be consumed from mobile devices and even some simple SPA's. This way, we need to use something like JWT for the API (There are a bunch of tutorials on how to do this with WebAPI only).

We want to do the main project using MVC (not SPA) way to leverage the use of view/controller scaffolding and everything Visual Studio can offer.

There is a lot of of tutorials of MVC-only or WebAPI-only approaches, but could you point me on how could I mix them together?

Is there a way of using JWT only with MVC and WebAPI system-wide?

Thank you in advance.

cezarlamann
  • 1,465
  • 2
  • 28
  • 43
  • Just FYI: MVC and WebAPI have been merged in MVC 6. `Controller` serves as base class for both 'MVC' and 'API' controllers, e.g. there is no `ApiController` anymore. – Henk Mollema Apr 14 '16 at 21:54
  • Hi @HenkMollema I know... For this reason I've put "ApiController" between quotes. I know that the controllers are the same. Anyway, thank you for the comment. – cezarlamann Apr 14 '16 at 22:47
  • Hi @Cezar. Did you ever figure this out? I have the exact same scenario and question. Thanks – Adrian Carr Jun 07 '16 at 16:21

1 Answers1

1

Limiting identity by scheme this link may be answer of your question.

In some scenarios, such as Single Page Applications it is possible to end up with multiple authentication methods, cookie authentication to log in and bearer authentication for javascript request.

I think, you can use below code for mvc and javascript calls(of course, you must enable cookie and bearer middlewares):

[Authorize(AuthenticationSchemes = "Cookie,Bearer")]
public class YourController : Controller
adem caglin
  • 22,700
  • 10
  • 58
  • 78
  • Thank you for answering! I'm affraid that this do not work in ASP.NET Core 1, because there is only an `ActiveAuthenticationSchemes` attribute, and it's out of the constructor. Now, the only thing it accepts as a parameter is a string containing the policy name: `public AuthorizeAttribute(string policy);`. Could you point me on how should I create a "WebAPI-Only" policy? – cezarlamann Apr 15 '16 at 12:35
  • i couldn't test the code, but may be a solution: `options.AddPolicy("PolicyName", policy => { policy.Requirements.Add(new Infrastructure.MinimumAgeRequirement(21)); policy.AddAuthenticationSchemes("Bearer"); });` – adem caglin Apr 15 '16 at 13:36