Naila Akbar
Naila Akbar

Reputation: 3358

Simple Authentication using Jwt in dot net core MVC

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.

Upvotes: 0

Views: 1253

Answers (1)

Alex Zhang
Alex Zhang

Reputation: 1118

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*/
});

Upvotes: 2

Related Questions