Anoop Balachandran
Anoop Balachandran

Reputation: 56

Web Api JWT token Authentication

I'm trying to create and consume a jwt token. The token generated successfully but using that token for a POST request it shows unauthorized error.

My startup.cs looks like this:

public void Configuration(IAppBuilder app)
{
    ConfigureAuth(app);
}

public void ConfigureAuth(IAppBuilder app)
{

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JWTTokenKey"]));

    var signInCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

    app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            //AuthenticationMode = AuthenticationMode.Active,
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidAudience = ConfigurationManager.AppSettings["Application"],
                ValidIssuer = ConfigurationManager.AppSettings["Application"],
                IssuerSigningKey = key
            }
        });
}

LoginController

public class LoginController : ApiController
{
    [HttpPost]
    [Route("api/v1/Login/Signin")]
    public IHttpActionResult Signin([FromBody] LoginModel login)
    {
        var claims = new[] { new Claim("UserName", login.UserName) };
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JWTTokenKey"]));
        var signInCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
        var jwt = new JwtSecurityToken(
                issuer: ConfigurationManager.AppSettings["Application"],
                audience: ConfigurationManager.AppSettings["Application"],
                expires: DateTime.Now.AddMinutes(5),
                claims: claims,
                signingCredentials: signInCredentials
            );
        var token = new JwtSecurityTokenHandler().WriteToken(jwt);
        return Json(new
        {
            access_token = token,
            expires = Convert.ToString(jwt.ValidTo)
        });
    }

    [Authorize]
    [HttpPost]
    public int Register(int id)
    {
        return 1;
    }

    [HttpPost]
    public void TestPost([FromBody]string value)
    {
    }

    public class LoginModel
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}

How can i call the Register method in LoginController with generated jwt token. Thanks in advance.

Upvotes: 0

Views: 199

Answers (1)

Murat Şanlısavaş
Murat Şanlısavaş

Reputation: 208

try
{
  using ( HttpClientHandler handler = new HttpClientHandler())
  {
    using(HttpClient c = new HttpClient(handler))
    {
      c.DefaultRequestHeaders.Add("Authorization","Bearer " + UsersJwtToken);
      //Get the token and attach it here.
      //This is how you add jwt token to your requests.
      //After this you can just make requests to the API.
     
    }

  }
}
catch(Exception ex)
{
}

Upvotes: 1

Related Questions