DavidB
DavidB

Reputation: 2596

Secure API with JWT access token

I am playing around with the openiddict Authorization code flow sample and all is working well.

https://github.com/openiddict/openiddict-samples/tree/dev/samples/CodeFlow

However, I want to make certain changes and I am struggling to do this. I would like to configure to use JWT tokens instead of the default opaque tokens, and also separate into an authorization server and a resource server. I also have an MCV web app that will communicate with the resource server via a httpClient.

Auth Server.Startup

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
                options.UseOpenIddict();
            });

            // Register the Identity services.
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
            });

            services.AddOpenIddict()

                .AddCore(options =>

                    options.UseEntityFrameworkCore()
                           .UseDbContext<ApplicationDbContext>();
                })

                // Register the OpenIddict server handler.
                .AddServer(options =>
                {
                    options.UseMvc();

                    options.EnableAuthorizationEndpoint("/connect/authorize")
                           .EnableLogoutEndpoint("/connect/logout")
                           .EnableTokenEndpoint("/connect/token")
                           .EnableUserinfoEndpoint("/api/userinfo");

                    options.RegisterScopes(OpenIdConnectConstants.Scopes.Email,
                                           OpenIdConnectConstants.Scopes.Profile,
                                           OpenIddictConstants.Scopes.Roles);


                    options.AllowAuthorizationCodeFlow();
                    options.EnableRequestCaching();
                    options.DisableHttpsRequirement();
                    options.UseJsonWebTokens();
                    options.AddEphemeralSigningKey();
                });
        }

As this is no longer a resource server I have removed the validation parts as I don't think this is required. And as I want to use JWT I have un-commented the following lines:

options.UseJsonWebTokens();
options.AddEphemeralSigningKey();

The authorization endpoint returns a SignIn result exactly like the sample, which redirects to the MVC app which then issues an authentication cookie. I can now access protected resources on my MVC APP.

MVC APP startup

  public void ConfigureServices(IServiceCollection services)
        {

            services.Configure<PortalDetails>(options => Configuration.GetSection("PortalDetails").Bind(options));

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(opts =>
            {
                opts.LoginPath = "/login";
                opts.LogoutPath = "/logout";
            })

            .AddJwtBearer(options =>
            {
                //Authority must be a url. It does not have a default value.
                options.Authority = "http://localhost:54540/";
                options.Audience = "mvc"; //This must be included in ticket creation
                options.RequireHttpsMetadata = false;
                options.IncludeErrorDetails = true; //
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType = "sub",
                    RoleClaimType = "role"
                };
            })

            .AddOpenIdConnect(options =>
            {
                // Note: these settings must match the application details
                // inserted in the database at the server level.
                options.ClientId = "mvc";
                options.ClientSecret = "901564A5-E7FE-42CB-B10D-61EF6A8F3654";

                options.RequireHttpsMetadata = false;
                options.GetClaimsFromUserInfoEndpoint = false; // TODO: If this if true then it doesnt work??
                options.SaveTokens = true;

                // Use the authorization code flow.
                options.ResponseType = OpenIdConnectResponseType.Code;
                options.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet;

                // Note: setting the Authority allows the OIDC client middleware to automatically
                // retrieve the identity provider's configuration and spare you from setting
                // the different endpoints URIs or the token validation parameters explicitly.
                options.Authority = "http://localhost:54540/";

                options.Scope.Add("email");
                options.Scope.Add("roles");

                options.SecurityTokenValidator = new JwtSecurityTokenHandler
                {
                    // Disable the built-in JWT claims mapping feature.,
                    InboundClaimTypeMap = new Dictionary<string, string>()
                };

                options.TokenValidationParameters.NameClaimType = "name";
                options.TokenValidationParameters.RoleClaimType = "role";
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddHttpClient<IApiGatewayClient, ApiGatewayClient>();
            services.AddSingleton<ITokenProvider, TokenProvider>();
        }

When calling the resource server I use:

string accessToken = await HttpContext.GetTokenAsync("access_token");

and I can see an access token, I attach that to my http request:

_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

but the result is forbidden.

Finally, I have a protected resource server:

Resource.Startup

  public void ConfigureServices(IServiceCollection services)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            //Add authentication and set default authentication scheme
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //same as "Bearer"
                .AddJwtBearer(options =>
                {
                    //Authority must be a url. It does not have a default value.
                    options.Authority = "http://localhost:54540";
                    options.Audience = "mvc"; //This must be included in ticket creation
                    options.RequireHttpsMetadata = false;
                    options.IncludeErrorDetails = true; //
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        NameClaimType = OpenIdConnectConstants.Claims.Subject,
                        RoleClaimType = OpenIdConnectConstants.Claims.Role,
                    };
                });

            services.AddMvc();
        }

I would like to know if this is the correct setup for my scenario, as I am getting a forbidden result from my resource server.

Thanks

Upvotes: 0

Views: 1194

Answers (1)

Shane
Shane

Reputation: 99

Here is a package which

  • Makes integrating JWT Bearer Token Security in your Asp Net Core 2.0+ app a breeze!
  • Azure Active Directory auth integration.
  • Facebook auth integration.
  • Twitter auth integration.
  • Google auth integration.
  • Also, Swagger UI integration!

It is called AspNetCore.Security.Jwt

GitHub:

https://github.com/VeritasSoftware/AspNetCore.Security.Jwt

The package integrates JWT bearer token into your app as below:

1. Implement IAuthentication interface in your app

using AspNetCore.Security.Jwt;
using System.Threading.Tasks;

namespace XXX.API
{
    public class Authenticator : IAuthentication
    {        
        public async Task<bool> IsValidUser(string id, string password)
        {
            //Put your id authenication here.
            return true;
        }
    }
}

2. In your Startup.cs

using AspNetCore.Security.Jwt;
using Swashbuckle.AspNetCore.Swagger;
.
.
public void ConfigureServices(IServiceCollection services)
{
    .
    .
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "XXX API", Version = "v1" });
    });

    services.AddSecurity<Authenticator>(this.Configuration, true);
    services.AddMvc().AddSecurity();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    .
    .
    .
    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "XXX API V1");
    });

    app.UseSecurity(true);

    app.UseMvc();
}

3. In your appsettings.json

Note:- You can put these settings in Secret Manager by using Manage User Secrets menu (right-click your Project).

 {
     "SecuritySettings": {
        "Secret": "a secret that needs to be at least 16 characters long",
        "Issuer": "your app",
        "Audience": "the client of your app",
        "IdType":  "Name",
        "TokenExpiryInHours" :  2
    },
    .
    .
    .
}

Then you will get endpoints automatically:

/token

/facebook

When you call these endpoints and are successfully authenticated, you will get back a JWT Bearer Token.

In your Controller that you want to secure

You must mark the Controller or Action that you want to secure with Authorize attribute like:

    using Microsoft.AspNetCore.Mvc;
    .
    .
    .

    namespace XXX.API.Controllers
    {
        using Microsoft.AspNetCore.Authorization;

        [Authorize]
        [Route("api/[controller]")]
        public class XXXController : Controller
        {
            .
            .
            .
        }
    }

In Swagger UI, you will automatically see these endpoints.

Authentication endpoints

Upvotes: 1

Related Questions