基于令牌的ASP认证.. NET Core(已刷新)

本文关键字:NET Core 刷新 认证 于令牌 令牌 ASP | 更新日期: 2023-09-27 17:51:09

我正在与ASP合作。. NET Core应用程序。我正在尝试实现基于令牌的身份验证,但不知道如何使用新的安全系统。

我的场景:客户端请求令牌。我的服务器应该授权用户并返回access_token,这将被客户端在后续请求中使用。

这里有两篇关于实现我所需要的东西的好文章:

    基于令牌的ASP认证. NET Web API 2、Owin和Identity
  • 使用JSON Web令牌

问题是-对我来说,如何在ASP中做同样的事情并不明显。网络核心。

我的问题是:如何配置ASP。. NET Core Web Api应用程序与基于令牌的身份验证工作?我应该追求什么方向?你有没有写过关于最新版本的文章,或者知道我在哪里可以找到?

谢谢!

基于令牌的ASP认证.. NET Core(已刷新)

根据Matt Dekrey的精彩回答,我创建了一个基于令牌的身份验证的完整工作示例。. NET Core (1.0.1)您可以在GitHub上的这个存储库中找到完整的代码(1.0.0-rc1, beta8, beta7的替代分支),但简而言之,重要的步骤是:

为应用程序生成一个密钥

在我的例子中,我在每次应用程序启动时生成一个随机密钥,您需要生成一个并将其存储在某个地方并将其提供给应用程序。请参阅这个文件,了解我如何生成一个随机密钥,以及如何从.json文件导入它。正如@kspearrin在评论中所建议的那样,数据保护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 - Configure

这里,我们需要配置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)
    }
});

TokenController

在令牌控制器中,您需要有一个方法来使用在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错误,则需要注册一个自定义异常处理程序,就像我在这里的示例中所做的那样。

这实际上是我的另一个答案的重复,我倾向于保持更新,因为它得到了更多的关注。评论也可能对你有用!

为。net Core 2更新:

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

  1. 创建一些我们稍后将使用的常量;我是这样做的:

    const string TokenAudience = "Myself";
    const string TokenIssuer = "MyProject";
    
  2. 将此添加到Startup.cs的ConfigureServices中。稍后我们将使用依赖注入来访问这些设置。我假设您的authenticationConfigurationConfigurationSectionConfiguration对象,这样您就可以为调试和生产提供不同的配置。确保您安全地存储您的密钥!可以是任意字符串

    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")]的承载令牌作为身份验证。

    services.AddAuthorization(auth =>
    {
        auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
            .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType)
            .RequireAuthenticatedUser().Build());
    });
    
  5. 棘手的部分来了:构建令牌。

    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页面的局部视图中呈现此内容,并结合。net 4.5中的仅承载身份验证,你现在可以使用ViewComponent来做同样的事情。这与上面的Controller Action代码基本相同

要实现您所描述的,您将需要OAuth2/OpenID Connect授权服务器和验证API访问令牌的中间件。武士刀曾经提供一个OAuthAuthorizationServerMiddleware,但它不再存在于ASP。网络核心。

我建议看一下AspNet.Security.OpenIdConnect。Server, OAuth2授权服务器中间件的一个实验性分支,你提到的教程使用了它:有一个OWIN/Katana 3版本,和一个ASP。. NET核心版本,支持net451(。.NET Desktop)和netstandard1.4(兼容.NET Core)。

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

不要错过MVC Core示例,该示例展示了如何使用AspNet.Security.OpenIdConnect配置OpenID连接授权服务器。服务器以及如何验证由服务器中间件发出的加密访问令牌:https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/blob/dev/samples/Mvc/Mvc.Server/Startup.cs

您也可以阅读这篇博客文章,它解释了如何实现资源所有者密码授予,这是OAuth2相当于基本身份验证:http://kevinchalet.com/2016/07/13/creating-your-own-openid-connect-server-with-asos-implementing-the-resource-owner-password-credentials-grant/

Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication();
    }
    public void Configure(IApplicationBuilder app)
    {
        // Add a new middleware validating the encrypted
        // access tokens issued by the OIDC server.
        app.UseOAuthValidation();
        // Add a new middleware issuing tokens.
        app.UseOpenIdConnectServer(options =>
        {
            options.TokenEndpointPath = "/connect/token";
            // Override OnValidateTokenRequest to skip client authentication.
            options.Provider.OnValidateTokenRequest = context =>
            {
                // Reject the token requests that don't use
                // grant_type=password or grant_type=refresh_token.
                if (!context.Request.IsPasswordGrantType() &&
                    !context.Request.IsRefreshTokenGrantType())
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
                        description: "Only grant_type=password and refresh_token " +
                                     "requests are accepted by this 
                    return Task.FromResult(0);
                }
                // Since there's only one application and since it's a public client
                // (i.e a client that cannot keep its credentials private),
                // call Skip() to inform the server the request should be
                // accepted without enforcing client authentication.
                context.Skip();
                return Task.FromResult(0);
            };
            // Override OnHandleTokenRequest to support
            // grant_type=password token requests.
            options.Provider.OnHandleTokenRequest = context =>
            {
                // Only handle grant_type=password token requests and let the
                // OpenID Connect server middleware handle the other grant types.
                if (context.Request.IsPasswordGrantType())
                {
                    // Do your credentials validation here.
                    // Note: you can call Reject() with a message
                    // to indicate that authentication failed.
                    var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
                    identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique id]");
                    // By default, claims are not serialized
                    // in the access and identity tokens.
                    // Use the overload taking a "destinations"
                    // parameter to make sure your claims
                    // are correctly inserted in the appropriate tokens.
                    identity.AddClaim("urn:customclaim", "value",
                        OpenIdConnectConstants.Destinations.AccessToken,
                        OpenIdConnectConstants.Destinations.IdentityToken);
                    var ticket = new AuthenticationTicket(
                        new ClaimsPrincipal(identity),
                        new AuthenticationProperties(),
                        context.Options.AuthenticationScheme);
                    // Call SetScopes with the list of scopes you want to grant
                    // (specify offline_access to issue a refresh token).
                    ticket.SetScopes("profile", "offline_access");
                    context.Validate(ticket);
                }
                return Task.FromResult(0);
            };
        });
    }
}

project.json

{
  "dependencies": {
    "AspNet.Security.OAuth.Validation": "1.0.0",
    "AspNet.Security.OpenIdConnect.Server": "1.0.0"
  }
}

祝你好运!

您可以使用OpenIddict来提供令牌(登录),然后在访问API/Controller时使用UseJwtBearerAuthentication来验证它们。

这基本上是您在Startup.cs中需要的所有配置:

ConfigureServices:

services.AddIdentity<ApplicationUser, ApplicationRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders()
    // this line is added for OpenIddict to plug in
    .AddOpenIddictCore<Application>(config => config.UseEntityFramework());

app.UseOpenIddictCore(builder =>
{
    // here you 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;
});
// use jwt bearer authentication to validate the tokens
app.UseJwtBearerAuthentication(options =>
{
    options.AutomaticAuthenticate = true;
    options.AutomaticChallenge = true;
    options.RequireHttpsMetadata = false;
    // must match the resource on your token request
    options.Audience = "http://localhost:58292/";
    options.Authority = "http://localhost:58292/";
});

还有一两个其他的小事情,比如你的DbContext需要从OpenIddictContext<ApplicationUser, Application, ApplicationRole, string>派生。

你可以在我的博客上看到一个完整的解释(包括功能的github repo):http://capesean.co.za/blog/asp-net-5-jwt-tokens/

您可以看一下OpenId连接示例,其中演示了如何处理不同的身份验证机制,包括JWT令牌:

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

如果你看一下Cordova后端项目,API的配置是这样的:

app.UseWhen(context => context.Request.Path.StartsWithSegments(new PathString("/api")), 
      branch => {
                branch.UseJwtBearerAuthentication(options => {
                    options.AutomaticAuthenticate = true;
                    options.AutomaticChallenge = true;
                    options.RequireHttpsMetadata = false;
                    options.Audience = "localhost:54540";
                    options.Authority = "localhost:54540";
                });
    });

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

此外,我还使用Aurelia前端框架和ASP实现了一个单页应用程序,其中包含基于令牌的身份验证实现。净的核心。还有一个信号R持久连接。然而,我没有做任何DB实现。代码可以在这里看到:https://github.com/alexandre-spieser/AureliaAspNetCoreAuth

希望有帮助,

,

亚历克斯