ASP.NET 内核中基于令牌的认证

我正在使用 ASP.NET Core 应用程序。我正在尝试实现基于令牌的身份验证,但是不知道如何为我的案例使用新的 保安系统。 我通过 例子,但他们没有帮助我很多,他们使用要么 cookie 认证或外部认证(GitHub,微软,Twitter)。

我的场景是: angularjs 应用程序应该请求传递用户名和密码的 /token URL。WebApi 应该授权用户并返回将被 angularjs 应用程序在以下请求中使用的 access_token

我发现了一篇很棒的文章,介绍了在当前版本的 ASP.NET-使用 ASP.NET Web API 2、 Owin 和 Identity 的基于令牌的身份验证中实现我所需要的东西。但是对于我来说,如何在 ASP.NET Core 中做同样的事情并不明显。

我的问题是: 如何配置 ASP.NET Core WebApi 应用程序以使用基于令牌的身份验证?

89850 次浏览

.Net Core 3.1的更新:

David Fowler (ASP.NET 核心团队)已经整合了一套难以置信的简单任务应用程序,包括一个 演示 JWT 的简单应用程序。我将很快把他的更新和简单化的风格融入到这篇文章中。

更新于.Net Core 2:

这个答案的早期版本使用了 RSA; 如果生成令牌的代码也在验证令牌,那么就没有必要使用 RSA。但是,如果您要分配责任,那么您可能仍然希望使用 Microsoft.IdentityModel.Tokens.RsaSecurityKey的实例执行此操作。

  1. 创建一些我们稍后将要使用的常量; 下面是我所做的:

    const string TokenAudience = "Myself";
    const string TokenIssuer = "MyProject";
    
  2. Add this to your Startup.cs's ConfigureServices. We'll use dependency injection later to access these settings. I'm assuming that your authenticationConfiguration is a ConfigurationSection or Configuration object such that you can have a different config for debug and production. Make sure you store your key securely! It can be any string.

    var keySecret = authenticationConfiguration["JwtSigningKey"];
    var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret));
    
    
    services.AddTransient(_ => new JwtSignInHandler(symmetricKey));
    
    
    services.AddAuthentication(options =>
    {
    // This causes the default authentication scheme to be JWT.
    // Without this, the Authorization header is not checked and
    // you'll get no results. However, this also means that if
    // you're already using cookies in your app, they won't be
    // checked by default.
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
    options.TokenValidationParameters.ValidateIssuerSigningKey = true;
    options.TokenValidationParameters.IssuerSigningKey = symmetricKey;
    options.TokenValidationParameters.ValidAudience = JwtSignInHandler.TokenAudience;
    options.TokenValidationParameters.ValidIssuer = JwtSignInHandler.TokenIssuer;
    });
    

    我已经看到其他答案改变了其他设置,比如 ClockSkew; 默认设置应该适用于时钟不完全同步的分布式环境。这些是您需要更改的唯一设置。

  3. 设置认证。你应该在任何需要你的 User信息的中间件(如 app.UseMvc())之前设置这一行。

    app.UseAuthentication();
    

    注意,这不会导致令牌与 SignInManager或其他任何东西一起发出。您需要提供您自己的输出 JWT 的机制-见下文。

  4. 您可能需要指定一个 AuthorizationPolicy。这将允许您指定只允许使用 [Authorize("Bearer")]作为身份验证的 Bearer 令牌的控制器和操作。

    services.AddAuthorization(auth =>
    {
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
    .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType)
    .RequireAuthenticatedUser().Build());
    });
    
  5. Here comes the tricky part: building the token.

    class JwtSignInHandler
    {
    public const string TokenAudience = "Myself";
    public const string TokenIssuer = "MyProject";
    private readonly SymmetricSecurityKey key;
    
    
    public JwtSignInHandler(SymmetricSecurityKey symmetricKey)
    {
    this.key = symmetricKey;
    }
    
    
    public string BuildJwt(ClaimsPrincipal principal)
    {
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
    
    var token = new JwtSecurityToken(
    issuer: TokenIssuer,
    audience: TokenAudience,
    claims: principal.Claims,
    expires: DateTime.Now.AddMinutes(20),
    signingCredentials: creds
    );
    
    
    return new JwtSecurityTokenHandler().WriteToken(token);
    }
    }
    

    然后,在您的控制器中,您希望在其中放置令牌,如下所示:

    [HttpPost]
    public string AnonymousSignIn([FromServices] JwtSignInHandler tokenFactory)
    {
    var principal = new System.Security.Claims.ClaimsPrincipal(new[]
    {
    new System.Security.Claims.ClaimsIdentity(new[]
    {
    new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Demo User")
    })
    });
    return tokenFactory.BuildJwt(principal);
    }
    

    我猜你已经有校长了吧。如果使用 Identity,则可以使用 IUserClaimsPrincipalFactory<>User转换为 ClaimsPrincipal

  6. 要测试它 : 获取一个令牌,将其放入 Jwt.io的表单中。上面提供的指令还允许您使用配置中的秘密来验证签名!

  7. 如果您在 HTML 页面上的部分视图中呈现此属性,并且在。净值4.5,现在可以使用 ViewComponent来做同样的事情。它与上面的 Controller Action 代码基本相同。

Matt Dekrey 的绝妙回答开始,我创建了一个完整的基于令牌的身份验证示例,使用 ASP.NET Core (1.0.1)。您可以找到完整的代码 在 GitHub 上的这个仓库中(1.0.0-rc1Beta 8Beta 7的替代分支) ,但是简而言之,重要的步骤是:

为应用程序生成密钥

在我的示例中,每次应用程序启动时,我都会生成一个随机密钥,您需要生成一个随机密钥并将其存储在某个地方,然后将其提供给您的应用程序。查看这个文件,了解我如何生成一个随机密钥,以及如何从.json 文件导入它.正如@kpirrin 在评论中建议的那样,数据保护 API似乎是“正确”管理按键的理想候选者,但我还没有弄清楚这是否可行。请提交一个拉请求,如果你的工作了!

Startup.cs-ConfigureServices

在这里,我们需要加载一个私钥,用于对令牌进行签名,我们还将使用该私钥来验证令牌所呈现的内容。我们将密钥存储在类级变量 key中,我们将在下面的 Configure 方法中重用它。TokenAuthOptions是一个简单的类,它保存着我们在 TokenController 中创建密钥所需的签名标识、访问者和发行者。

// Replace this with some sort of loading from config / file.
RSAParameters keyParams = RSAKeyUtils.GetRandomKey();


// Create the key, and a set of token options to record signing credentials
// using that key, along with the other parameters we will need in the
// token controlller.
key = new RsaSecurityKey(keyParams);
tokenOptions = new TokenAuthOptions()
{
Audience = TokenAudience,
Issuer = TokenIssuer,
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.Sha256Digest)
};


// Save the token options into an instance so they're accessible to the
// controller.
services.AddSingleton<TokenAuthOptions>(tokenOptions);


// Enable the use of an [Authorize("Bearer")] attribute on methods and
// classes to protect.
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
.RequireAuthenticatedUser().Build());
});

我们还设置了一个授权策略,允许我们在希望保护的端点和类上使用 [Authorize("Bearer")]

Startup.cs-配置

这里,我们需要配置 JwtBearerAuthentication:

app.UseJwtBearerAuthentication(new JwtBearerOptions {
TokenValidationParameters = new TokenValidationParameters {
IssuerSigningKey = key,
ValidAudience = tokenOptions.Audience,
ValidIssuer = tokenOptions.Issuer,


// When receiving a token, check that it is still valid.
ValidateLifetime = true,


// This defines the maximum allowable clock skew - i.e.
// provides a tolerance on the token expiry time
// when validating the lifetime. As we're creating the tokens
// locally and validating them on the same machines which
// should have synchronised time, this can be set to zero.
// Where external tokens are used, some leeway here could be
// useful.
ClockSkew = TimeSpan.FromMinutes(0)
}
});

Token 控制器

在令牌控制器中,需要有一个方法来使用加载到 Startup.cs 中的密钥生成签名密钥。我们已经在 Startup 中注册了一个 TokenAuthOptions 实例,因此我们需要在 TokenController 的构造函数中注入该实例:

[Route("api/[controller]")]
public class TokenController : Controller
{
private readonly TokenAuthOptions tokenOptions;


public TokenController(TokenAuthOptions tokenOptions)
{
this.tokenOptions = tokenOptions;
}
...

然后你需要在你的处理器中为登录端点生成一个令牌,在我的例子中,我使用一个用户名和密码来验证那些使用 if 语句的用户名和密码,但是你需要做的关键事情是创建或加载一个基于声明的身份,并为此生成一个令牌:

public class AuthRequest
{
public string username { get; set; }
public string password { get; set; }
}


/// <summary>
/// Request a new token for a given username/password pair.
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
[HttpPost]
public dynamic Post([FromBody] AuthRequest req)
{
// Obviously, at this point you need to validate the username and password against whatever system you wish.
if ((req.username == "TEST" && req.password == "TEST") || (req.username == "TEST2" && req.password == "TEST"))
{
DateTime? expires = DateTime.UtcNow.AddMinutes(2);
var token = GetToken(req.username, expires);
return new { authenticated = true, entityId = 1, token = token, tokenExpires = expires };
}
return new { authenticated = false };
}


private string GetToken(string user, DateTime? expires)
{
var handler = new JwtSecurityTokenHandler();


// Here, you should create or look up an identity for the user which is being authenticated.
// For now, just creating a simple generic identity.
ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user, "TokenAuth"), new[] { new Claim("EntityID", "1", ClaimValueTypes.Integer) });


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

应该就是这样了。只需将 [Authorize("Bearer")]添加到您想要保护的任何方法或类中,如果您试图在没有标记的情况下访问它,就会得到一个错误。如果希望返回401而不是500错误,则需要注册一个自定义异常处理程序 就像我在这里举的例子一样

看一下 OpenIddict-这是一个新项目(在编写本文时) ,它使得在 ASP.NET 5中配置 JWT 令牌的创建和刷新令牌变得很容易。令牌的验证由其他软件处理。

假设您将 IdentityEntity Framework一起使用,最后一行是您要添加到 ConfigureServices方法中的内容:

services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddOpenIddictCore<Application>(config => config.UseEntityFramework());

Configure中,您设置 OpenIddict 来提供 JWT 令牌:

app.UseOpenIddictCore(builder =>
{
// tell openiddict you're wanting to use jwt tokens
builder.Options.UseJwtTokens();
// NOTE: for dev consumption only! for live, this is not encouraged!
builder.Options.AllowInsecureHttp = true;
builder.Options.ApplicationCanDisplayErrors = true;
});

您还可以在 Configure中配置令牌的验证:

// use jwt bearer authentication
app.UseJwtBearerAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.RequireHttpsMetadata = false;
options.Audience = "http://localhost:58292/";
options.Authority = "http://localhost:58292/";
});

还有一两件次要的事情,比如您的 DbContext 需要从 OpenIddicContext 派生。

你可以在这篇博文中看到完整的解释: http://capesean.co.za/blog/asp-net-5-jwt-tokens/

一个功能演示可在: https://github.com/capesean/openiddict-test

您可以查看 OpenId connect 示例,其中演示了如何处理不同的身份验证机制,包括 JWT Token:

Https://github.com/aspnet-contrib/aspnet。安全性。 OpenidConnect。样品

如果你看看 Cordova Backend 项目,API 的配置是这样的:

           // Create a new branch where the registered middleware will be executed only for non API calls.
app.UseWhen(context => !context.Request.Path.StartsWithSegments(new PathString("/api")), branch => {
// Insert a new cookies middleware in the pipeline to store
// the user identity returned by the external identity provider.
branch.UseCookieAuthentication(new CookieAuthenticationOptions {
AutomaticAuthenticate = true,
AutomaticChallenge = true,
AuthenticationScheme = "ServerCookie",
CookieName = CookieAuthenticationDefaults.CookiePrefix + "ServerCookie",
ExpireTimeSpan = TimeSpan.FromMinutes(5),
LoginPath = new PathString("/signin"),
LogoutPath = new PathString("/signout")
});


branch.UseGoogleAuthentication(new GoogleOptions {
ClientId = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com",
ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f"
});


branch.UseTwitterAuthentication(new TwitterOptions {
ConsumerKey = "6XaCTaLbMqfj6ww3zvZ5g",
ConsumerSecret = "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI"
});
});

该项目的/Provider/ authorizationprovider.cs 和 ResourceController 中的逻辑也值得一看;)。

或者,您也可以使用下面的代码来验证令牌(还有一个代码片段可以让它与 signalR 一起工作) :

        // Add a new middleware validating access tokens.
app.UseOAuthValidation(options =>
{
// Automatic authentication must be enabled
// for SignalR to receive the access token.
options.AutomaticAuthenticate = true;


options.Events = new OAuthValidationEvents
{
// Note: for SignalR connections, the default Authorization header does not work,
// because the WebSockets JS API doesn't allow setting custom parameters.
// To work around this limitation, the access token is retrieved from the query string.
OnRetrieveToken = context =>
{
// Note: when the token is missing from the query string,
// context.Token is null and the JWT bearer middleware will
// automatically try to retrieve it from the Authorization header.
context.Token = context.Request.Query["access_token"];


return Task.FromResult(0);
}
};
});

对于发行令牌,您可以像下面这样使用 openId Connect 服务器包:

        // Add a new middleware issuing access tokens.
app.UseOpenIdConnectServer(options =>
{
options.Provider = new AuthenticationProvider();
// Enable the authorization, logout, token and userinfo endpoints.
//options.AuthorizationEndpointPath = "/connect/authorize";
//options.LogoutEndpointPath = "/connect/logout";
options.TokenEndpointPath = "/connect/token";
//options.UserinfoEndpointPath = "/connect/userinfo";


// Note: if you don't explicitly register a signing key, one is automatically generated and
// persisted on the disk. If the key cannot be persisted, an exception is thrown.
//
// On production, using a X.509 certificate stored in the machine store is recommended.
// You can generate a self-signed certificate using Pluralsight's self-cert utility:
// https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip
//
// options.SigningCredentials.AddCertificate("7D2A741FE34CC2C7369237A5F2078988E17A6A75");
//
// Alternatively, you can also store the certificate as an embedded .pfx resource
// directly in this assembly or in a file published alongside this project:
//
// options.SigningCredentials.AddCertificate(
//     assembly: typeof(Startup).GetTypeInfo().Assembly,
//     resource: "Nancy.Server.Certificate.pfx",
//     password: "Owin.Security.OpenIdConnect.Server");


// Note: see AuthorizationController.cs for more
// information concerning ApplicationCanDisplayErrors.
options.ApplicationCanDisplayErrors = true // in dev only ...;
options.AllowInsecureHttp = true // in dev only...;
});

我使用 Aurelia 前端框架和 ASP.NET 核心实现了一个基于令牌的身份验证的单页应用程序。还有一个信号 R 持久连接。但是,我还没有做任何 DB 实现。 这里的代码: Https://github.com/alexandre-spieser/aureliaaspnetcoreauth