首页 文章

ASP.NET核心中基于令牌的身份验证(刷新)

提问于
浏览
60

我'm working with ASP.NET Core application. I' m试图实现基于令牌的身份验证,但无法弄清楚如何使用新的Security System .

My scenario: 客户端请求令牌 . 我的服务器应该授权用户并返回access_token,客户端将在以下请求中使用该access_token .

这里有两篇关于正确实现我需要的文章:

问题是 - 对我来说,如何在ASP.NET Core中做同样的事情并不明显 .

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

谢谢!

5 回答

  • 66

    要实现您描述的内容,您需要OAuth2 / OpenID Connect授权服务器和验证API访问令牌的中间件 . Katana曾经提供 OAuthAuthorizationServerMiddleware ,但它在ASP.NET Core中不再存在 .

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

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

    不要错过MVC Core示例,该示例演示了如何使用 AspNet.Security.OpenIdConnect.Server 配置OpenID Connect授权服务器以及如何验证服务器中间件发出的加密访问令牌: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"
      }
    }
    

    祝好运!

  • 21

    您可以查看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中的逻辑和该项目的RessourceController也值得一看;) .

    此外,我使用Aurelia前端框架和ASP.NET核心实现了一个基于令牌的身份验证实现的单页面应用程序 . 还有一个信号R持久连接 . 但是我没有做过任何数据库实现 . 代码可以在这里看到:https://github.com/alexandre-spieser/AureliaAspNetCoreAuth

    希望这可以帮助,

    最好,

    亚历克斯

  • 3

    您可以使用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());
    

    Configure

    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/

  • 2
    • 仅为您的应用程序生成RSA密钥 . 下面是一个非常基本的示例,但是有很多关于如何在.Net Framework中处理安全密钥的信息 . 至少我强烈推荐你go read some of it .
    private static string GenerateRsaKeys()
    {
        RSACryptoServiceProvider myRSA = new RSACryptoServiceProvider(2048);
        RSAParameters publicKey = myRSA.ExportParameters(true);
        return myRSA.ToXmlString(includePrivateParameters: true);
    }
    

    将其保存为.xml文件并将其包含在您的应用程序中;我将它嵌入到我的DLL中,因为它是一个小型的个人项目,我认为无论如何都没有人可以访问我的程序集,但是有很多理由说明为什么这不是一个好主意,所以我不在这里提供这个例子 . 最终,您必须决定什么是最适合您的项目 .

    注意:有人指出 ToXmlStringFromXmlString 在.NET Core中不可用 . 相反,您可以使用 RSAParameters ExportParameters(bool includePrivateParameters)void ImportParameters(RSAParameters parameters) 以符合Core的方式自行保存/加载值,例如使用JSON .

    • 创建一些我们稍后将使用的常量;这是我做的:
    const string TokenAudience = "Myself";
    const string TokenIssuer = "MyProject";
    
    • 将此添加到Startup.cs的 ConfigureServices . 我们'll use dependency injection later to access these settings. I'米离开了访问RSA xml流;但我假设您可以在 stream 变量中访问它 .
    RsaSecurityKey key;
    using (var textReader = new System.IO.StreamReader(stream))
    {
        RSACryptoServiceProvider publicAndPrivate = new RSACryptoServiceProvider();
        publicAndPrivate.FromXmlString(textReader.ReadToEnd());
    
        key = new RsaSecurityKey(publicAndPrivate.ExportParameters(true));
    }
    
    services.AddInstance(new SigningCredentials(key, 
      SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest));
    
    services.Configure<OAuthBearerAuthenticationOptions>(bearer =>
    {
        bearer.TokenValidationParameters.IssuerSigningKey = key;
        bearer.TokenValidationParameters.ValidAudience = TokenAudience;
        bearer.TokenValidationParameters.ValidIssuer = TokenIssuer;
    });
    
    • 设置承载认证 . 如果您正在使用Identity,请在 UseIdentity 行之前执行此操作 . 请注意,任何第三方身份验证行(例如 UseGoogleAuthentication )都必须 UseIdentityUseIdentity 行 . 如果您使用Identity,则不需要任何 UseCookieAuthentication .
    app.UseOAuthBearerAuthentication();
    
    • 您可能想要指定 AuthorizationPolicy . 这将允许您指定仅允许使用 [Authorize("Bearer")] 进行身份验证的承载令牌的控制器和操作 .
    services.ConfigureAuthorization(auth =>
    {
        auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
            .AddAuthenticationTypes(OAuthBearerAuthenticationDefaults.AuthenticationType)
            .RequireAuthenticatedUser().Build());
    });
    
    • 这里有一个棘手的部分:构建令牌 . 我不会在这里提供我的所有代码,但它应该足以重现 . (在我自己的代码库中,我在这段代码中有一些不相关的专有内容 . )

    这个位是从构造函数注入的;这就是为什么我们配置上面的选项而不是简单地将它们传递给UseOAuthBearerAuthentication()

    private readonly OAuthBearerAuthenticationOptions bearerOptions;
    private readonly SigningCredentials signingCredentials;
    

    然后,在你的 /Token 行动......

    // add to using clauses:
    // using System.IdentityModel.Tokens.Jwt;
    
    var handler = bearerOptions.SecurityTokenValidators.OfType<JwtSecurityTokenHandler>()
        .First();
    // The identity here is the ClaimsIdentity you want to authenticate the user as. 
    // You can add your own custom claims to it if you like.
    // You can get this using the SignInManager if you're using Identity.
    var securityToken = handler.CreateToken(
        issuer: bearerOptions.TokenValidationParameters.ValidIssuer, 
        audience: bearerOptions.TokenValidationParameters.ValidAudience, 
        signingCredentials: signingCredentials,
        subject: identity);
    var token = handler.WriteToken(securityToken);
    

    var token 是您的持票人令牌 - 您可以将此字符串作为字符串返回给用户,以便按照您对Bearer的期望传递认证 .

    • 如果您在HTML页面上的部分视图中与.Net 4.5中的仅承载身份验证一起呈现此内容,您现在可以使用 ViewComponent 执行相同操作 . 它与上面的Controller Action代码大致相同 .
  • 4

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

    Generate a key for your application

    在我的示例中,每次应用程序启动时,我都会生成一个随机密钥,您需要生成一个并将其存储在某个位置并将其提供给您的应用程序 . 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似乎是管理密钥"correctly"的理想候选者,但我还是可能的've not worked out if that' . 如果您解决了,请提交拉取请求!

    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());
    });
    

    我们还设置了授权策略,允许我们在我们希望保护的 endpoints 和类上使用 [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;
        }
    ...
    

    然后,您需要在处理程序中为登录 endpoints 生成令牌,在我的示例中,我使用用户名和密码并使用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 .

相关问题