首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >ASP.NET核心中基于令牌的身份验证(刷新)

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

Stack Overflow用户
提问于 2015-05-30 21:03:22
回答 5查看 55K关注 0票数 69

我正在使用ASP.NET核心应用程序。我正在尝试实现基于令牌的身份验证,但不知道如何使用新的Security System

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

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

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

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

谢谢!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2015-10-19 22:42:01

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似乎是“正确”管理密钥的理想候选者,但我还没有弄清楚这是否可能。如果您解决了这个问题,请提交拉取请求!

Startup.cs - ConfigureServices

在这里,我们需要为要签名的令牌加载一个私钥,我们还将使用该私钥来验证呈现的令牌。我们将键存储在一个类级变量key中,我们将在下面的Configure方法中重用该变量。TokenAuthOptions是一个简单的类,它包含我们在TokenController中创建密钥所需的签名身份、受众和颁发者。

代码语言:javascript
复制
// 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:

代码语言:javascript
复制
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的构造函数中:

代码语言:javascript
复制
[Route("api/[controller]")]
public class TokenController : Controller
{
    private readonly TokenAuthOptions tokenOptions;

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

然后,您将需要在您的处理程序中为登录端点生成令牌,在我的示例中,我使用用户名和密码并使用if语句验证它们,但您需要做的关键事情是创建或加载基于声明的身份,并为此生成令牌:

代码语言:javascript
复制
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

票数 73
EN

Stack Overflow用户

发布于 2015-06-08 02:31:08

这实际上是another answer of mine的复制品,我倾向于保持更新,因为它得到了更多的关注。这里的评论也可能对你有用!

针对.Net核心2进行了更新:

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

  1. 创建了几个我们稍后将使用的常量;下面是我所做的:

const string TokenAudience = "Myself";const string TokenIssuer = "MyProject";

  • Add this to your Startup.cs's ConfigureServices。我们稍后将使用依赖注入来访问这些设置。我假设您的authenticationConfiguration是一个ConfigurationSectionConfiguration对象,这样您就可以为调试和生产使用不同的配置。确保您安全地存储您的密钥!它可以是任何字符串。

var keySecret = authenticationConfiguration"JwtSigningKey";var symmetricKey =authenticationConfiguration JwtSigningKey services.AddTransient(_ =>新JwtSignInHandler(symmetricKey));services.AddAuthentication(选项=> { //这将导致默认身份验证方案为JWT。//如果没有此选项,则不会检查Authorization标头,并且//您将得不到任何结果。然而,这也意味着如果//你已经在你的应用程序中使用cookies,//默认情况下它们不会被选中。options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;}) .AddJwtBearer(options => { options.TokenValidationParameters.ValidateIssuerSigningKey =JwtBearerDefaults.AuthenticationScheme;options.TokenValidationParameters.ValidAudience = symmetricKey;options.TokenValidationParameters.ValidAudience=.AddJwtBearer;});

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

  • 设置身份验证。在任何需要您的User信息的中间件(如app.UseMvc() )之前,都应该有这一行。

app.UseAuthentication();

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

  • 你可能想要指定一个AuthorizationPolicy。这将允许您指定控制器和操作,这些控制器和操作仅允许不记名令牌作为使用[Authorize("Bearer")]的身份验证。

services.AddAuthorization(auth => { auth.AddPolicy("Bearer",new AuthorizationPolicyBuilder() =>().Build());});

  • 来了棘手的部分:构建令牌。

类JwtSignInHandler {公有常量字符串TokenAudience =“我自己”;公有常量字符串TokenIssuer = "MyProject";私有只读SymmetricSecurityKey密钥;公有JwtSignInHandler(SymmetricSecurityKey symmetricKey) { this.key = symmetricKey;}公有字符串BuildJwt(ClaimsPrincipal主体){ var creds =新SigningCredentials(key,SecurityAlgorithms.HmacSha256);var JwtSecurityToken=新令牌(颁发者: TokenIssuer,受众: TokenAudience,声明: principal.Claims,过期: DateTime.Now.AddMinutes(20),signingCredentials:凭证);返回新的JwtSecurityTokenHandler().WriteToken( token );}}

然后,在您想要令牌的控制器中,如下所示:

新公有字符串AnonymousSignIn(FromServices JwtSignInHandler tokenFactory) { var System.Security.Claims.ClaimsPrincipal=new[](System.Security.Claims.ClaimsIdentity{new[]{新var“演示用户”) }) });tokenFactory.BuildJwt(tokenFactory.BuildJwt);}

在这里,我假设你已经有了一个校长。如果您使用的是标识,则可以使用IUserClaimsPrincipalFactory<>将您的User转换为测试:获取一个令牌,将其放入jwt.io的形式中。我上面提供的说明还允许您使用配置中的秘密来验证您在HTML页面上的部分视图中呈现的signature!

  • If,结合.Net 4.5中的仅限持有者身份验证,您现在可以使用ViewComponent来做同样的事情。它与上面的控制器操作代码基本相同。
票数 24
EN

Stack Overflow用户

发布于 2015-06-06 01:29:09

要实现您所描述的内容,您将需要一个OAuth2/OpenID Connect授权服务器和一个为API验证访问令牌的中间件。ASP.NET曾经提供过OAuthAuthorizationServerMiddleware,但是现在它已经不存在于Katana核心中了。

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

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

不要错过MVC Core示例,该示例展示了如何使用AspNet.Security.OpenIdConnect.Server配置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

代码语言:javascript
复制
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

代码语言:javascript
复制
{
  "dependencies": {
    "AspNet.Security.OAuth.Validation": "1.0.0",
    "AspNet.Security.OpenIdConnect.Server": "1.0.0"
  }
}

祝好运!

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30546542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档