Reference Tokens In IdentityServer 4

nkmnhan@gmail.com | 56 day | 182


In this article, I will show you the reference token and how to install reference token in identity server 4

 

Token Types in Identity Server 4

In Identity Server 4 has 2 types of access token:

  • Jwt token is a self-contained access token - it’s a protected data structure with claims and an expiration. It's hard to revoke. And it will be valid until it expired.
  •  Reference token is quite different from Jwt token - Identity Server 4 will restore the content token in the data store. When the API receives this token, the API must call to identity server to validate this token.

Reference token flow

 For more detail, you can take a look at the official document here

Config Reference token in Identity Server 4 .Net Core MVC

Prerequisite:

Create 3 projects:

  • API: Web APIs
  • Client: ASP.NET Core MVC
  • IdentityServer: ASP.NET Core MVC

You can find an implementation of the above available on My GitHub.

IdentityServer project:

I used SQL Server to restore data for this sample

Add NuGet packages:

  • IdentityServer4
  • IdentityServer4.AspNetIdentity
  • IdentityServer4.EntityFramework

When you seed Client, you must switch the token type of a client to Reference

Set up Client

 

The introspection endpoint requires authentication - since the client of an introspection endpoint is an API, you configure the secret on the ApiResource:

Config Api Resource

This is a ConfigureServices for IdentityServer:

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

	services.AddDbContext<ApplicationDbContext>(options =>
		options.UseSqlServer(Configuration.GetConnectionString("IdentityUserConnection")));

	services.AddIdentity<ApplicationUser, IdentityRole>()
		.AddEntityFrameworkStores<ApplicationDbContext>()
		.AddDefaultTokenProviders();

	var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
	string connectionString = Configuration.GetConnectionString("IdentityConfigConnection");

	services.AddIdentityServer()
		.AddConfigurationStore(options =>
		{
			options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
				sql => sql.MigrationsAssembly(migrationsAssembly));
		})
		.AddOperationalStore(options =>
		{
			options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
				sql => sql.MigrationsAssembly(migrationsAssembly));
		})
		.AddAspNetIdentity<ApplicationUser>()
		.AddDeveloperSigningCredential();

	services.AddLogging();
}

Client project:

Add NuGet packages:

  • Microsoft.AspNetCore.Authentication.OpenIdConnect

This is a ConfigureServices for Client:

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

	JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

	services.AddAuthentication(options =>
	{
		options.DefaultScheme = "Cookies";
		options.DefaultChallengeScheme = "oidc";
	})
		.AddCookie("Cookies")
		.AddOpenIdConnect("oidc", options =>
		{
			options.Authority = "http://localhost:5000";
			options.RequireHttpsMetadata = false;

			options.ClientId = "mvc";
			options.ClientSecret = "secret";
			options.ResponseType = "code";

			options.SaveTokens = true;

			options.Scope.Add("api1");
			options.Scope.Add("offline_access");
		});
}

Api project:

Add NuGet packages:

  • IdentityServer4.AccessTokenValidation

IdentityServer provides an implementation of the OAuth 2.0 introspection specification which allows APIs to dereference the tokens. I used IdentityServer4.AccessTokenValidation which can validate both JWTs and reference tokens.

This is a ConfigureServices for Api:

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

	services.AddDistributedMemoryCache();

	services.AddAuthentication("Bearer")
		.AddIdentityServerAuthentication("Bearer", options =>
		{
			options.Authority = "http://localhost:5000";
			options.RequireHttpsMetadata = false;

			options.ApiName = "api1";
			options.ApiSecret = "secret";

			options.EnableCaching = true;
			options.CacheDuration = TimeSpan.FromMinutes(10);
		});

	services.AddCors(options =>
	{
		// this defines a CORS policy called "default"
		options.AddPolicy("default", policy =>
		{
			policy.WithOrigins("http://localhost:5003")
				.AllowAnyHeader()
				.AllowAnyMethod();
		});
	});
}

Run The Projects

Execute all our projects and access http://localhost:5002/ then login with the default account.

Login Page

Login success

Login success

Call API success

Call Api success

We can verify more information in logs and database

Introspection

Persisted Grands

I hope this article helped you understand the reference token and how to configure it.
If you have any further questions feel free to contact me.


Top Articles

Bất Đầu Với WebApi Và Dot Net Core (.Net Core)

1131 day
Butter Ngo
Views 6824
Comments 0

Repository Và Unit Of Work (Entity Framework)

1050 day
ndtung449@gmail.com
Views 4162
Comments 0

Dot Net Core Bearer Token With (JWT) (.Net Core)

1063 day
Butter Ngo
Views 4159
Comments 0

Bắt Đầu Với Dot NET Core (.Net Core)

1143 day
Butter Ngo
Views 3834
Comments 0

Top Question

Bi lỗi Invalid Column Name khi sử dụng LinQ (.Net)

990 day
Bảo Dương
Views 1058
Answers 2

Làm thế nào để lấy information từ token (.Net Core)

380 day
ngovu.dl@gmail.com
Views 604
Answers 1

.NET CORE API JWT (.Net Core)

283 day
huynhminhnhut97@gmail.com
Views 595
Answers 2