Http Backchannel Use Proxy and Read Proxy Settings Jwt .net Core
JWT in ASP.NET Cadre
JWT (JSON web token) has become more and more popular in web evolution. It is an open up standard which allows transmitting information between parties as a JSON object in a secure and meaty way. The information transmitting using JWT between parties are digitally signed and so that information technology can be hands verified and trusted.
In this article, nosotros will learn how to setup JWT with ASP.Cyberspace core web awarding. We can create an awarding using Visual Studio or using CLI (Command Line Interface).
- dotnet new webapi -northward JWTAuthentication
Above control will create an ASP.Internet Spider web API project with the proper name "JWTAuthentication" in the current binder.
The outset pace is to configure JWT based authentication in our projection. To exercise this, we need to register a JWT authentication schema by using "AddAuthentication" method and specifying JwtBearerDefaults.AuthenticationScheme. Here, we configure the authentication schema with JWT bearer options.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(options =>
- {
- options.TokenValidationParameters =new TokenValidationParameters
- {
- ValidateIssuer =true ,
- ValidateAudience =true ,
- ValidateLifetime =true ,
- ValidateIssuerSigningKey =truthful ,
- ValidIssuer = Configuration["Jwt:Issuer" ],
- ValidAudience = Configuration["Jwt:Issuer" ],
- IssuerSigningKey =new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration[ "Jwt:Key" ]))
- };
- });
- services.AddMvc();
- }
In this example, we accept specified which parameters must be taken into account to consider JWT as valid. Every bit per our lawmaking, the following items consider a token valid:
- Validate the server (ValidateIssuer = truthful) that generates the token.
- Validate the recipient of the token is authorized to receive (ValidateAudience = truthful)
- Check if the token is not expired and the signing key of the issuer is valid (ValidateLifetime = truthful)
- Validate signature of the token (ValidateIssuerSigningKey = true)
- Additionally, we specify the values for the issuer, audience, signing key. In this example, I accept stored these values in appsettings.json file.
AppSetting.Json
- {
- "Jwt": {
- "Key": "ThisismySecretKey",
- "Issuer": "Examination.com"
- }
- }
The above-mentioned steps are used to configure a JWT based authentication service. The next stride is to make the authentication service is bachelor to the application. To do this, we demand to call app.UseAuthentication() method in the Configure method of startup class. The UseAuthentication method is chosen before UseMvc method.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- app.UseAuthentication();
- app.UseMvc();
- }
Generate JSON Web Token
I have created a LoginController and Login method inside this controller, which is responsible to generate the JWT. I have marked this method with the AllowAnonymous attribute to featherbed the authentication. This method expects the Usermodel object for Username and Password.
I have created the "AuthenticateUser" method, which is responsible to validate the user credential and returns to the UserModel. For demo purposes, I have returned the hardcode model if the username is "Jignesh". If the "AuthenticateUser" method returns the user model, API generates the new token by using the "GenerateJSONWebToken" method.
Here, I have created a JWT using the JwtSecurityToken class. I accept created an object of this course past passing some parameters to the constructor such as issuer, audience, expiration, and signature.
Finally, JwtSecurityTokenHandler.WriteToken method is used to generate the JWT. This method expects an object of the JwtSecurityToken class.
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.IdentityModel.Tokens;
- using Organisation;
- using System.IdentityModel.Tokens.Jwt;
- using System.Security.Claims;
- using System.Text;
- namespace JWTAuthentication.Controllers
- {
- [Route("api/[controller]" )]
- [ApiController]
- public grade LoginController : Controller
- {
- private IConfiguration _config;
- public LoginController(IConfiguration config)
- {
- _config = config;
- }
- [AllowAnonymous]
- [HttpPost]
- public IActionResult Login([FromBody]UserModel login)
- {
- IActionResult response = Unauthorized();
- var user = AuthenticateUser(login);
- if (user != null )
- {
- var tokenString = GenerateJSONWebToken(user);
- response = Ok(new { token = tokenString });
- }
- return response;
- }
- individual string GenerateJSONWebToken(UserModel userInfo)
- {
- var securityKey =new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config[ "Jwt:Key" ]));
- var credentials =new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
- var token =new JwtSecurityToken(_config[ "Jwt:Issuer" ],
- _config["Jwt:Issuer" ],
- zippo ,
- expires: DateTime.Now.AddMinutes(120),
- signingCredentials: credentials);
- return new JwtSecurityTokenHandler().WriteToken(token);
- }
- private UserModel AuthenticateUser(UserModel login)
- {
- UserModel user =null ;
- if (login.Username == "Jignesh" )
- {
- user =new UserModel { Username = "Jignesh Trivedi" , EmailAddress = "exam.btest@gmail.com" };
- }
- return user;
- }
- }
- }
In one case, nosotros take enabled the JWT based authentication, I have created a unproblematic Web API method that returns a list of value strings when invoked with an HTTP GET request. Here, I have marked this method with the authorize attribute, so that this endpoint will trigger the validation check of the token passed with an HTTP request.
If we telephone call this method without a token, we volition get 401 (UnAuthorizedAccess) HTTP status lawmaking equally a response. If we want to bypass the authentication for any method, we can mark that method with the AllowAnonymous attribute.
To test the created Web API, I am Using Fiddler. First, I have requested to "API/login" method to generate the token. I have passed the following JSON in the request body.
- { "username" : "Jignesh" , "password" : "password" }
Equally a response, we will go the JSON like the post-obit,
- {
- "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKaWduZXNoIFRyaXZlZGkiLCJlbWFpbCI6InRlc3QuYnRlc3RAZ21haWwuY29tIiwiRGF0ZU9mSm9pbmciOiIwMDAxLTAxLTAxIiwianRpIjoiYzJkNTZjNzQtZTc3Yy00ZmUxLTgyYzAtMzlhYjhmNzFmYzUzIiwiZXhwIjoxNTMyMzU2NjY5LCJpc3MiOiJUZXN0LmNvbSIsImF1ZCI6IlRlc3QuY29tIn0.8hwQ3H9V8mdNYrFZSjbCpWSyR1CNyDYHcGf6GqqCGnY"
- }
Now, nosotros will try to get the listing of values by passing this token into the authentication HTTP header. Post-obit is my Action method definition.
- [HttpGet]
- [Qualify]
- public ActionResult<IEnumerable< cord >> Get()
- {
- render new string [] { "value1" , "value2" , "value3" , "value4" , "value5" };
- }
- Say-so: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKaWduZXNoIFRyaXZlZGkiLCJlbWFpbCI6InRlc3QuYnRlc3RAZ21haWwuY29tIiwiRGF0ZU9mSm9pbmciOiIwMDAxLTAxLTAxIiwianRpIjoiYzJkNTZjNzQtZTc3Yy00ZmUxLTgyYzAtMzlhYjhmNzFmYzUzIiwiZXhwIjoxNTMyMzU2NjY5LCJpc3MiOiJUZXN0LmNvbSIsImF1ZCI6IlRlc3QuY29tIn0.8hwQ3H9V8mdNYrFZSjbCpWSyR1CNyDYHcGf6GqqCGnY
Handle Claims with JWT
Claims are data contained by the token. They are information about the user which helps the states to authorize admission to a resource. They could be Username, email accost, office, or any other data. Nosotros can add claims data to the JWT so that they are available when checking for authority.
In the above example, if nosotros want to pass the claims to our token and then the claim data needs to add together GenerateJSONWebToken method of Login controller. In the following example, I have added a username, electronic mail address, and date of joining as claimed into the token.
- private string GenerateJSONWebToken(UserModel userInfo)
- {
- var securityKey =new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config[ "Jwt:Central" ]));
- var credentials =new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
- var claims =new [] {
- new Merits(JwtRegisteredClaimNames.Sub, userInfo.Username),
- new Claim(JwtRegisteredClaimNames.Email, userInfo.EmailAddress),
- new Claim( "DateOfJoing" , userInfo.DateOfJoing.ToString( "yyyy-MM-dd" )),
- new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
- };
- var token =new JwtSecurityToken(_config[ "Jwt:Issuer" ],
- _config["Jwt:Issuer" ],
- claims,
- expires: DateTime.Now.AddMinutes(120),
- signingCredentials: credentials);
- return new JwtSecurityTokenHandler().WriteToken(token);
- }
The claims are an array of central-value pair. The keys may exist values of a JwtRegisteredClaimNames structure (it provides names for public standardized claims) or custom name (such as DateOfJoining in in a higher place example).
This claims tin can be used to filter the information. In the following instance, I accept to change the listing of values if the user spends more than five years with the company.
- [HttpGet]
- [Authorize]
- public ActionResult<IEnumerable< string >> Get()
- {
- var currentUser = HttpContext.User;
- int spendingTimeWithCompany = 0;
- if (currentUser.HasClaim(c => c.Blazon == "DateOfJoing" ))
- {
- DateTime appointment = DateTime.Parse(currentUser.Claims.FirstOrDefault(c => c.Type =="DateOfJoing" ).Value);
- spendingTimeWithCompany = DateTime.Today.Year - date.Year;
- }
- if (spendingTimeWithCompany > 5)
- {
- render new string [] { "High Time1" , "High Time2" , "High Time3" , "High Time4" , "High Time5" };
- }
- else
- {
- render new string [] { "value1" , "value2" , "value3" , "value4" , "value5" };
- }
- }
Summary
JWT is very famous in web development. It is an open up standard that allows transmitting data betwixt parties equally a JSON object in a secure and compact way. In this commodity, we will learn how to generate and use JWT with ASP.NET cadre application.
You tin can view or download the source lawmaking from the GitHub link here.
Source: https://www.c-sharpcorner.com/article/jwt-json-web-token-authentication-in-asp-net-core/
0 Response to "Http Backchannel Use Proxy and Read Proxy Settings Jwt .net Core"
Publicar un comentario