如何在令牌生成时强制执行用户名和密码,或者这是不好的做法

How do I enforce username and password on token generation or is it bad practice

我已经启动了一个简单的网络 api 并使用 jwt 添加了令牌生成。但是我在用户存储的应用程序帐户中使用这是我设置令牌的功能。它以大摇大摆的方式出现,但我不明白的是如何在发出令牌请求时强制输入用户名和密码。或者这是不好的做法。

这是我生成安全令牌时的class。

public JwtService(IConfiguration config)
{
        var test = config;
          _secret = config.GetSection("JwtToken").GetSection("SecretKey").Value;

        _expDate = config.GetSection("JwtToken").GetSection("expirationInMinutes").Value;
}

    public string GenerateSecurityToken(string email)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_secret);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[]
            {
            new Claim(ClaimTypes.Email, email)
        })
        ,
            Expires = DateTime.UtcNow.AddMinutes(double.Parse(_expDate)),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);

        return tokenHandler.WriteToken(token);

    }
}

 public static IServiceCollection AddTokenAuthentication(this IServiceCollection services, IConfiguration config)
    {
         var secret = config.GetSection("JwtToken").GetSection("SecretKey").Value;
        var keySecret = Base64UrlEncoder.DecodeBytes(secret);

        var key = Encoding.ASCII.GetBytes(keySecret.ToString());
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false,
                // ValidIssuer = "localhost",
                //ValidAudience = "localhost"
            };
        });

        return services;
     }

Swagger 生成代码

  services.AddSwaggerGen(c =>
  {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "App Manager - Running Buddies", Version = "v1" });

            c.AddSecurityDefinition("bearer", new OpenApiSecurityScheme
            {
                Name = "Authorization",
                Type = SecuritySchemeType.ApiKey,
                Scheme = "bearer",
                BearerFormat = "JWT",
                In = ParameterLocation.Header,
                Description = "JWT Authorization header using the Bearer scheme.",
            });
    });

招摇Ui测试

您可能希望在使用 HTTP POST 的模型中传递 username/password。 请确保仅在登录请求有效时才发出令牌,即在您成功验证用户身份后。 请参阅 使用 JWT 保护 ASP.NET 核心 2.0 应用程序 了解更多详情。

编辑:要使用身份执行登录,您可以使用 SignInManager.PasswordSignInAsync or to just check the credentials SignInManager.CheckPasswordSignInAsync. See the samples 作为示例:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    // generate the token
}