<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>authenticate asp net core &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/authenticate-asp-net-core/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Wed, 07 Sep 2022 04:46:40 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>authenticate asp net core &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Authenticate and Authorize JWT Token in ASP.NET Core 6</title>
		<link>https://topreviewhostingasp.net/how-to-authenticate-and-authorize-jwt-token-in-asp-net-core-6/</link>
					<comments>https://topreviewhostingasp.net/how-to-authenticate-and-authorize-jwt-token-in-asp-net-core-6/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Wed, 07 Sep 2022 04:40:34 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<category><![CDATA[authenticate asp net core]]></category>
		<category><![CDATA[authorize asp net core]]></category>
		<category><![CDATA[jwt token asp net core]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3159</guid>

					<description><![CDATA[In this article, I will explain how to create the JWT token and how to Authenticate and Authorize it in very simple steps. 1. Add ASP.Net Core API Application Open visual studio 2022 click on create new project &#8211;&#62; Select ASP.Net Core Web API &#8211;&#62; Next Give desired project and solution name &#8211;&#62; Next &#8211;&#62; select framework [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this article, I will explain how to create the JWT token and how to Authenticate and Authorize it in very simple steps.</p>



<h2 class="wp-block-heading">1. Add ASP.Net Core API Application</h2>



<p>Open visual studio 2022 click on create new project &#8211;&gt; Select ASP.Net Core Web API &#8211;&gt; Next</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="1024" height="682" class="wp-image-3160 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/09/visualstudio-1024x682.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/09/visualstudio-1024x682.jpg 1024w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/visualstudio-300x200.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/visualstudio-768x512.jpg 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/visualstudio-50x33.jpg 50w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/visualstudio-750x500.jpg 750w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/visualstudio.jpg 1190w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>



<p>Give desired project and solution name &#8211;&gt; Next &#8211;&gt; select framework .Net 6.0 &#8211;&gt; Create</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="654" class="wp-image-3161 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/09/aspnetcore-1024x654.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/09/aspnetcore-1024x654.png 1024w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/aspnetcore-300x192.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/aspnetcore-768x490.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/aspnetcore-50x32.png 50w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/aspnetcore.png 1190w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">2. Add Nuget Packages </h2>



<p>Add the following packages from nuget package manager.</p>



<ul>
<li>Microsoft.AspNetCore.Authentication.JwtBearer</li>
<li>Microsoft.IdentityModel.Tokens</li>
<li>System.IdentityModel.Tokens.Jwt</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" width="624" height="188" class="wp-image-3162 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/09/nugetpackage.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/09/nugetpackage.png 624w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/nugetpackage-300x90.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/nugetpackage-50x15.png 50w" sizes="(max-width: 624px) 100vw, 624px" /></figure>



<h2 class="wp-block-heading">3. Add setting in appsetting.json</h2>



<p>Open appsetting.json and add following Key, Issuer and Audience</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="503" height="157" class="wp-image-3163 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/09/appjson.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/09/appjson.png 503w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/appjson-300x94.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/appjson-50x16.png 50w" sizes="(max-width: 503px) 100vw, 503px" /></figure>



<p>* To generate the random key use </p>



<figure class="wp-block-embed">
<div class="wp-block-embed__wrapper">https://www.random.org/strings</div>
</figure>



<p>* For issuer and audience local URL follow the below steps</p>



<p>Project properties &#8211;&gt; Debug &#8211;&gt; General &#8211;&gt; Open Debug Launch Profile UI</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="624" height="186" class="wp-image-3164 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/09/debugUI.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/09/debugUI.png 624w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/debugUI-300x89.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/debugUI-50x15.png 50w" sizes="(max-width: 624px) 100vw, 624px" /></figure>



<p>Select IIS Express and pick the App URL</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="624" height="228" class="wp-image-3165 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/09/sqldebugging.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/09/sqldebugging.png 624w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/sqldebugging-300x110.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/09/sqldebugging-50x18.png 50w" sizes="(max-width: 624px) 100vw, 624px" /></figure>



<pre class="wp-block-code"><code>"Jwt": {
    "Key": "ACDt1vR3lXToPQ1g3MyN", //Generate random String from https://www.random.org/strings
    "Issuer": "http://localhost:28747/", //Project Property-&gt; Debug-&gt; IIS--&gt;App URL (you can local host url as well)
    "Audience": "http://localhost:28747/"
  },</code></pre>



<h2 class="wp-block-heading">4. Register JWT token for Authentication in Program.cs file</h2>



<pre class="wp-block-code"><code>using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//JWT Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =&gt; {
    options.TokenValidationParameters = new TokenValidationParameters {
        ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();</code></pre>



<h2 class="wp-block-heading">5. Create Models (UserLogin, UserModel and UserConstant)</h2>



<p>Add a new folder with Models name and create UserLogin, UserModel and UserConstant classes.</p>



<pre class="wp-block-code"><code>namespace JWTLoginAuthenticationAuthorization.Models
{
    public class UserModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public string Role { get; set; }
    }
}</code></pre>



<pre class="wp-block-code"><code>namespace JWTLoginAuthenticationAuthorization.Models
{
    public class UserLogin
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
}</code></pre>



<pre class="wp-block-code"><code>namespace JWTLoginAuthenticationAuthorization.Models
{
    // We are not taking data from data base so we get data from constant
    public class UserConstants
    {
        public static List&lt;UserModel&gt; Users = new()
            {
                    new UserModel(){ Username="naeem",Password="naeem_admin",Role="Admin"}
            };
    }
}</code></pre>



<h2 class="wp-block-heading">6. Create LoginAPI Controller (Authenticate user and generate token)</h2>



<p>Add a new Empty API controller name “LoginController” in controller folder.</p>



<figure class="wp-block-image"><img decoding="async" class="aligncenter" src="https://csharpcorner-mindcrackerinc.netdna-ssl.com/article/jwt-token-creation-authentication-and-authorization-in-asp-net-core-6-0-with-po/Images/Picture8.png" alt="JWT Token Creation, Authentication and Authorization in ASP.Net Core 6.0 with Postman" /></figure>



<p>Here creates one Post Action method for Login and two methods for Authenticating the user credentials and Generate the token (if user is authenticated).</p>



<pre class="wp-block-code"><code>using JWTLoginAuthenticationAuthorization.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace JWTLoginAuthenticationAuthorization.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IConfiguration _config;
        public LoginController(IConfiguration config)
        {
            _config = config;
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login([FromBody] UserLogin userLogin)
        {
            var user = Authenticate(userLogin);
            if (user != null)
            {
                var token = GenerateToken(user);
                return Ok(token);
            }

            return NotFound("user not found");
        }

        // To generate token
        private string GenerateToken(UserModel user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier,user.Username),
                new Claim(ClaimTypes.Role,user.Role)
            };
            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                _config["Jwt:Audience"],
                claims,
                expires: DateTime.Now.AddMinutes(15),
                signingCredentials: credentials);


            return new JwtSecurityTokenHandler().WriteToken(token);

        }

        //To authenticate user
        private UserModel Authenticate(UserLogin userLogin)
        {
            var currentUser = UserConstants.Users.FirstOrDefault(x =&gt; x.Username.ToLower() ==
                userLogin.Username.ToLower() &amp;&amp; x.Password == userLogin.Password);
            if (currentUser != null)
            {
                return currentUser;
            }
            return null;
        }
    }
}</code></pre>



<h2 class="wp-block-heading">7. Create User API Controller to authorize user role</h2>



<p>Add new empty API controller named “UserController.cs” in controller folder.</p>



<p>Here we will authorize the endpoint on the behalf of role. </p>



<pre class="wp-block-code"><code>namespace JWTLoginAuthenticationAuthorization.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        //For admin Only
        [HttpGet]
        [Route("Admins")]
        [Authorize(Roles = "Admin")]
        public IActionResult AdminEndPoint()
        {
            var currentUser = GetCurrentUser();
            return Ok($"Hi you are an {currentUser.Role}");
        }
        private UserModel GetCurrentUser()
        {
            var identity = HttpContext.User.Identity as ClaimsIdentity;
            if (identity != null)
            {
                var userClaims = identity.Claims;
                return new UserModel
                {
                    Username = userClaims.FirstOrDefault(x =&gt; x.Type == ClaimTypes.NameIdentifier)?.Value,
                    Role = userClaims.FirstOrDefault(x =&gt; x.Type == ClaimTypes.Role)?.Value
                };
            }
            return null;
        }
    }
}</code></pre>



<h2 class="wp-block-heading">8. Test the API endpoint in Postman with Token</h2>



<p>Run the application and copy the URL domain from the browser.</p>



<p>Now open the Postman, give the URL with correct API route and select post request &#8211;&gt; Body &#8211;&gt; Json &#8211;&gt; give the value of Username and Password</p>



<figure class="wp-block-image"><img decoding="async" class="aligncenter" src="https://csharpcorner-mindcrackerinc.netdna-ssl.com/article/jwt-token-creation-authentication-and-authorization-in-asp-net-core-6-0-with-po/Images/Picture9.png" alt="JWT Token Creation, Authentication and Authorization in ASP.Net Core 6.0 with Postman" /></figure>



<p>After clicking on send button we will get the JWT token in response.</p>



<figure class="wp-block-image"><img decoding="async" class="aligncenter" src="https://csharpcorner-mindcrackerinc.netdna-ssl.com/article/jwt-token-creation-authentication-and-authorization-in-asp-net-core-6-0-with-po/Images/Picture10.png" alt="JWT Token Creation, Authentication and Authorization in ASP.Net Core 6.0 with Postman" /></figure>



<p>Now copy this token and add a new Get request in postman and add the JWT token Authorization Tab &#8211;&gt; Select Bearer &#8211;&gt; Insert token and click on send button to test the authorization with given token.</p>



<p>If the token is not valid token then we will get 401 Error otherwise will get the bolow result.</p>



<figure class="wp-block-image"><img decoding="async" class="aligncenter" src="https://csharpcorner-mindcrackerinc.netdna-ssl.com/article/jwt-token-creation-authentication-and-authorization-in-asp-net-core-6-0-with-po/Images/Picture11.png" alt="JWT Token Creation, Authentication and Authorization in ASP.Net Core 6.0 with Postman" /></figure>



<h2 class="wp-block-heading">Summary</h2>



<p>So we created the token and did the authentication on the behalf of username and password then check the user authorization.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-authenticate-and-authorize-jwt-token-in-asp-net-core-6/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
