locked
How to generate access token by using jwt ? RRS feed

  • Question

  • User696604810 posted

    I work on asp.net core 2.2 application and i need to generate access token by using jwt and what is payload 


    i dont know how to generate i search more on internet but not understand what this mean


    i need actually when make success login generate access token but i dont know what this term made and how to generate ?


    can you please show me any sample code or explain that ?

    {
    "request_status" : {
    "status" : "succeeded",
    "code": 0,
    "message" : "login succeeded!"
    },
    
    "access_token" : "",
    
    "user_data": {
    
    "UserFullName" : "Ahmed",
    
    "LoginTime" : "12",
    
    "Admin" : "adil"
    
    
    },
    "branches": [
    {
    "BranchCode" : "1",
    "BranchName":"Baha"
    
    }
    
    ]
    
    }



    Sunday, September 1, 2019 3:32 AM

All replies

  • User718448626 posted

    Hi,

    You need this in your server code.    Create a MyData class to contain your json data and the controller will automatically convert the "POST" to the data if the structure is correct.  Use sometime like postman or RestLet (Chrome browser) to test your web api.  You need to get the Token from the controller first.

    //Startup.cs
       
       public void ConfigureServices(IServiceCollection services)
       {   
    	  // Add This to the ConfigureServices section
          services.AddAuthentication(option =>
                        {
                            option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                            option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                            option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                        })
    
                        .AddJwtBearer(options =>
                        {
                            options.TokenValidationParameters =
                             new TokenValidationParameters
                             {
                                 // The signing key must match!
                                 ValidateIssuerSigningKey = true,
                                 // Validate the JWT Issuer (iss) claim
                                 ValidateIssuer = true,
                                 // Validate the JWT Audience (aud) claim
                                 ValidateAudience = true,
                                 // Validate the token expiry
                                 ValidateLifetime = true,
    
                                 IssuerSigningKey = new SymmetricSecurityKey(Encoding.Utf8.GetBytes("MySuperSecretPassword")),
                                 
                                 ValidIssuer = "https://www.mysupervwebsite.com",
                                 ValidAudience = "https://www.mysupervwebsite.com",
    							 
                                 // If you want to allow a certain amount of clock drift, set that here:
                                 ClockSkew = TimeSpan.Zero
                             };
    	  }}
    	  
    	  }
    	  
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
     
            // Add this line
    	    app.UseAuthentication();
    		
    		 app.UseMvc();
    	 )
    	 
    
    //ValueController.cs
    
    
    namespace MyApp.Controllers
    {
        [Authorize]
        [Route("api/[controller]")]
        [Produces("application/json")]
        [ApiController]
        public class ValueController : ControllerBase
        {	 
    	   
    public ValueController() {}

    public IActionResult Post([FromBody] MyData data )
    {
    // Do Work;
    return Ok();
    }
    } }


    // TokenController.cs

    [AllowAnonymous]
    [HttpGet("GetToken")]
    public IActionResult GetToken(string user, string password)
    {
    var jwt = new JwtToken();
    //Secret ID of the User from Database
    var sid = GetFromDB(user,password);

    List<Claim> claimslist = new List<Claim>()
    {
    new Claim(ClaimTypes.Sid, sid ),
    new Claim(ClaimTypes.Role, role),
    new Claim(ClaimTypes.Role, "Doctor")
    };

    var retval = new JwtSecurityToken(
    issuer: "https://www.mysupervwebsite.com",
    audience: "https://www.mysupervwebsite.com",
    claims: claimlist,
    expires: DateTime.UtcNow.AddSeconds(120),
    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.Utf8.GetBytes("MySuperSecretPassword")), SecurityAlgorithms.HmacSha256)

    );

    string token = new JwtSecurityTokenHandler().WriteToken(retval);


    return Ok(token);

    }

    Sunday, September 1, 2019 7:25 AM
  • User696604810 posted

    thank you for reply 

    action above return access token so that i need to get access token  merged with data object i make post to it

    this is my post action 

      [HttpPost(Contracts.ApiRoutes.Login.UserLogin)]
            public  IActionResult PostUserLogins([FromBody]Users user)
            {
    
                string JsonResults = "";
                int LoginStatus = _AuthunticateService.PostUserLogin(user.UserName,user.Password ,out DataTable dtBranches,out string errorMessage, out int statusCode);
                if(LoginStatus == 0)
                {
                    user.StatusCode = statusCode;
                    user.StatusText = "succeeded";
                    user.MessageStatus = "login succeeded!";
                    List<Branches> branchesList = new List<Branches>() ;
                    for (int i=0;i< dtBranches.Rows.Count -1;i++)
                    {
                        Branches branch = new Branches();
                        branch.BranchCode = Utilities.ObjectConverter.ConvertToInteger(dtBranches.Rows[i]["BranchCode"]);
                        branch.BranchName = Utilities.ObjectConverter.ConvertToString(dtBranches.Rows[i]["BranchCode"]);
                        branchesList.Add(branch);
                    }
                    user.Branches = branchesList;
                    user.LoginTime = DateTime.Now.ToString();
                    // How to get access token here 
                    JsonResults = JsonConvert.SerializeObject(user);
                }

    access token must convert to json with data i make post to it .

    how to get access token from another action you do .

    //How to add access token
     user.StatusCode = statusCode;
     user.StatusText = "succeeded";
     user.MessageStatus = "login succeeded!";

    Monday, September 2, 2019 12:19 AM
  • User718448626 posted

    Below is  the code to extact the Jwt Token claims.  Also you do not want to added user identifiable data in the JWT token as it can be unpacked by anyone with some knowledge.

    [HttpPost(Contracts.ApiRoutes.Login.UserLogin)]
    public IActionResult PostUserLogins([FromBody]Users user)
    {
    // The Users class is the data that you passed from the body of the Post and the data must be in 
    // Json Format that match the Users class
    
    // This will extract the Claims from the token passed
    var sid = User.Claims.Where(w => w.Type == ClaimTypes.Sid).FirstOrDefault();
    var role = var sid = User.Claims.Where(w => w.Type == ClaimTypes.Role).FirstOrDefault();
    
    }

    Monday, September 2, 2019 1:10 AM
  • User-1764593085 posted

    Hi ahmedbarbary,

    If you use JWT authentication, the authorization header will contains the jwt token and it starts with "Bearer ", try to use `HttpContext` to get the token in controller like:

    var authHeader = HttpContext.Request.Headers["Authorization"].ToString();//Which starts with "Bearer "
    var token = authHeader.Substring("Bearer ".Length).Trim();

    user.access_token = token;

    With Regards.

    Monday, September 2, 2019 2:44 AM
  • User696604810 posted

    can you explain these two lines

    var sid = User.Claims.Where(w => w.Type == ClaimTypes.Sid).FirstOrDefault();
    var role = var sid = User.Claims.Where(w => w.Type == ClaimTypes.Role).FirstOrDefault();
    where this table exist
    im not have claim on user table


    Monday, September 2, 2019 8:41 AM
  • User-1764593085 posted

    ahmedbarbary

    can you explain these two lines

    var sid = User.Claims.Where(w => w.Type == ClaimTypes.Sid).FirstOrDefault();
    var role = var sid = User.Claims.Where(w => w.Type == ClaimTypes.Role).FirstOrDefault();
    where this table exist 
    im not have claim on user table 
    

    The code`User.Claims` means ` HttpContext.User.Claims` not the User table. Above code is to retrieve claims form the HttpContext, the claims are added when you create token in below code.

    [AllowAnonymous]
    [HttpGet("GetToken")]
    public IActionResult GetToken(string user, string password)
    {
    var jwt = new JwtToken();
    //Secret ID of the User from Database
    var sid = GetFromDB(user,password);
    
    List<Claim> claimslist = new List<Claim>()
    {
    new Claim(ClaimTypes.Sid, sid ),
    new Claim(ClaimTypes.Role, role),
    new Claim(ClaimTypes.Role, "Doctor")
    };
    
    var retval = new JwtSecurityToken(
    issuer: "https://www.mysupervwebsite.com",
    audience: "https://www.mysupervwebsite.com",
    claims: claimlist, 
    expires: DateTime.UtcNow.AddSeconds(120),
    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.Utf8.GetBytes("MySuperSecretPassword")), SecurityAlgorithms.HmacSha256)
    
    );
    
    string token = new JwtSecurityTokenHandler().WriteToken(retval);
    
    
    return Ok(token);
    
    }

    With Regards,

    Xing

    Tuesday, September 3, 2019 1:55 AM
  • User1168443798 posted

    For Asp.net Core with jwt authentication, you could refer link below step by step.

    #ASP.NET Core 2.2 - JWT Authentication Tutorial with Example API

    https://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api

    Wednesday, September 25, 2019 8:44 AM