基于.NET Core 2.0的 JWT

为了让 JWT 在 DotNet 核心2.0上工作(现在已经到了最终版本) ,我经历了相当大的一次冒险。有一个 的文档,但所有的示例代码似乎都使用过时的 API,并新鲜到核心,它是积极地令人头晕目眩,以指出它究竟应该如何实现。我试过用何塞,但是应用程序。UseJwtBearerAuthentication 已被弃用,并且没有关于下一步要做什么的文档。

是否有任何使用 dotnet core 2.0的开源项目可以简单地从授权头解析 JWT 并允许我授权对 HS256编码的 JWT 令牌的请求?

下面的类没有抛出任何异常,但是没有请求被授权,而且我没有得到任何指示 为什么它们是未授权的。答案是空的401所以对我来说没有例外但是秘密不匹配。

奇怪的是,我的令牌是用 HS256算法加密的,但是我没有看到任何指示器告诉它强制它在任何地方使用该算法。

这是我目前上的课:

using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using Microsoft.IdentityModel.Tokens;
using System.Text;


namespace Site.Authorization
{
public static class SiteAuthorizationExtensions
{
public static IServiceCollection AddSiteAuthorization(this IServiceCollection services)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("SECRET_KEY"));


var tokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKeys = new List<SecurityKey>{ signingKey },




// Validate the token expiry
ValidateLifetime = true,
};


services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;




})


.AddJwtBearer(o =>
{
o.IncludeErrorDetails = true;
o.TokenValidationParameters  = tokenValidationParameters;
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();


c.Response.StatusCode = 401;
c.Response.ContentType = "text/plain";


return c.Response.WriteAsync(c.Exception.ToString());
}


};
});


return services;
}
}
}
67508 次浏览

My tokenValidationParameters works when they look like this:

 var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = GetSignInKey(),
ValidateIssuer = true,
ValidIssuer = GetIssuer(),
ValidateAudience = true,
ValidAudience = GetAudience(),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};

and

    static private SymmetricSecurityKey GetSignInKey()
{
const string secretKey = "very_long_very_secret_secret";
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));


return signingKey;
}


static private string GetIssuer()
{
return "issuer";
}


static private string GetAudience()
{
return "audience";
}

Moreover, add options.RequireHttpsMetadata = false like this:

         .AddJwtBearer(options =>
{
options.TokenValidationParameters =tokenValidationParameters
options.RequireHttpsMetadata = false;
});

EDIT:

Dont forget to call

 app.UseAuthentication();

in Startup.cs -> Configure method before app.UseMvc();

Here is a solution for you.

In your startup.cs, firstly, config it as services:

  services.AddAuthentication().AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = "somethong",
ValidAudience = "something",
:
};
});

second, call this services in config

          app.UseAuthentication();

now you can use it in your controller by add attribute

          [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpGet]
public IActionResult GetUserInfo()
{

For full details source code that use angular as Frond-end see here

Here is my implementation for a .Net Core 2.0 API:

    public IConfigurationRoot Configuration { get; }


public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc(
config =>
{
// This enables the AuthorizeFilter on all endpoints
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
            

}
).AddJsonOptions(opt =>
{
opt.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});


services.AddLogging();


services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Audience = Configuration["AzureAD:Audience"];
options.Authority = Configuration["AzureAD:AADInstance"] + Configuration["AzureAD:TenantId"];
});
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAuthentication(); // THIS METHOD MUST COME BEFORE UseMvc...() !!
app.UseMvcWithDefaultRoute();
}

appsettings.json:

{
"AzureAD": {
"AADInstance": "https://login.microsoftonline.com/",
"Audience": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"ClientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"Domain": "mydomain.com",
"TenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
},
...
}

The above code enables auth on all controllers. To allow anonymous access you can decorate an entire controller:

[Route("api/[controller]")]
[AllowAnonymous]
public class AnonymousController : Controller
{
...
}

or just decorate a method to allow a single endpoint:

    [AllowAnonymous]
[HttpPost("anonymousmethod")]
public async Task<IActionResult> MyAnonymousMethod()
{
...
}

Notes:

  • This is my first attempt at AD auth - if anything is wrong, please let me know!

  • Audience must match the Resource ID requested by the client. In our case our client (an Angular web app) was registered separately in Azure AD, and it used its Client Id, which we registered as the Audience in the API

  • ClientId is called Application ID in the Azure Portal (why??), the Application ID of the app registration for the API.

  • TenantId is called Directory ID in the Azure Portal (why??), found under Azure Active Directory > Properties

  • If deploying the API as an Azure hosted Web App, ensure you set the Application Settings:

    eg. AzureAD:Audience / xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

Here is a full working minimal sample with a controller. I hope you can check it using Postman or JavaScript call.

  1. appsettings.json, appsettings.Development.json. Add a section. Note, Key should be rather long and Issuer is an address of the service:

    ...
    ,"Tokens": {
    "Key": "Rather_very_long_key",
    "Issuer": "http://localhost:56268/"
    }
    ...
    

    !!! In real project, don't keep Key in appsettings.json file. It should be kept in Environment variable and take it like this:

    Environment.GetEnvironmentVariable("JWT_KEY");
    

UPDATE: Seeing how .net core settings work, you don't need to take it exactly from Environment. You may use setting. However,instead we may write this variable to environment variables in production, then our code will prefer environment variables instead of configuration.

  1. AuthRequest.cs : Dto keeping values for passing login and password:

    public class AuthRequest
    {
    public string UserName { get; set; }
    public string Password { get; set; }
    }
    
  2. Startup.cs in Configure() method BEFORE app.UseMvc() :

    app.UseAuthentication();
    
  3. Startup.cs in ConfigureServices() :

    services.AddAuthentication()
    .AddJwtBearer(cfg =>
    {
    cfg.RequireHttpsMetadata = false;
    cfg.SaveToken = true;
    
    
    cfg.TokenValidationParameters = new TokenValidationParameters()
    {
    ValidIssuer = Configuration["Tokens:Issuer"],
    ValidAudience = Configuration["Tokens:Issuer"],
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
    };
    
    
    });
    
  4. Add a controller:

        [Route("api/[controller]")]
    public class TokenController : Controller
    {
    private readonly IConfiguration _config;
    private readonly IUserManager _userManager;
    
    
    public TokenController(IConfiguration configuration, IUserManager userManager)
    {
    _config = configuration;
    _userManager = userManager;
    }
    
    
    [HttpPost("")]
    [AllowAnonymous]
    public IActionResult Login([FromBody] AuthRequest authUserRequest)
    {
    var user = _userManager.FindByEmail(model.UserName);
    
    
    if (user != null)
    {
    var checkPwd = _signInManager.CheckPasswordSignIn(user, model.authUserRequest);
    if (checkPwd)
    {
    var claims = new[]
    {
    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
    new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()),
    };
    
    
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
    
    var token = new JwtSecurityToken(_config["Tokens:Issuer"],
    _config["Tokens:Issuer"],
    claims,
    expires: DateTime.Now.AddMinutes(30),
    signingCredentials: creds);
    
    
    return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
    }
    }
    
    
    return BadRequest("Could not create token");
    }}
    

That's all folks! Cheers!

UPDATE: People ask how get Current User. Todo:

  1. In Startup.cs in ConfigureServices() add

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    
  2. In a controller add to constructor:

    private readonly int _currentUser;
    public MyController(IHttpContextAccessor httpContextAccessor)
    {
    _currentUser = httpContextAccessor.CurrentUser();
    }
    
  3. Add somewhere an extension and use it in your Controller (using ....)

    public static class IHttpContextAccessorExtension
    {
    public static int CurrentUser(this IHttpContextAccessor httpContextAccessor)
    {
    var stringId = httpContextAccessor?.HttpContext?.User?.FindFirst(JwtRegisteredClaimNames.Jti)?.Value;
    int.TryParse(stringId ?? "0", out int userId);
    
    
    return userId;
    }
    }
    

Asp.net Core 2.0 JWT Bearer Token Authentication Implementation with Web Api Demo

Add Package "Microsoft.AspNetCore.Authentication.JwtBearer"

Startup.cs ConfigureServices()

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;


cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = "me",
ValidAudience = "you",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("rlyaKithdrYVl6Z80ODU350md")) //Secret
};


});

Startup.cs Configure()

// ===== Use Authentication ======
app.UseAuthentication();

User.cs // It is a model class just for example. It can be anything.

public class User
{
public Int32 Id { get; set; }
public string Username { get; set; }
public string Country { get; set; }
public string Password { get; set; }
}

UserContext.cs // It is just context class. It can be anything.

public class UserContext : DbContext
{
public UserContext(DbContextOptions<UserContext> options) : base(options)
{
this.Database.EnsureCreated();
}


public DbSet<User> Users { get; set; }
}

AccountController.cs

[Route("[controller]")]
public class AccountController : Controller
{


private readonly UserContext _context;


public AccountController(UserContext context)
{
_context = context;
}


[AllowAnonymous]
[Route("api/token")]
[HttpPost]
public async Task<IActionResult> Token([FromBody]User user)
{
if (!ModelState.IsValid) return BadRequest("Token failed to generate");
var userIdentified = _context.Users.FirstOrDefault(u => u.Username == user.Username);
if (userIdentified == null)
{
return Unauthorized();
}
user = userIdentified;


//Add Claims
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.UniqueName, "data"),
new Claim(JwtRegisteredClaimNames.Sub, "data"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};


var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("rlyaKithdrYVl6Z80ODU350md")); //Secret
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);


var token = new JwtSecurityToken("me",
"you",
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);


return Ok(new
{
access_token = new JwtSecurityTokenHandler().WriteToken(token),
expires_in = DateTime.Now.AddMinutes(30),
token_type = "bearer"
});
}
}

UserController.cs

[Authorize]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
private readonly UserContext _context;


public UserController(UserContext context)
{
_context = context;
if(_context.Users.Count() == 0 )
{
_context.Users.Add(new User { Id = 0, Username = "Abdul Hameed Abdul Sattar", Country = "Indian", Password = "123456" });
_context.SaveChanges();
}
}


[HttpGet("[action]")]
public IEnumerable<User> GetList()
{
return _context.Users.ToList();
}


[HttpGet("[action]/{id}", Name = "GetUser")]
public IActionResult GetById(long id)
{
var user = _context.Users.FirstOrDefault(u => u.Id == id);
if(user == null)
{
return NotFound();
}
return new ObjectResult(user);
}




[HttpPost("[action]")]
public IActionResult Create([FromBody] User user)
{
if(user == null)
{
return BadRequest();
}


_context.Users.Add(user);
_context.SaveChanges();


return CreatedAtRoute("GetUser", new { id = user.Id }, user);


}


[HttpPut("[action]/{id}")]
public IActionResult Update(long id, [FromBody] User user)
{
if (user == null)
{
return BadRequest();
}


var userIdentified = _context.Users.FirstOrDefault(u => u.Id == id);
if (userIdentified == null)
{
return NotFound();
}


userIdentified.Country = user.Country;
userIdentified.Username = user.Username;


_context.Users.Update(userIdentified);
_context.SaveChanges();
return new NoContentResult();
}




[HttpDelete("[action]/{id}")]
public IActionResult Delete(long id)
{
var user = _context.Users.FirstOrDefault(u => u.Id == id);
if (user == null)
{
return NotFound();
}


_context.Users.Remove(user);
_context.SaveChanges();


return new NoContentResult();
}
}

Test on PostMan: You will receive token in response.

Pass TokenType and AccessToken in Header in other webservices. enter image description here

Best of Luck! I am just Beginner. I only spent one week to start learning asp.net core.

Just to update on the excellent answer by @alerya I had to modify the helper class to look like this;

public static class IHttpContextAccessorExtension
{
public static string CurrentUser(this IHttpContextAccessor httpContextAccessor)
{
var userId = httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return userId;
}
}

Then I could obtain the userId in my service layer. I know it's easy in the controller, but a challenge further down.