0

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.

2
  • you say "but using that token for a POST request it shows unauthorized error.". How did you use it? Did you add an Authorization header? Commented Nov 29, 2018 at 10:48
  • Yes. Authorization header is added as Bearer token Commented Nov 30, 2018 at 4:39

1 Answer 1

1
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)
{
}
Sign up to request clarification or add additional context in comments.

1 Comment

also logging the exception would be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.