0

I'm trying to add JWT validation in my dot net core application. I've followed this link to understand JWT and able to generate a token by givings some values like this.

var token = new JwtSecurityToken(
  issuer: issuer,
  audience: aud,
  claims: claims,
  expires: expTime,
  signingCredentials: creds
);

Edit: and to follow this answer, I've also added JwtBearerAuthentication middleware in my app by adding app.UseJwtBearerAuthentication(new JwtBearerOptions { /* options */ }) to Startup.Configure() method.

Now I'm stuck how could I pass this token inside HTTP header? I'm generating this token on Login but whats next? How could I get to know that JWT is added and working fine??

Any kind of help will be appreciated.

1 Answer 1

2

This is a runnable sample for bearer token authentication in ASP.NET Core.
How to achieve a bearer token authentication and authorization in ASP.NET Core

At back end, you can generate the token following this code:

[Route("api/[controller]")]
public class TokenAuthController : Controller
{
    [HttpPost]
    public string GetAuthToken(User user)
    {
        var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password);

        if (existUser != null)
        {
            var requestAt = DateTime.Now;
            var expiresIn = requestAt + TokenAuthOption.ExpiresSpan;
            var token = GenerateToken(existUser, expiresIn);

            return JsonConvert.SerializeObject(new {
                stateCode = 1,
                requertAt = requestAt,
                expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds,
                accessToken = token
            });
        }
        else
        {
            return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" });
        }
    }

    private string GenerateToken(User user, DateTime expires)
    {
        var handler = new JwtSecurityTokenHandler();

        ClaimsIdentity identity = new ClaimsIdentity(
            new GenericIdentity(user.Username, "TokenAuth"),
            new[] {
                new Claim("ID", user.ID.ToString())
            }
        );

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = TokenAuthOption.Issuer,
            Audience = TokenAuthOption.Audience,
            SigningCredentials = TokenAuthOption.SigningCredentials,
            Subject = identity,
            Expires = expires
        });
        return handler.WriteToken(securityToken);
    }
}

In Startup.cs/ConfigureServices method

services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
        .RequireAuthenticatedUser().Build());
});

And add this code in Configure method

app.UseJwtBearerAuthentication(new JwtBearerOptions {
    TokenValidationParameters = new TokenValidationParameters {
        IssuerSigningKey = TokenAuthOption.Key,
        ValidAudience = TokenAuthOption.Audience,
        ValidIssuer = TokenAuthOption.Issuer,
        ValidateIssuerSigningKey = true,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromMinutes(0)
    }
});

At front end, you just add the token to header like this:

$.ajaxSetup({
    headers: { "Authorization": "Bearer " + accessToken }
});

or

$.ajax("http://somedomain/somepath/somepage",{
    headers:{ "Authorization": "Bearer " + accessToken },
    /*some else parameter for ajax, see more you can review the Jquery API*/
});
Sign up to request clarification or add additional context in comments.

5 Comments

from where and how I can get that accessToken??
You can find the code in Controllers/TokenAuthController.cs from the code sample.
is there any way to implement this solution through razor syntax? where we don't have ajax calls?
It's can not add the http header to the form request in browser. but you can set the token to cookie in browser, and in server side, add a middleware to set the httpheader by cookie.
maybe you should create another question for web jwt web page authentication.

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.