I have started a simple web api and added token generation to it using jwt. However I used in app accounts for the user store this is my function for setting up the token. Its showing up in swagger fine but what I dont get is how to I enforce the username and password to be entered when the request for token is made. Or is that bad practise.
This is my class when I generate the security token.
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 Gen Code
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.",
});
});
Swagger Ui Test
You might want to pass username/password in a model using HTTP POST . Be sure to only issue a token when the login request is valid, ie after you have successfully authenticated the user. See Securing ASP.NET Core 2.0 Applications with JWTs for further details.
Edit: To perform a login using Identity you could use SignInManager.PasswordSignInAsync or to just check the credentials SignInManager.CheckPasswordSignInAsync . See the samples for an example:
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
// generate the token
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.