JWT Authentication in ASP.NET 5 Using OAuthBearerAuthentication

I am working on an ASP.NET 5 application and I would like to use JWT to protect certain endpoints in the application. So far, we have decided that we (unlike a third party) will release JWT, since all our clients are “owned” by the application, that is, we do not have “external” clients. In the example, I have an endpoint that creates and returns JWT using the following jwt-dotnet library (I appreciate that it is basic, for example, without expiration and one application, etc.):

...
// include a single subject claim (user id)
var claims = new Dictionary<string, object>() { { "sub", "1234" } };
var key = "EXAMPLE_SECRET_KEY_TO_SIGN_JWT";
var token = JWT.JsonWebToken.Encode(claims, key, JWT.JwtHashAlgorithm.HS256);
...
// return JWT

I can encode and decode this JWT using the same key as would be expected. In my Startup.cs file, I use Microsoft.AspNet.Authentication.OAuthBearer middleware to authorize the corresponding routes in my controllers that have the [Authorize] attribute. However, after looking at a few posts, including here and here , I cannot find an example of how to supply this signature key in the same way to the OAuth middleware. The code in my Startup.cs file is as follows:

public class Startup
{
    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        app.UseErrorPage();
        app.UseOAuthBearerAuthentication();
        app.UseMvc();
    }

    ...

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<OAuthBearerAuthenticationOptions>(bearer =>
        {
            bearer.AutomaticAuthentication = true;
            bearer.TokenValidationParameters.ValidAudience = "Example audience";
            bearer.TokenValidationParameters.ValidIssuer = "Example issuer";
            bearer.TokenValidationParameters.ValidateAudience = true;
            bearer.TokenValidationParameters.ValidateIssuer = true;
            bearer.TokenValidationParameters... // how do I set the signing key as a string literal?
        });
        services.AddMvc();
    }
}

, , . , , , RSA, / .

, , , - , , , !

+4
1

EDIT: RC2:

var key = Convert.FromBase64String("base64-encoded symmetric key");

app.UseJwtBearerAuthentication(options => {
    options.AutomaticAuthenticate = true;
    options.AutomaticChallenge = true;

    options.Authority = Configuration["jwt:authority"];
    options.Audience = Configuration["jwt:audience"];

    options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(key);
});

, , - : - OAuth2 IdentityModel 5, , , .

, (https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/250), , (, RSA ).

(. https://gist.github.com/sandorfr/4039d540b6b552154522), RSA .

+2

Source: https://habr.com/ru/post/1609784/


All Articles