Token Based Authentication in ASP.NET Core

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 for my case. I went through examples but they didn't help me much, they are using either cookie authentication or external authentication (GitHub, Microsoft, Twitter).

What my scenario is: angularjs application should request /token url passing username and password. WebApi should authorize user and return access_token which will be used by angularjs app in following requests.

I've found great article about implementing exactly what I need in current version of ASP.NET - Token Based Authentication using ASP.NET Web API 2, Owin, and Identity. But 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 WebApi application to work with token based authentication?


Updated for .Net Core 2:

Previous versions of this answer used RSA; it's really not necessary if your same code that is generating the tokens is also verifying the tokens. However, if you're distributing the responsibility, you probably still want to do this using an instance of Microsoft.IdentityModel.Tokens.RsaSecurityKey .

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

    const string TokenAudience = "Myself";
    const string TokenIssuer = "MyProject";
    
  • Add this to your Startup.cs's ConfigureServices . We'll use dependency injection later to access these settings. I'm assuming that your authenticationConfiguration is a ConfigurationSection or Configuration object such that you can have a different config for debug and production. Make sure you store your key securely! It can be any string.

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

    I've seen other answers change other settings, such as ClockSkew ; the defaults are set such that it should work for distributed environments whose clocks aren't exactly in sync. These are the only settings you need to change.

  • Set up Authentication. You should have this line before any middleware that requires your User info, such as app.UseMvc() .

    app.UseAuthentication();
    

    Note that this will not cause your token to be emitted with the SignInManager or anything else. You will need to provide your own mechanism for outputting your JWT - see below.

  • 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.AddAuthorization(auth =>
    {
        auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
            .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType)
            .RequireAuthenticatedUser().Build());
    });
    
  • Here comes the tricky part: building the token.

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

    Then, in your controller where you want your token, something like the following:

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

    Here, I'm assuming you already have a principal. If you are using Identity, you can use IUserClaimsPrincipalFactory<> to transform your User into a ClaimsPrincipal .

  • To test it : Get a token, put it into the form at jwt.io. The instructions I provided above also allow you to use the secret from your config to validate the signature!

  • 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.


  • Working from Matt Dekrey's fabulous answer, I've created a fully working example of token-based authentication, working against ASP.NET Core (1.0.1). You can find the full code in this repository on GitHub (alternative branches for 1.0.0-rc1, beta8, beta7), but in brief, the important steps are:

    Generate a key for your application

    In my example, I generate a random key each time the app starts, you'll need to generate one and store it somewhere and provide it to your application. See this file for how I'm generating a random key and how you might import it from a .json file. As suggested in the comments by @kspearrin, the Data Protection API seems like an ideal candidate for managing the keys "correctly", but I've not worked out if that's possible yet. Please submit a pull request if you work it out!

    Startup.cs - ConfigureServices

    Here, we need to load a private key for our tokens to be signed with, which we will also use to verify tokens as they are presented. We're storing the key in a class-level variable key which we'll re-use in the Configure method below. TokenAuthOptions is a simple class which holds the signing identity, audience and issuer that we'll need in the TokenController to create our keys.

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

    We've also set up an authorization policy to allow us to use [Authorize("Bearer")] on the endpoints and classes we wish to protect.

    Startup.cs - Configure

    Here, we need to configure the 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

    In the token controller, you need to have a method to generate signed keys using the key that was loaded in Startup.cs. We've registered a TokenAuthOptions instance in Startup, so we need to inject that in the constructor for TokenController:

    [Route("api/[controller]")]
    public class TokenController : Controller
    {
        private readonly TokenAuthOptions tokenOptions;
    
        public TokenController(TokenAuthOptions tokenOptions)
        {
            this.tokenOptions = tokenOptions;
        }
    ...
    

    Then you'll need to generate the token in your handler for the login endpoint, in my example I'm taking a username and password and validating those using an if statement, but the key thing you need to do is create or load a claims-based identity and generate the token for that:

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

    And that should be it. Just add [Authorize("Bearer")] to any method or class you want to protect, and you should get an error if you attempt to access it without a token present. If you want to return a 401 instead of a 500 error, you'll need to register a custom exception handler as I have in my example here.


    You can have a look at the OpenId connect samples which illustrate how to deal with different authentication mechanisms, including JWT Tokens:

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

    If you look at the Cordova Backend project, the configuration for the API is like so:

               // Create a new branch where the registered middleware will be executed only for non API calls.
            app.UseWhen(context => !context.Request.Path.StartsWithSegments(new PathString("/api")), branch => {
                // Insert a new cookies middleware in the pipeline to store
                // the user identity returned by the external identity provider.
                branch.UseCookieAuthentication(new CookieAuthenticationOptions {
                    AutomaticAuthenticate = true,
                    AutomaticChallenge = true,
                    AuthenticationScheme = "ServerCookie",
                    CookieName = CookieAuthenticationDefaults.CookiePrefix + "ServerCookie",
                    ExpireTimeSpan = TimeSpan.FromMinutes(5),
                    LoginPath = new PathString("/signin"),
                    LogoutPath = new PathString("/signout")
                });
    
                branch.UseGoogleAuthentication(new GoogleOptions {
                    ClientId = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com",
                    ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f"
                });
    
                branch.UseTwitterAuthentication(new TwitterOptions {
                    ConsumerKey = "6XaCTaLbMqfj6ww3zvZ5g",
                    ConsumerSecret = "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI"
                });
            });
    

    The logic in /Providers/AuthorizationProvider.cs and the RessourceController of that project are also worth having a look at ;).

    Alternatively you can also use the following code to validate tokens (there is also a snippet to make it work with signalR):

            // Add a new middleware validating access tokens.
            app.UseOAuthValidation(options =>
            {
                // Automatic authentication must be enabled
                // for SignalR to receive the access token.
                options.AutomaticAuthenticate = true;
    
                options.Events = new OAuthValidationEvents
                {
                    // Note: for SignalR connections, the default Authorization header does not work,
                    // because the WebSockets JS API doesn't allow setting custom parameters.
                    // To work around this limitation, the access token is retrieved from the query string.
                    OnRetrieveToken = context =>
                    {
                        // Note: when the token is missing from the query string,
                        // context.Token is null and the JWT bearer middleware will
                        // automatically try to retrieve it from the Authorization header.
                        context.Token = context.Request.Query["access_token"];
    
                        return Task.FromResult(0);
                    }
                };
            });
    

    For issuing token you can use the openId Connect server packages like so:

            // Add a new middleware issuing access tokens.
            app.UseOpenIdConnectServer(options =>
            {
                options.Provider = new AuthenticationProvider();
                // Enable the authorization, logout, token and userinfo endpoints.
                //options.AuthorizationEndpointPath = "/connect/authorize";
                //options.LogoutEndpointPath = "/connect/logout";
                options.TokenEndpointPath = "/connect/token";
                //options.UserinfoEndpointPath = "/connect/userinfo";
    
                // Note: if you don't explicitly register a signing key, one is automatically generated and
                // persisted on the disk. If the key cannot be persisted, an exception is thrown.
                // 
                // On production, using a X.509 certificate stored in the machine store is recommended.
                // You can generate a self-signed certificate using Pluralsight's self-cert utility:
                // https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip
                // 
                // options.SigningCredentials.AddCertificate("7D2A741FE34CC2C7369237A5F2078988E17A6A75");
                // 
                // Alternatively, you can also store the certificate as an embedded .pfx resource
                // directly in this assembly or in a file published alongside this project:
                // 
                // options.SigningCredentials.AddCertificate(
                //     assembly: typeof(Startup).GetTypeInfo().Assembly,
                //     resource: "Nancy.Server.Certificate.pfx",
                //     password: "Owin.Security.OpenIdConnect.Server");
    
                // Note: see AuthorizationController.cs for more
                // information concerning ApplicationCanDisplayErrors.
                options.ApplicationCanDisplayErrors = true // in dev only ...;
                options.AllowInsecureHttp = true // in dev only...;
            });
    

    EDIT: I have implemented a single page application with token based authentication implementation using the Aurelia front end framework and ASP.NET core. There is also a signal R persistent connection. However I have not done any DB implementation. Code can be seen here: https://github.com/alexandre-spieser/AureliaAspNetCoreAuth

    Hope this helps,

    Best,

    Alex

    链接地址: http://www.djcxy.com/p/508.html

    上一篇: 如何检查列表是否为空?

    下一篇: ASP.NET Core中基于令牌的身份验证