在ASP.NET核心基于令牌身份验证(刷新) [英] Token Based Authentication in ASP.NET Core (refreshed)

查看:1839
本文介绍了在ASP.NET核心基于令牌身份验证(刷新)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的情况:
客户端请求的令​​牌。我的服务器应授权用户和返回的access_token在以下请求将由客户使用。

下面是关于究竟实现两个伟大的文章我需要什么:

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

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

感谢您!


解决方案

  1. 生成只为您的应用程序中的RSA密钥。一个非常基本的例子如下,但有许多关于安全密钥如何在.Net框架处理的信息;我强烈建议你去阅读它的一些的,至少。

     私有静态字符串GenerateRsaKeys()
    {
        的RSACryptoServiceProvider myRSA =新的RSACryptoServiceProvider(2048);
        RSAParameters公钥= myRSA.ExportParameters(真);
        返回myRSA.ToXmlString(includePrivateParameters:真);
    }

    保存此出一个.xml文件,包括它与你的应用程序;我在DLL中嵌入它,因为它是一个小的个人项目我想,应该没有人可以访问我的组装反正,但有很多的原因,这是不是一个好主意,所以我不在这里提供的例子。最终,你必须决定什么是最适合你的项目。

    注:的有人指出, ToXmlString FromXmlString 不可用在.NET中的核心。相反,你可以保存/使用自己加载值 RSAParameters ExportParameters(布尔includePrivateParameters)无效ImportParameters(RSAParameters参数)在一个符合核心路,例如使用JSON


  2. 创建我们将在以后使用的常量;这里就是我所做的:

     常量字符串TokenAudience =我;
    常量字符串TokenIssuer =MyProject的;


  3. 添加到您的Startup.cs的 ConfigureServices 。我们将使用依赖注入后访问这些设置。我要离开了访问RSA XML流;但我假设你可以访问它在变量。

      RsaSecurityKey键;
    使用(VAR的TextReader =新就是System.IO.StreamReader(流))
    {
        的RSACryptoServiceProvider publicAndPrivate =新的RSACryptoServiceProvider();
        publicAndPrivate.FromXmlString(textReader.ReadToEnd());    关键=新RsaSecurityKey(publicAndPrivate.ExportParameters(真));
    }services.AddInstance(新SigningCredentials(钥匙,
      SecurityAlgorithms.RsaSha256Signature,SecurityAlgorithms.Sha256Digest));services.Configure< OAuthBearerAuthenticationOptions>(承载= GT;
    {
        bearer.TokenValidationParameters.IssuerSigningKey =键;
        bearer.TokenValidationParameters.ValidAudience = TokenAudience;
        bearer.TokenValidationParameters.ValidIssuer = TokenIssuer;
    });


  4. 设置承载认证。如果您使用的身份,这样做的的的 UseIdentity 行。请注意,任何第三方认证线,如 UseGoogleAuthentication ,一定要去的之前 UseIdentity 行。你不需要任何 UseCookieAuthentication 如果您使用的身份。

      app.UseOAuthBearerAuthentication();


  5. 您可能需要指定一个 AuthorizationPolicy 。这将允许你指定控制器和行动,只有身份验证通过允许承载标记 [授权(载体)]

      services.ConfigureAuthorization(AUTH =>
    {
        auth.AddPolicy(旗手,新AuthorizationPolicyBuilder()
            .AddAuthenticationTypes(OAuthBearerAuthenticationDefaults.AuthenticationType)
            .RequireAuthenticatedUser()构建());
    });


  6. 下面到了棘手的部分:建筑物的标记。我不打算在这里提供所有我的code,但它应该是足够的重现。 (我有几个不相关的专有正确的事情围绕在我自己的codeBase的这个code)

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

     私人只读OAuthBearerAuthenticationOptions bearerOptions;
    私人只读SigningCredentials signingCredentials;

    然后,在你的 /令牌行动...

      //添加到使用条款:
    使用System.IdentityModel.Tokens.Jwt //;VAR处理器= bearerOptions.SecurityTokenValidators.OfType< JwtSecurityTokenHandler>()
        。第一();
    //这里的身份是你要以用户为验证ClaimsIdentity。
    //如果你喜欢,你可以添加自己的自定义声明它。
    //您可以使用SignInManager如果你使用的身份获得此。
    VAR securityToken = handler.CreateToken(
        发行人:bearerOptions.TokenValidationParameters.ValidIssuer,
        观众:bearerOptions.TokenValidationParameters.ValidAudience,
        signingCredentials:signingCredentials,
        主题:身份);
    VAR令牌= handler.WriteToken(securityToken);

    VAR标记是承载令牌 - 你可以作为一个字符串返回此向用户传递如你所期望的承载认证

    <。 / LI>
  7. 如果你在一个局部视图你的HTML页面上结合的唯一承载的身份验证在.NET 4.5渲染这一点,你现在可以使用 ViewComponent 做同样的。这主要是一样的控制器动作code以上。


I'm working with ASP.NET Core application. I'm trying to implement Token Based Authentication but can not figure out how to use new Security System.

My scenario: A client requests a token. My server should authorize the user and return access_token which will be used by the client in following requests.

Here are two great articles about implementing exactly what I need:

The problem is - it is not obvious for me how to do the same thing in ASP.NET Core.

My question is: how to configure ASP.NET Core Web Api application to work with token based authentication? What direction should I pursue? Have you written any articles about the newest version, or know where I could find ones?

Thank you!

解决方案

  1. Generate an RSA key just for your application. A very basic example is below, but there's lots of information about how security keys are handled in the .Net Framework; I highly recommend that you go read some of it, at least.

    private static string GenerateRsaKeys()
    {
        RSACryptoServiceProvider myRSA = new RSACryptoServiceProvider(2048);
        RSAParameters publicKey = myRSA.ExportParameters(true);
        return myRSA.ToXmlString(includePrivateParameters: true);
    }
    

    Save this out to a .xml file and include it with your application; I embedded it in my DLL because it's a small personal project I figured that no one should get access to my assembly anyway, but there's lots of reasons why this is not a good idea and so I am not providing that example here. Ultimately, you have to decide what is best for your project.

    Note: It was pointed out that the ToXmlString and FromXmlString are not available in .NET Core. Instead, you can save/load the values yourself using RSAParameters ExportParameters(bool includePrivateParameters) and void ImportParameters(RSAParameters parameters) in a Core-compliant way, such as using JSON.

  2. Create a few constants that we'll be using later; here's what I did:

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

  3. Add this to your Startup.cs's ConfigureServices. We'll use dependency injection later to access these settings. I'm leaving out accessing the RSA xml stream; but I'm assuming you have access to it in a stream variable.

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

  4. Set up Bearer Authentication. If you're using Identity, do this before the UseIdentity line. Note that any third-party authentication lines, such as UseGoogleAuthentication, must go before the UseIdentity line. You do not need any UseCookieAuthentication if you are using Identity.

    app.UseOAuthBearerAuthentication();
    

  5. You may want to specify an AuthorizationPolicy. This will allow you to specify controllers and actions that only allow Bearer tokens as authentication using [Authorize("Bearer")].

    services.ConfigureAuthorization(auth =>
    {
        auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
            .AddAuthenticationTypes(OAuthBearerAuthenticationDefaults.AuthenticationType)
            .RequireAuthenticatedUser().Build());
    });
    

  6. Here comes the tricky part: building the token. I'm not going to provide all my code here, but it should be enough to reproduce. (I have a few unrelated proprietary things right around this code in my own codebase.)

    This bit is injected from the constructor; this is why we configured the options above rather than simply passing them to the UseOAuthBearerAuthentication()

    private readonly OAuthBearerAuthenticationOptions bearerOptions;
    private readonly SigningCredentials signingCredentials;
    

    Then, in your /Token action...

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

    The var token is your bearer token - you can return this as a string to the user to pass as you'd expect for Bearer authentication.

  7. If you were rendering this in a partial view on your HTML page in combination with the bearer-only authentication in .Net 4.5, you can now use a ViewComponent to do the same. It's mostly the same as the Controller Action code above.

这篇关于在ASP.NET核心基于令牌身份验证(刷新)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆