Click here to Skip to main content
14,733,444 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I work on asp.net core 2.2 application and i need to generate access token by using jwt
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 ?

What I have tried:

{
"request_status" : {
"status" : "succeeded",
"code": 0,
"message" : "login succeeded!"
},
"access_token" : "",
"user_data": { 
  "UserFullName" : "Ahmed", 
  "LoginTime" : "12", 
  "Admin" : "adil"
  
},
"branches": [
{ 
  "BranchCode" : "1",
  "BranchName":"Baha" 
  
}
]
}
Posted
Updated 15-Sep-19 19:34pm
Comments
Richard MacCutchan 1-Sep-19 6:48am
   
I don't know what you searched for but google "access+token+by+using+jwt", which will find you lots of useful information.

1 solution

You need to implement below code in a controller.
public class LoginController : Controller
    {
        private IConfiguration _config;

        public LoginController(IConfiguration config)
        {
            _config = config;
        }
        
        [AllowAnonymous]
        [HttpPost]
        [Route("Login")]
        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;
        }

        private 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"],
              null,
              expires: DateTime.Now.AddSeconds(500),
              signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        private UserModel AuthenticateUser(UserModel login)
        {
            UserModel user = null;

            //Validate the User Credentials  
            //Demo Purpose, I have Passed HardCoded User Information  
            if (login.Username == "Abc")
            {
                user = new UserModel { Username = "Abc Xyz", Password = "12345" };
            }
            return user;
        }
    }

Here, i have login controller for this. When user Logged-in then above method will generate token.
But you need to change code in your startup.cs file like below:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection 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:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }


Now Generate Another controller for test Login Controller.
Here i have Test Controller:
[Route("api/[controller]")]
   [ApiController]
   public class TestController : ControllerBase
   {
       [HttpGet]
       [Authorize]
       [Route("Get")]
       public ActionResult<IEnumerable<string>> Get()
       {
           return new string[] { "value1", "value2", "value3", "value4", "value5" };
       }
   }

You can see that Get() method in test controller is Authorize. So when user will access Get() in Test Controller without Login, error will display.

So Methods in Login Controller will generate Token then by use that generated token, user can access Get() method and Data will display.

Hope this will help you.
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900