ChatGPT解决这个技术问题 Extra ChatGPT

ASP.NET Core 中基于令牌的身份验证

我正在使用 ASP.NET Core 应用程序。我正在尝试实施基于令牌的身份验证,但无法弄清楚如何为我的案例使用新的 Security System。我经历了examples,但他们对我帮助不大,他们使用的是 cookie 身份验证或外部身份验证(GitHub、Microsoft、Twitter)。

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

我找到了关于在当前版本的 ASP.NET - Token Based Authentication using ASP.NET Web API 2, Owin, and Identity 中实现我所需要的内容的好文章。但对我来说如何在 ASP.NET Core 中做同样的事情并不明显。

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


M
Matt DeKrey

.Net Core 3.1 更新:

David Fowler(ASP .NET Core 团队的架构师)组合了一组非常简单的任务应用程序,包括 simple application demonstrating JWT。我将很快将他的更新和简单的风格融入这篇文章。

为 .Net Core 2 更新:

此答案的先前版本使用 RSA;如果生成令牌的相同代码也在验证令牌,那真的没有必要。但是,如果您要分配责任,您可能仍希望使用 Microsoft.IdentityModel.Tokens.RsaSecurityKey 的实例来执行此操作。

创建一些我们稍后将使用的常量;这就是我所做的: const string TokenAudience = "Myself";常量字符串 TokenIssuer = "我的项目";将此添加到您的 Startup.cs 的 ConfigureServices。稍后我们将使用依赖注入来访问这些设置。我假设您的 authenticationConfiguration 是一个 ConfigurationSection 或 Configuration 对象,这样您就可以为调试和生产使用不同的配置。确保安全地存储您的密钥!它可以是任何字符串。 var keySecret = authenticationConfiguration["JwtSigningKey"]; var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret)); services.AddTransient(_ => new JwtSignInHandler(symmetricKey)); services.AddAuthentication(options => { // 这会导致默认身份验证方案为 JWT。 // 没有这个,Authorization 标头不会被检查并且 // 你不会得到任何结果。然而,这也意味着如果 //您已经在您的应用程序中使用 cookie,默认情况下不会检查它们。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;默认设置使其适用于时钟不完全同步的分布式环境。这些是您需要更改的唯一设置。设置身份验证。在任何需要您的用户信息的中间件(例如 app.UseMvc())之前,您应该有此行。 app.UseAuthentication();请注意,这不会导致您的令牌与 SignInManager 或其他任何东西一起发出。您需要提供自己的机制来输出 JWT - 见下文。您可能需要指定 AuthorizationPolicy。这将允许您使用 [Authorize("Bearer")] 指定仅允许承载令牌作为身份验证的控制器和操作。 services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType) .RequireAuthenticatedUser().Build()); });棘手的部分来了:构建令牌。类 JwtSignInHandler { public const string TokenAudience = "Myself";公共常量字符串 TokenIssuer = "MyProject";私有只读 SymmetricSecurityKey 密钥;公共 JwtSignInHandler(SymmetricSecurityKey symmetricKey) { this.key = symmetricKey; } 公共字符串 BuildJwt(ClaimsPrincipal principal) { var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(发行者:TokenIssuer,受众:TokenAudience,声明:principal.Claims,过期:DateTime.Now.AddMinutes(20),signingCredentials:creds);返回新的 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") }) });返回 tokenFactory.BuildJwt(principal); } 在这里,我假设您已经有一个委托人。如果您使用 Identity,则可以使用 IUserClaimsPrincipalFactory<> 将您的 User 转换为 ClaimsPrincipal。测试它:获取一个令牌,将其放入 jwt.io 的表单中。我上面提供的说明还允许您使用配置中的秘密来验证签名!如果您在 HTML 页面的部分视图中呈现此内容并结合 .Net 4.5 中的仅持有者身份验证,您现在可以使用 ViewComponent 来执行相同的操作。它与上面的控制器动作代码基本相同。


您需要实际注入 IOptions<OAuthBearerAuthenticationOptions> 才能使用选项;由于选项模型框架支持的命名配置,不支持直接使用选项对象。
更新到我正在使用的内容,尽管现在答案应该被重写。谢谢你戳我!
在 Microsoft.AspNet.Authentication.OAuthBearer - beta 5 - 6 和可能更早的 beta 版本中,#5 已更改为以下内容,但尚未确认。 auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(OAuthBearerAuthenticationDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build());
@MattDeKrey 我已将此答案用作基于简单令牌的身份验证示例的起点,并将其更新为适用于 beta 7 - 请参阅 github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample - 还包含这些评论中的一些指针。
Updated again for RC1 - Beta7Beta8 的旧版本在 GitHub 上的分支中可用。
C
Community

Matt Dekrey's fabulous answer 开始,我创建了一个基于令牌的身份验证的完整工作示例,针对 ASP.NET Core (1.0.1)。您可以找到完整的代码 in this repository on GitHub1.0.0-rc1beta8beta7 的替代分支),但简而言之,重要的步骤是:

为您的应用程序生成密钥

在我的示例中,每次应用程序启动时我都会生成一个随机密钥,您需要生成一个并将其存储在某处并将其提供给您的应用程序。 See this file for how I'm generating a random key and how you might import it from a .json file。正如@kspearrin 在评论中所建议的那样,Data Protection API 似乎是“正确”管理密钥的理想候选者,但我还没有弄清楚这是否可能。如果你解决了,请提交一个拉取请求!

Startup.cs - 配置服务

在这里,我们需要为要签名的令牌加载一个私钥,我们还将使用它来验证令牌的出现。我们将密钥存储在类级变量 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)
    }
});

令牌控制器

在令牌控制器中,您需要有一种方法来使用在 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 错误,则需要注册自定义异常处理程序 as I have in my example here


这是一个非常棒的例子,包括了我需要让@MattDeKrey 的例子工作的所有缺失的部分,非常感谢!请注意,仍然以 beta7 而不是 beta8 为目标的任何人仍然可以在 github history
您是否必须使用自己手动生成的签名密钥?有什么方法可以直接利用数据保护库已经生成和管理的密钥?这不是 cookie 身份验证令牌的工作方式吗?
谢谢你,但是我不太明白为什么在 ASP.Net 4 Web API 中开箱即用的东西现在需要在 ASP.Net 5 中进行相当多的配置。似乎是倒退了一步。
我认为他们真的在推动 ASP.NET 5 的“社交身份验证”,我想这有点道理,但是有些应用程序不适合,所以我不确定我是否同意他们的方向 @JMK
为 dotnet core 1.0.1 更新,任何感兴趣的人都可以使用。
P
Pang

您可以查看 OpenId 连接示例,这些示例说明了如何处理不同的身份验证机制,包括 JWT 令牌:

https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Samples

如果您查看 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"
            });
        });

/Providers/AuthorizationProvider.cs 中的逻辑和该项目的 RessourceController 也值得一看;)。

或者,您也可以使用以下代码来验证令牌(还有一个片段可以使其与 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持久连接。但是,我还没有完成任何数据库实现。此处代码:https://github.com/alexandre-spieser/AureliaAspNetCoreAuth


S
Sean

看看 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 需要从 OpenIddictContext 派生。

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

可在以下位置获得功能演示:https://github.com/capesean/openiddict-test