ASP。NET Core标识:支持JWT令牌进行用户身份验证

介绍 这是关于ASP系列文章的第三篇文章。网络核心身份: ASP。NET Core标识:启动asp.net CoreNET Core标识:建立一个web项目和标识数据库NET Core标识:用户注册,登录和注销功能使用ASP。asp.net Core mvc asp.net。angular 4:使用JWT令牌进行用户身份验证angular 4:使用外部提供者进行用户身份验证 在前面的步骤中,我们创建了一个ASP。具有登录/注销功能的asp.net Core MVC网站。网络核心的身份。我们构建的MVC网站使用了基于cookie的身份验证,这在这个场景中工作得很好。但是对于许多其他场景(比如使用移动应用程序的安全API),基于cookie的方法不是一个好的选择。对于这些场景,一种流行的方法是基于令牌的身份验证。在这一步中,我们将向项目中添加用于身份验证的jwt令牌生成功能。 我不打算详细解释什么是JWT令牌,以及它与基于cookie的方法有何不同,因为有很多关于这个主题的好文章。如果你感兴趣,你可以看看这些文章: https://auth0.com/blog/angularjs——验证——饼干- vs token/ https://auth0.com/blog/ten - -你应该知道- -令牌和cookies/ https://medium.com/vandium software/5 -简单的步骤- -理解- json - web标记智威汤逊- 1164 c0adfcec 本文的完整代码可在此回购https://github.com/ra1han/aspnet- coreidentity中的Demo 3文件夹中获得。 在启动时准备服务 要启用JWT令牌生成,我们必须为标识中间件配置服务。但是如果我们查看Startup类中ConfigureServices方法的当前实现,就会发现没有对cookie的配置。 那么基于cookie的认证是如何工作的呢?这是有效的,因为如果我们不手动配置它,默认行为是基于Cookie的认证。 我们将使用服务。在ConfigureServices方法中添加身份验证以添加其他身份验证方案。 隐藏,收缩,复制Code

public void ConfigureServices(IServiceCollection services)
{
	services.AddDbContext<applicationdbcontext>(options =>
					options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

	services.AddIdentity<applicationuser, identityrole="">()
											.AddEntityFrameworkStores<applicationdbcontext>()
											.AddDefaultTokenProviders();

	services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
			.AddCookie()
			.AddJwtBearer(jwtBearerOptions =>
			{
				jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
				{
					ValidateActor = false,
					ValidateAudience = false,
					ValidateLifetime = true,
					ValidateIssuerSigningKey = true,
					ValidIssuer = Configuration["Token:Issuer"],
					ValidAudience = Configuration["Token:Audience"],
					IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes
                                                       (Configuration["Token:Key"]))
				};
			});

	services.AddMvc();
}

准备控制器 现在,我们将添加两个新的web API控制器: TokenController—匿名访问,用户使用它来检索JWT令牌greetingcontroller—安全且只能使用JWT令牌身份验证方案访问 TokenController中的令牌生成代码: 隐藏,收缩,复制Code

[HttpPost]
public async Task<iactionresult> Get(LoginViewModel model)
{
	if (ModelState.IsValid)
	{
		var user = await _userManager.FindByEmailAsync(model.Email);
		if (user != null)
		{

			var result = await _signInManager.CheckPasswordSignInAsync
                            (user, model.Password, lockoutOnFailure: false);

			if (!result.Succeeded)
			{
				return Unauthorized();
			}

			var claims = new[]
			{
				new Claim(JwtRegisteredClaimNames.Sub, model.Email),
				new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
			};

			var token = new JwtSecurityToken
			(
				issuer: _configuration["Token:Issuer"],
				audience: _configuration["Token:Audience"],
				claims: claims,
				expires: DateTime.UtcNow.AddDays(60),
				notBefore: DateTime.UtcNow,
				signingCredentials: new SigningCredentials(new SymmetricSecurityKey
                            (Encoding.UTF8.GetBytes(_configuration["Token:Key"])),
						SecurityAlgorithms.HmacSha256)
			);

			return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
		}
	}

	return BadRequest();
}

使用API 现在来测试我们的实现,我们将使用邮差。 首先,我们将尝试从postman访问Greeting API (http://localhost:36946/api/ Greeting)。我们将看到我们得到未经授权的错误。 现在,让我们从令牌API (http://localhost:36946/api/token)创建一个令牌。我们将提供用户名和密码,API将返回承载令牌。 现在让我们用承载令牌再次调用Greeting API。 它工作!在下一篇文章中,我们将创建一个Angular 4项目,其中包含在这一步中开发的用户身份验证功能。 本文转载于:http://www.diyabc.com/frontweb/news17310.html

原文地址:https://www.cnblogs.com/Dincat/p/13494021.html