I'm using ASP.Net Core 2.0, I want to build a Web API project with Individual User Accounts Authorization type, but the only option is Connect to an existing user store in the cloud
.
How can I add a template for Web API with Individual User Accounts with Store user accounts in-app
?
This option is available for Web Application but not for Web API.
Try start your project in the console with the command
dotnet new webapi -au Individual
You can open your project in VS after that. (to work around the dialog). Then you can use for example the authorize-attribute.
But the project is still configured to use Azure Bearer Authentication.
You have to decide where to get identity from.
You can take identityserver4 or build your own "Custom storage providers for ASP.NET Core Identity" (MS-Docs)
The difference to MVC WebApp: here you have an account controller with views to handle registrations and get a username and password and so forth.
I was puzzled by the same thing, and ended up selecting Web Application
instead of Web API
. There is probably logic in MS removing "in-app accounts" - With Web API you are probably writing SPA, and "views" (Login, Forgot Password, etc.) should be in your client code; not Razor views on the server.
Note, that if you go with IdentityServer 4, the views are generated in the IS4 application; not in Business API application.
So I think Microsoft is trying to give you a hint here...
To get the answer, I built both the API version without authentication and the version with, then did a diff on the generated folders (and ignored the one extra code block in appsettings.json which appears when you use the cloud-auth option).
Turns out that enabling authentication requires only a few lines of code.
If you make the following changes to a No-Authentication version of the API template, you will have an Authentication version:
In Startup.cs, add: using Microsoft.AspNetCore.Authentication;
in the "using" section. Also add: app.UseAuthentication();
right before app.UseMvc();
as shown below:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
In Controllers\ValuesController.cs, add: using Microsoft.AspNetCore.Authorization;
in the "using" section. Also add: [Authorize]
immediately above [Route("api/[controller]")]
That's all you need to add templated authentication to the vanilla API template. Of course you'll need to add the actual authentication code, but at a template level, you're done.
(Side note: there was also an optional assumption made by Microsoft in the Auth version that you'll use UserSecretsId, so if you want that too, simply right-click on the solution and select Manage User Secrets.)