My .NET Core version is:3.1
,I want to authenticate my Users by Identity
,Here is the Startup.cs
code:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Wulikunkun.Web.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Identity;
namespace Wulikunkun.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
// Make the session cookie essential
options.Cookie.IsEssential = true;
});
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddHttpContextAccessor();
services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(Environment.GetEnvironmentVariable("MySqlConnection")));
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Home/Index";
options.LogoutPath = "/Home/Index";
options.AccessDeniedPath = "/Home/Index";
});
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "wulikunkun's api", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
And here is a part of my LogIn
action code:
var result = _signManager.PasswordSignInAsync(user.UserName, user.Password, true, true);
if (result.IsCompletedSuccessfully)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,corrUser.UserName),
new Claim(ClaimTypes.Email,corrUser.Email)
};
await _userManager.AddClaimsAsync(corrUser, claims);
}
return Json(new
{
StatusCode = 1
});
But I found the Http.Uesr.Identity.IsAuthenticated
is false when the result.IsCompletedSuccessfully
returns true
and this is my csproj
file content:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.8">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.4" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.21" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Ninject" Version="3.3.4" />
<PackageReference Include="StackExchange.Redis" Version="2.1.58" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.7" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.1.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
<PackageReference Include="NLog" Version="4.6.7" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Wulikunkun.Utility\Utility.csproj" />
</ItemGroup>
<ProjectExtensions>
<VisualStudio>
<UserProperties appsettings_1json__JsonSchema="" />
</VisualStudio>
</ProjectExtensions>
</Project>
AddAuthentication
need to be injected in ConfigureServices
. Otherwise it will not trigger the authentication service.
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddAuthentication();
//...
}
Result.
This is my action of registration.
[HttpPost]
public async Task<IActionResult> Register(string username, string password)
{
var user = new IdentityUser
{
UserName = username,
Email = "",
};
var result = await _userManager.CreateAsync(user, password);
if (result.Succeeded)
{
var res = _signInManager.PasswordSignInAsync(username, password, true, true);
return Json(new
{
StatusCode = 2
}); // Carry cookie to browser.
}
return View("Index");
}