How to set up JWT-based authentication in ASP.NET Core

5/8/2023
Back to List

ASP.NET Core provides several options for authentication, including cookie-based authentication, token-based authentication (using JWT), and external authentication providers such as Google, Facebook, and Twitter. Here's a brief overview of how to set up JWT-based authentication in ASP.NET Core:


  1. Add authentication middleware to the application's Startup.cs file. This middleware can be added by calling the AddAuthentication() method and specifying the authentication scheme you want to use (in this case, JWT-based authentication).

    public void ConfigureServices(IServiceCollection services)
    {
    // Add authentication services
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
    options.TokenValidationParameters = new TokenValidationParameters
    {
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateLifetime = true,
    ValidateIssuerSigningKey = true,
    ValidIssuer = Configuration["Jwt:Issuer"],
    ValidAudience = Configuration["Jwt:Audience"],
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
    };
    });
    }
  2. Configure the authentication middleware to use the JWT-based authentication scheme. This is done in the Configure() method of Startup.cs.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    // Add authentication middleware
    app.UseAuthentication();
    }
  3. Protect the desired routes or controllers with the [Authorize] attribute. This attribute can be placed at the controller or action level to restrict access to authorized users only.

    [Authorize]
    public class HomeController : Controller
    {
    public IActionResult Index()
    {
    return View();
    }
    }
  4. Create a JWT token when the user successfully authenticates. This token will contain the user's claims, which can be used to authorize subsequent requests.

    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
    // Validate user credentials
    var user = await _userManager.FindByEmailAsync(model.Email);
    if (user == null || !await _userManager.CheckPasswordAsync(user, model.Password))
    {
    return Unauthorized();
    }

    // Create token
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(Configuration["Jwt:Key"]);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
    Subject = new ClaimsIdentity(new Claim[]
    {
    new Claim(ClaimTypes.NameIdentifier, user.Id),
    new Claim(ClaimTypes.Email, user.Email)
    }),
    Expires = DateTime.UtcNow.AddDays(7),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);

    return Ok(new { token = tokenString });
    }
  5. Add the JWT token to the Authorization header of subsequent requests. This can be done using a bearer token, like so:

    Authorization: Bearer <Token>

SuperChad
Gravatar About Sean Nelson
I like codes and stuff.

4 comments
Gravatar Fafcryday - 11/20/2024 5:48:10 PM
2 were outborn <a href=https://fastpriligy.top/>what is priligy</a> Swanson, SM, et al
Gravatar furosemide spironolactone cirrhosis - 1/17/2025 11:51:56 PM
Ôèáðèíîëèçèéã äàðàíãóéëàõ ýì Øèìýã èéí ýñðýã, äàðõëàë ñýðãýýõ áýëäìýë <a href=https://lasix2buy.top/>lasix usa blog</a>
Gravatar why do athletes Take Steroids - 6/5/2025 7:07:51 AM
It’s necessary to weigh these components and consult with a medical skilled before making a decision. With consistent exercise, proper vitamin, and the right mindset, it is attainable to achieve pure muscle development with out relying on steroids. Winstrol will suppress testosterone ranges, decreasing sperm amount and high quality. Users who administer common cycles of toxic anabolic steroids such as Winstrol with insufficient time off in between cycles are at larger risk of testosterone deficiency or infertility. We have found incidents of zits vulgaris to be more prevalent on trenbolone because of extreme stimulation of the sebaceous glands. Additionally, we observe the next incidence of hair follicle loss on trenbolone in comparability with different anabolic steroids. Therefore, it’s important to allow an "off-cycle" period much like the "on-cycle" one. For instance, if your steroid cycle lasts for 4 weeks, then make positive that you’re off the steroid for a similar period, if not more. This is a nice way to let the hormone ranges stabilize on their own. An unusually giant or bloated stomach in bodybuilders isn’t usually a sign of anabolic steroid consumption. It’s sometimes brought on by the overuse of insulin or the HGH (human growth hormone) and is usually called the "HGH gut." Nonetheless, bodybuilders who use these chemicals are likely to use other steroids. The formation of male breast tissues, or "man boobs," as they're commonly known, is brought on as a end result of gynecomastia. As a aggressive powerlifter, Doug ate a high-protein food plan and trained exhausting within the gym everyday. In 2016, Greg tipped the dimensions at 670 pounds and was advised that he needed to "get busy dying, or get busy residing." By 2020, he misplaced 260 pounds. But as his weight loss slowed down, he needed to push previous a plateau to meet his fitness targets. After starting TRT, Scott dropped 60 pounds, vanquished his fatigue, and is reinvigorated at work. Ten years later, he weighed 285 kilos and relied on two energy drinks simply to start his day. He’s in the gym five days per week and performs the drums with as a lot intensity as when he was 31. With higher red blood cell counts, there could be an improved oxygen-carrying capability within the bloodstream. This enhanced oxygenation promotes endurance and stamina, enabling individuals to coach tougher and longer. Additionally, Trenbolone additionally enhances nutrient effectivity by increasing the body’s capacity to extract and make the most of nutrients from the diet, optimizing the fuel available for muscle progress and efficiency. For some folks, it might take a quantity of steroid injections to feel outcomes. Below are the solutions to some regularly requested questions about epidural steroid injections. A 2019 study comparing epidurals with IV anesthesia showed comparable outcomes on again ache. Additionally, some individuals may use steroids for medical reasons, corresponding to to deal with muscle wasting ailments or hormonal imbalances. Testosterone can also negatively have an effect on high-density lipoprotein (HDL) and low-density lipoprotein (LDL) ldl cholesterol ratios, probably inflicting hypertension (2). Nevertheless, we observe such elevations in blood strain to be delicate in comparability to more extreme anabolic steroids. Despite this, we now have observed lowered anabolism in customers who take away Deca Durabolin from stacks. To put trenbolone’s androgenicity into perspective, its androgen ranking is 500, which is 5 times greater than that of testosterone. Trenbolone will also suppress endogenous testosterone ranges, resulting in male hypogonadism. Dianabol has the capability to add 25–30 kilos of lean mass from a cycle. We have discovered Anavar’s hepatic effects to be much less poisonous in comparison with other oral steroids. Some of our patients have found testosterone suspension injections to be painful. This may be attributed to testosterone suspension requiring a a lot bigger needle due to it containing larger, non-micronized crystals. Usually, we see beginners experiencing as much as a 20% increase in lifts from an Anavar cycle. Thus, if users are at present benching 200 pounds, they could possibly be lifting 240 after 6 weeks. We discover this to be attributed to its distribution of fluid and increased uptake of adenosine triphosphate (ATP) within the muscle cells. ATP is an vitality molecule that has been shown to increase muscular power and endurance. Thus, gymgoers could really feel stronger during workouts and be capable of train extra intensely, lifting heavier weights for longer periods. Testosterone is essentially the most well-known and generally used steroid for this function, however there are additionally different types similar to Dianabol, Deca-Durabolin, and Trenbolone. These steroids have varying results on muscle achieve, with some being more effective than others relying on the person and their objectives. 10 weeks later, the guys who had been taking testosterone had ranges that have been 3-6 instances greater than normal, but(!), you in all probability anticipated that. Hone is an online clinic that helps men and women handle their well being. As part of your subscription and as medically indicated, physicians prescribe medicines, and recommend dietary supplements which are delivered to you from the consolation of your house. Different factors which are exterior we will have under personal management in a lot of the instances. Hormones are big communal and health hazard which can create points on the lengthy term. In the regular and natural water cycle, these metabolites will get into the drinking water. Over the time with day by day uptake of tap water, male population is uncovered to feminine sexual hormones, which have negative affect on male development in puberty and spermatogenesis in reproductive ages. In any case, use of anabolic steroids has direct and unfavorable affect on spermatogenesis which was confirmed very lengthy time ago. Now, think about the influence on somebody endeavoring to grow muscle mass! Diving into details, one would possibly ask, "How does the substance in question function within the human body? " Worry not; we’re right here to interrupt down the process into easy phrases for a better grasp. As with many anabolic steroids, it starts by interacting with the body’s cell receptors. The scale makes use of a 5-point Likert scale, where 1 denotes ‘very important’ and 5 ‘not important at all’, with values assigned as 1.zero, 0.eight, 0.6, 0.four and 0.2. The whole rating of the 5 objects indicates the self-management angle score of the patient. The scale has been tested with a correlation coefficient of 0.20 and a Cronbach’s alpha (α) worth of zero.seventy eight, demonstrating glorious reliability and validity [19].
Gravatar 0ahukewixpkubzmjnahxdgs0Khugka8kq4dudcao|side effects definition - 6/13/2025 5:17:35 AM
70918248