在ASP.NET核心基于令牌的认证(刷新)

问题描述 投票:65回答:5

我与ASP.NET应用程序的核心工作。我试图实现基于令牌的认证,但无法弄清楚如何使用新Security System

我的场景:一个客户端请求的令牌。我的服务器应授权用户,并返回其的access_token将通过客户端在以下请求中使用。

这里有究竟执行什么,我需要两个伟大的文章:

问题是 - 这不是很明显,我该怎么做同样的事情在ASP.NET核心。

我的问题是:如何配置ASP.NET核心web API应用程序与基于令牌的认证工作?我应该追求什么方向?你写了关于最新版本的任何条款,或知道在哪里能找到的?

谢谢!

c# authentication asp.net-web-api authorization asp.net-core
5个回答
71
投票

Matt Dekrey's fabulous answer工作,我创建了基于令牌的认证工作的完整示例,对ASP.NET核心(1.0.1)工作。你可以找到完整的代码in this repository on GitHub(用于1.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似乎是“正确的”管理密钥的理想人选,但我从来没有制定出如果可能的话呢。如果你的工作的时候,请提交pull请求!

Startup.cs - ConfigureServices

在这里,我们需要装入我们的令牌的专用密钥与,我们也将使用,因为它们呈现给验证令牌进行签名。我们存储在类级别的关键变量key我们将重新使用在下面的配置方法。 TokenAuthOptions是一个简单的类,它持有的签字认同,观众和发行人,我们需要在T​​okenController创造我们的钥匙。

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

TokenController

在令牌控制器,你需要有使用在Startup.cs加载密钥生成签署密钥的方法。我们已经注册在启动一个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


23
投票

这真是another answer of mine的副本,我倾向于保持更多了最新的,因为它得到更多的关注。评论也可能对你有用!

更新了对.NET核心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或其他任何发射。您需要提供自己的机制,用来输出你的智威汤逊 - 见下文。
  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); } 在这里,我假设你已经有了一个主体。如果您使用的身份,您可以使用IUserClaimsPrincipalFactory<>User转变成一个ClaimsPrincipal
  6. 为了测试它:获取一个道理,把它变成在jwt.io形式。我上面提供的说明还允许您使用秘密从你的配置验证签名!
  7. 如果你是在一个局部视图结合在.NET 4.5中唯一承载认证渲染这段HTML网页上,你现在可以使用ViewComponent做同样的。这主要是与上面相同的控制器操作代码。

4
投票

为了实现你的描述,你需要两个OAuth2用户/ ID连接授权服务器和中间件验证的访问令牌为API。武士刀用来提供一个OAuthAuthorizationServerMiddleware,但它不能在ASP.NET核心不复存在。

我建议有一个外观AspNet.Security.OpenIdConnect.Server,用于由你提到的教程中的OAuth2授权服务器中间件的实验叉:有一个OWIN /武士刀3版本,以及ASP.NET核心版本,同时支持net451(.NET桌面)和netstandard1.4(与.NET核心兼容)。

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

千万不要错过MVC岩心样品,演示如何使用AspNet.Security.OpenIdConnect.Server以及如何验证服务器中间件发出的加密访问令牌来配置ID连接授权服务器: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"
  }
}

祝好运!


3
投票

您可以使用OpenIddict服务令牌(登录),然后使用UseJwtBearerAuthentication来验证他们当API /控制器访问。

这基本上是所有你需要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库):http://capesean.co.za/blog/asp-net-5-jwt-tokens/


2
投票

你可以看看ID连接这说明如何处理不同的身份验证机制,包括智威汤逊令牌样本:

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

如果你看一下科尔多瓦后端项目,对于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也值得拥有看看)。

此外,我已经实现与使用奥里利亚前端框架和ASP.NET核心基于令牌认证实现单页的应用程序。还有一个信号R持久连接。不过,我没有做任何数据库的实现。代码可以在这里看到:https://github.com/alexandre-spieser/AureliaAspNetCoreAuth

希望这可以帮助,

最好,

亚历克斯

© www.soinside.com 2019 - 2024. All rights reserved.