Stop Expired Access Token from retrieving data from resource Server










1















I have been fiddling around with IDS 4 and I have a small problem. I set my token life times to about 15 seconds and even though they are expired I can still retrieve date from my resource server. If I remove the token from my header on the client call I get a 401 error.



Client



 [Authorize]
public async Task<ActionResult> Shouts()


var accessToken = await HttpContext.GetTokenAsync("access_token");
var tokenh = new JwtSecurityTokenHandler();

var jwtSecurityToken= tokenh.ReadJwtToken(accessToken);

var val = jwtSecurityToken.ValidTo;



using (var client = new HttpClient())


client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var rawResponse = await client.GetAsync("http://localhost:5002/api/Values/Get");

if (rawResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)

var refreshSucc = await this.RefreshTokensAsync(this.HttpContext);
if (!refreshSucc)

var authServerInfo = await this.GetAuthenticationServerInfo();
return Redirect(authServerInfo.AuthorizeEndpoint);



var response = await (rawResponse).Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<String>>(response);
return View("Shouts", data);


public class Startup

public Startup(IConfiguration configuration)

Configuration = configuration;


public IConfiguration Configuration get;

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)


JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>

options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
)
.AddCookie("Cookies",o=>o.LogoutPath="/home/logout")
.AddOpenIdConnect("oidc", opt =>

opt.SignInScheme = "Cookies";
opt.Authority = "http://localhost:5000";
opt.RequireHttpsMetadata = false;
opt.ClientId = "AuthTest_Code";
opt.ClientSecret = "secret";
opt.ResponseType = "id_token code";
opt.Scope.Add("TestAPI");
opt.Scope.Add("offline_access");
opt.Scope.Add("email");
opt.GetClaimsFromUserInfoEndpoint = true;
opt.SaveTokens = true;
);
services.AddMvc();


// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)

if (env.IsDevelopment())

app.UseBrowserLink();
app.UseDeveloperExceptionPage();

else

app.UseExceptionHandler("/Home/Error");


app.UseStaticFiles();

app.UseAuthentication();

app.UseMvc(routes =>

routes.MapRoute(
name: "default",
template: "controller=Home/action=Index/id?");
);




Auth Server



 public static IEnumerable<Client> GetClients()

return new List<Client>

new Client

ClientId = "AuthTest_Code",
ClientSecrets=new new Secret("secret".Sha256()) ,
AllowedGrantTypes = GrantTypes.Hybrid,
AllowedScopes = new List<string>

IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"TestAPI"
,
AllowAccessTokensViaBrowser=true,
AllowOfflineAccess=true,
RedirectUris = new "http://localhost:5001/signin-oidc" ,
PostLogoutRedirectUris= "http://localhost:5001/signout-callback-odic",
RequireConsent=false,
AccessTokenLifetime=15,
AbsoluteRefreshTokenLifetime=15

;


public class Startup

public IHostingEnvironment Environment get;

public Startup(IHostingEnvironment environment)

Environment = environment;

// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)

var isServer = services.AddIdentityServer()
.AddSigningCredential(new X509Certificate2(@"C:OpenSSLCertsAuthenticate.pfx", "Password1"))
.AddInMemoryApiResources(TestConfig.GetApis())
.AddInMemoryClients(TestConfig.GetClients())
.AddInMemoryIdentityResources(TestConfig.GetIdentityResources())
.AddTestUsers(TestConfig.GetUsers());


services.AddMvc();


// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)

if (Environment.IsDevelopment())

app.UseDeveloperExceptionPage();


app.UseIdentityServer();

app.UseStaticFiles();

app.UseMvcWithDefaultRoute();




Resource Server



using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace ResourceAPI

public class Startup

// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)

services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();

services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>

options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ApiName = "TestAPI";
);


// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)

app.UseAuthentication();
app.UseMvc();





[Route("api/[controller]")]
public class ValuesController:ControllerBase

[HttpGet]
[Route("Get")]
[Authorize]
public async Task<IActionResult> Get()

var username = User.Claims.FirstOrDefault(t => t.Type == "email")?.Value;
return Ok(new string "value1", "value2" );




Access Token:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ0Q0Q4NjFEQjA0MzdEMUM4NUY2REU0MTIyMkFDOEIwMTE3M0Q2MTAiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJSTTJHSGJCRGZSeUY5dDVCSWlySXNCRnoxaEEifQ.eyJuYmYiOjE1NDIxMjc4OTQsImV4cCI6MTU0MjEyNzkwOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJUZXN0QVBJIl0sImNsaWVudF9pZCI6IkF1dGhUZXN0X0NvZGUiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTQyMTI3ODkzLCJpZHAiOiJsb2NhbCIsImVtYWlsIjoiRGF2aWRAQUJldHRlckxpZmUuY28uemEiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiZW1haWwiLCJUZXN0QVBJIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbInB3ZCJdfQ.hNskjZz3IBqPg_5T0xVwYEP5RukcMt3l019PRp74vNBkiEr6FLvBADa_eylhNGA8qDd7SwyDkq6APaKxaNt0YybAChZvFW6pzLlfknVVHM1vuN7PDOX9PNGhFK9kSONBypXo6JqV3epactsmJvhr3FZxBSufUDRyV4j_YY3O8TCjJf_5UORc_3ox9clNdjt-Vx-BlcDjVbpBw2P76F3pq2IPPDM139H4qYcyaTzSlEbFd3EdVwO6O85bWM1G8yQ9zQAUk23It29oHxTtwsi5Wg4Zpmt7K7AlvKjKxKoxw_Y32QdBkGY9xU_KXOn4h0WJV3LG-InZc7BveLGHq6ncaQ










share|improve this question




























    1















    I have been fiddling around with IDS 4 and I have a small problem. I set my token life times to about 15 seconds and even though they are expired I can still retrieve date from my resource server. If I remove the token from my header on the client call I get a 401 error.



    Client



     [Authorize]
    public async Task<ActionResult> Shouts()


    var accessToken = await HttpContext.GetTokenAsync("access_token");
    var tokenh = new JwtSecurityTokenHandler();

    var jwtSecurityToken= tokenh.ReadJwtToken(accessToken);

    var val = jwtSecurityToken.ValidTo;



    using (var client = new HttpClient())


    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
    var rawResponse = await client.GetAsync("http://localhost:5002/api/Values/Get");

    if (rawResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)

    var refreshSucc = await this.RefreshTokensAsync(this.HttpContext);
    if (!refreshSucc)

    var authServerInfo = await this.GetAuthenticationServerInfo();
    return Redirect(authServerInfo.AuthorizeEndpoint);



    var response = await (rawResponse).Content.ReadAsStringAsync();
    var data = JsonConvert.DeserializeObject<List<String>>(response);
    return View("Shouts", data);


    public class Startup

    public Startup(IConfiguration configuration)

    Configuration = configuration;


    public IConfiguration Configuration get;

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)


    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    services.AddAuthentication(options =>

    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
    )
    .AddCookie("Cookies",o=>o.LogoutPath="/home/logout")
    .AddOpenIdConnect("oidc", opt =>

    opt.SignInScheme = "Cookies";
    opt.Authority = "http://localhost:5000";
    opt.RequireHttpsMetadata = false;
    opt.ClientId = "AuthTest_Code";
    opt.ClientSecret = "secret";
    opt.ResponseType = "id_token code";
    opt.Scope.Add("TestAPI");
    opt.Scope.Add("offline_access");
    opt.Scope.Add("email");
    opt.GetClaimsFromUserInfoEndpoint = true;
    opt.SaveTokens = true;
    );
    services.AddMvc();


    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    if (env.IsDevelopment())

    app.UseBrowserLink();
    app.UseDeveloperExceptionPage();

    else

    app.UseExceptionHandler("/Home/Error");


    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>

    routes.MapRoute(
    name: "default",
    template: "controller=Home/action=Index/id?");
    );




    Auth Server



     public static IEnumerable<Client> GetClients()

    return new List<Client>

    new Client

    ClientId = "AuthTest_Code",
    ClientSecrets=new new Secret("secret".Sha256()) ,
    AllowedGrantTypes = GrantTypes.Hybrid,
    AllowedScopes = new List<string>

    IdentityServerConstants.StandardScopes.OpenId,
    IdentityServerConstants.StandardScopes.Profile,
    IdentityServerConstants.StandardScopes.Email,
    "TestAPI"
    ,
    AllowAccessTokensViaBrowser=true,
    AllowOfflineAccess=true,
    RedirectUris = new "http://localhost:5001/signin-oidc" ,
    PostLogoutRedirectUris= "http://localhost:5001/signout-callback-odic",
    RequireConsent=false,
    AccessTokenLifetime=15,
    AbsoluteRefreshTokenLifetime=15

    ;


    public class Startup

    public IHostingEnvironment Environment get;

    public Startup(IHostingEnvironment environment)

    Environment = environment;

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)

    var isServer = services.AddIdentityServer()
    .AddSigningCredential(new X509Certificate2(@"C:OpenSSLCertsAuthenticate.pfx", "Password1"))
    .AddInMemoryApiResources(TestConfig.GetApis())
    .AddInMemoryClients(TestConfig.GetClients())
    .AddInMemoryIdentityResources(TestConfig.GetIdentityResources())
    .AddTestUsers(TestConfig.GetUsers());


    services.AddMvc();


    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    if (Environment.IsDevelopment())

    app.UseDeveloperExceptionPage();


    app.UseIdentityServer();

    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();




    Resource Server



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.DependencyInjection;

    namespace ResourceAPI

    public class Startup

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)

    services.AddMvcCore()
    .AddAuthorization()
    .AddJsonFormatters();

    services.AddAuthentication("Bearer")
    .AddIdentityServerAuthentication(options =>

    options.Authority = "http://localhost:5000";
    options.RequireHttpsMetadata = false;
    options.ApiName = "TestAPI";
    );


    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    app.UseAuthentication();
    app.UseMvc();





    [Route("api/[controller]")]
    public class ValuesController:ControllerBase

    [HttpGet]
    [Route("Get")]
    [Authorize]
    public async Task<IActionResult> Get()

    var username = User.Claims.FirstOrDefault(t => t.Type == "email")?.Value;
    return Ok(new string "value1", "value2" );




    Access Token:
    eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ0Q0Q4NjFEQjA0MzdEMUM4NUY2REU0MTIyMkFDOEIwMTE3M0Q2MTAiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJSTTJHSGJCRGZSeUY5dDVCSWlySXNCRnoxaEEifQ.eyJuYmYiOjE1NDIxMjc4OTQsImV4cCI6MTU0MjEyNzkwOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJUZXN0QVBJIl0sImNsaWVudF9pZCI6IkF1dGhUZXN0X0NvZGUiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTQyMTI3ODkzLCJpZHAiOiJsb2NhbCIsImVtYWlsIjoiRGF2aWRAQUJldHRlckxpZmUuY28uemEiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiZW1haWwiLCJUZXN0QVBJIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbInB3ZCJdfQ.hNskjZz3IBqPg_5T0xVwYEP5RukcMt3l019PRp74vNBkiEr6FLvBADa_eylhNGA8qDd7SwyDkq6APaKxaNt0YybAChZvFW6pzLlfknVVHM1vuN7PDOX9PNGhFK9kSONBypXo6JqV3epactsmJvhr3FZxBSufUDRyV4j_YY3O8TCjJf_5UORc_3ox9clNdjt-Vx-BlcDjVbpBw2P76F3pq2IPPDM139H4qYcyaTzSlEbFd3EdVwO6O85bWM1G8yQ9zQAUk23It29oHxTtwsi5Wg4Zpmt7K7AlvKjKxKoxw_Y32QdBkGY9xU_KXOn4h0WJV3LG-InZc7BveLGHq6ncaQ










    share|improve this question


























      1












      1








      1


      0






      I have been fiddling around with IDS 4 and I have a small problem. I set my token life times to about 15 seconds and even though they are expired I can still retrieve date from my resource server. If I remove the token from my header on the client call I get a 401 error.



      Client



       [Authorize]
      public async Task<ActionResult> Shouts()


      var accessToken = await HttpContext.GetTokenAsync("access_token");
      var tokenh = new JwtSecurityTokenHandler();

      var jwtSecurityToken= tokenh.ReadJwtToken(accessToken);

      var val = jwtSecurityToken.ValidTo;



      using (var client = new HttpClient())


      client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
      var rawResponse = await client.GetAsync("http://localhost:5002/api/Values/Get");

      if (rawResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)

      var refreshSucc = await this.RefreshTokensAsync(this.HttpContext);
      if (!refreshSucc)

      var authServerInfo = await this.GetAuthenticationServerInfo();
      return Redirect(authServerInfo.AuthorizeEndpoint);



      var response = await (rawResponse).Content.ReadAsStringAsync();
      var data = JsonConvert.DeserializeObject<List<String>>(response);
      return View("Shouts", data);


      public class Startup

      public Startup(IConfiguration configuration)

      Configuration = configuration;


      public IConfiguration Configuration get;

      // This method gets called by the runtime. Use this method to add services to the container.
      public void ConfigureServices(IServiceCollection services)


      JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
      services.AddAuthentication(options =>

      options.DefaultScheme = "Cookies";
      options.DefaultChallengeScheme = "oidc";
      )
      .AddCookie("Cookies",o=>o.LogoutPath="/home/logout")
      .AddOpenIdConnect("oidc", opt =>

      opt.SignInScheme = "Cookies";
      opt.Authority = "http://localhost:5000";
      opt.RequireHttpsMetadata = false;
      opt.ClientId = "AuthTest_Code";
      opt.ClientSecret = "secret";
      opt.ResponseType = "id_token code";
      opt.Scope.Add("TestAPI");
      opt.Scope.Add("offline_access");
      opt.Scope.Add("email");
      opt.GetClaimsFromUserInfoEndpoint = true;
      opt.SaveTokens = true;
      );
      services.AddMvc();


      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)

      if (env.IsDevelopment())

      app.UseBrowserLink();
      app.UseDeveloperExceptionPage();

      else

      app.UseExceptionHandler("/Home/Error");


      app.UseStaticFiles();

      app.UseAuthentication();

      app.UseMvc(routes =>

      routes.MapRoute(
      name: "default",
      template: "controller=Home/action=Index/id?");
      );




      Auth Server



       public static IEnumerable<Client> GetClients()

      return new List<Client>

      new Client

      ClientId = "AuthTest_Code",
      ClientSecrets=new new Secret("secret".Sha256()) ,
      AllowedGrantTypes = GrantTypes.Hybrid,
      AllowedScopes = new List<string>

      IdentityServerConstants.StandardScopes.OpenId,
      IdentityServerConstants.StandardScopes.Profile,
      IdentityServerConstants.StandardScopes.Email,
      "TestAPI"
      ,
      AllowAccessTokensViaBrowser=true,
      AllowOfflineAccess=true,
      RedirectUris = new "http://localhost:5001/signin-oidc" ,
      PostLogoutRedirectUris= "http://localhost:5001/signout-callback-odic",
      RequireConsent=false,
      AccessTokenLifetime=15,
      AbsoluteRefreshTokenLifetime=15

      ;


      public class Startup

      public IHostingEnvironment Environment get;

      public Startup(IHostingEnvironment environment)

      Environment = environment;

      // This method gets called by the runtime. Use this method to add services to the container.
      // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
      public void ConfigureServices(IServiceCollection services)

      var isServer = services.AddIdentityServer()
      .AddSigningCredential(new X509Certificate2(@"C:OpenSSLCertsAuthenticate.pfx", "Password1"))
      .AddInMemoryApiResources(TestConfig.GetApis())
      .AddInMemoryClients(TestConfig.GetClients())
      .AddInMemoryIdentityResources(TestConfig.GetIdentityResources())
      .AddTestUsers(TestConfig.GetUsers());


      services.AddMvc();


      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)

      if (Environment.IsDevelopment())

      app.UseDeveloperExceptionPage();


      app.UseIdentityServer();

      app.UseStaticFiles();

      app.UseMvcWithDefaultRoute();




      Resource Server



      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;
      using Microsoft.AspNetCore.Builder;
      using Microsoft.AspNetCore.Hosting;
      using Microsoft.AspNetCore.Http;
      using Microsoft.Extensions.DependencyInjection;

      namespace ResourceAPI

      public class Startup

      // This method gets called by the runtime. Use this method to add services to the container.
      // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
      public void ConfigureServices(IServiceCollection services)

      services.AddMvcCore()
      .AddAuthorization()
      .AddJsonFormatters();

      services.AddAuthentication("Bearer")
      .AddIdentityServerAuthentication(options =>

      options.Authority = "http://localhost:5000";
      options.RequireHttpsMetadata = false;
      options.ApiName = "TestAPI";
      );


      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)

      app.UseAuthentication();
      app.UseMvc();





      [Route("api/[controller]")]
      public class ValuesController:ControllerBase

      [HttpGet]
      [Route("Get")]
      [Authorize]
      public async Task<IActionResult> Get()

      var username = User.Claims.FirstOrDefault(t => t.Type == "email")?.Value;
      return Ok(new string "value1", "value2" );




      Access Token:
      eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ0Q0Q4NjFEQjA0MzdEMUM4NUY2REU0MTIyMkFDOEIwMTE3M0Q2MTAiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJSTTJHSGJCRGZSeUY5dDVCSWlySXNCRnoxaEEifQ.eyJuYmYiOjE1NDIxMjc4OTQsImV4cCI6MTU0MjEyNzkwOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJUZXN0QVBJIl0sImNsaWVudF9pZCI6IkF1dGhUZXN0X0NvZGUiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTQyMTI3ODkzLCJpZHAiOiJsb2NhbCIsImVtYWlsIjoiRGF2aWRAQUJldHRlckxpZmUuY28uemEiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiZW1haWwiLCJUZXN0QVBJIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbInB3ZCJdfQ.hNskjZz3IBqPg_5T0xVwYEP5RukcMt3l019PRp74vNBkiEr6FLvBADa_eylhNGA8qDd7SwyDkq6APaKxaNt0YybAChZvFW6pzLlfknVVHM1vuN7PDOX9PNGhFK9kSONBypXo6JqV3epactsmJvhr3FZxBSufUDRyV4j_YY3O8TCjJf_5UORc_3ox9clNdjt-Vx-BlcDjVbpBw2P76F3pq2IPPDM139H4qYcyaTzSlEbFd3EdVwO6O85bWM1G8yQ9zQAUk23It29oHxTtwsi5Wg4Zpmt7K7AlvKjKxKoxw_Y32QdBkGY9xU_KXOn4h0WJV3LG-InZc7BveLGHq6ncaQ










      share|improve this question
















      I have been fiddling around with IDS 4 and I have a small problem. I set my token life times to about 15 seconds and even though they are expired I can still retrieve date from my resource server. If I remove the token from my header on the client call I get a 401 error.



      Client



       [Authorize]
      public async Task<ActionResult> Shouts()


      var accessToken = await HttpContext.GetTokenAsync("access_token");
      var tokenh = new JwtSecurityTokenHandler();

      var jwtSecurityToken= tokenh.ReadJwtToken(accessToken);

      var val = jwtSecurityToken.ValidTo;



      using (var client = new HttpClient())


      client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
      var rawResponse = await client.GetAsync("http://localhost:5002/api/Values/Get");

      if (rawResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)

      var refreshSucc = await this.RefreshTokensAsync(this.HttpContext);
      if (!refreshSucc)

      var authServerInfo = await this.GetAuthenticationServerInfo();
      return Redirect(authServerInfo.AuthorizeEndpoint);



      var response = await (rawResponse).Content.ReadAsStringAsync();
      var data = JsonConvert.DeserializeObject<List<String>>(response);
      return View("Shouts", data);


      public class Startup

      public Startup(IConfiguration configuration)

      Configuration = configuration;


      public IConfiguration Configuration get;

      // This method gets called by the runtime. Use this method to add services to the container.
      public void ConfigureServices(IServiceCollection services)


      JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
      services.AddAuthentication(options =>

      options.DefaultScheme = "Cookies";
      options.DefaultChallengeScheme = "oidc";
      )
      .AddCookie("Cookies",o=>o.LogoutPath="/home/logout")
      .AddOpenIdConnect("oidc", opt =>

      opt.SignInScheme = "Cookies";
      opt.Authority = "http://localhost:5000";
      opt.RequireHttpsMetadata = false;
      opt.ClientId = "AuthTest_Code";
      opt.ClientSecret = "secret";
      opt.ResponseType = "id_token code";
      opt.Scope.Add("TestAPI");
      opt.Scope.Add("offline_access");
      opt.Scope.Add("email");
      opt.GetClaimsFromUserInfoEndpoint = true;
      opt.SaveTokens = true;
      );
      services.AddMvc();


      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)

      if (env.IsDevelopment())

      app.UseBrowserLink();
      app.UseDeveloperExceptionPage();

      else

      app.UseExceptionHandler("/Home/Error");


      app.UseStaticFiles();

      app.UseAuthentication();

      app.UseMvc(routes =>

      routes.MapRoute(
      name: "default",
      template: "controller=Home/action=Index/id?");
      );




      Auth Server



       public static IEnumerable<Client> GetClients()

      return new List<Client>

      new Client

      ClientId = "AuthTest_Code",
      ClientSecrets=new new Secret("secret".Sha256()) ,
      AllowedGrantTypes = GrantTypes.Hybrid,
      AllowedScopes = new List<string>

      IdentityServerConstants.StandardScopes.OpenId,
      IdentityServerConstants.StandardScopes.Profile,
      IdentityServerConstants.StandardScopes.Email,
      "TestAPI"
      ,
      AllowAccessTokensViaBrowser=true,
      AllowOfflineAccess=true,
      RedirectUris = new "http://localhost:5001/signin-oidc" ,
      PostLogoutRedirectUris= "http://localhost:5001/signout-callback-odic",
      RequireConsent=false,
      AccessTokenLifetime=15,
      AbsoluteRefreshTokenLifetime=15

      ;


      public class Startup

      public IHostingEnvironment Environment get;

      public Startup(IHostingEnvironment environment)

      Environment = environment;

      // This method gets called by the runtime. Use this method to add services to the container.
      // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
      public void ConfigureServices(IServiceCollection services)

      var isServer = services.AddIdentityServer()
      .AddSigningCredential(new X509Certificate2(@"C:OpenSSLCertsAuthenticate.pfx", "Password1"))
      .AddInMemoryApiResources(TestConfig.GetApis())
      .AddInMemoryClients(TestConfig.GetClients())
      .AddInMemoryIdentityResources(TestConfig.GetIdentityResources())
      .AddTestUsers(TestConfig.GetUsers());


      services.AddMvc();


      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)

      if (Environment.IsDevelopment())

      app.UseDeveloperExceptionPage();


      app.UseIdentityServer();

      app.UseStaticFiles();

      app.UseMvcWithDefaultRoute();




      Resource Server



      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;
      using Microsoft.AspNetCore.Builder;
      using Microsoft.AspNetCore.Hosting;
      using Microsoft.AspNetCore.Http;
      using Microsoft.Extensions.DependencyInjection;

      namespace ResourceAPI

      public class Startup

      // This method gets called by the runtime. Use this method to add services to the container.
      // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
      public void ConfigureServices(IServiceCollection services)

      services.AddMvcCore()
      .AddAuthorization()
      .AddJsonFormatters();

      services.AddAuthentication("Bearer")
      .AddIdentityServerAuthentication(options =>

      options.Authority = "http://localhost:5000";
      options.RequireHttpsMetadata = false;
      options.ApiName = "TestAPI";
      );


      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)

      app.UseAuthentication();
      app.UseMvc();





      [Route("api/[controller]")]
      public class ValuesController:ControllerBase

      [HttpGet]
      [Route("Get")]
      [Authorize]
      public async Task<IActionResult> Get()

      var username = User.Claims.FirstOrDefault(t => t.Type == "email")?.Value;
      return Ok(new string "value1", "value2" );




      Access Token:
      eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ0Q0Q4NjFEQjA0MzdEMUM4NUY2REU0MTIyMkFDOEIwMTE3M0Q2MTAiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJSTTJHSGJCRGZSeUY5dDVCSWlySXNCRnoxaEEifQ.eyJuYmYiOjE1NDIxMjc4OTQsImV4cCI6MTU0MjEyNzkwOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJUZXN0QVBJIl0sImNsaWVudF9pZCI6IkF1dGhUZXN0X0NvZGUiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTQyMTI3ODkzLCJpZHAiOiJsb2NhbCIsImVtYWlsIjoiRGF2aWRAQUJldHRlckxpZmUuY28uemEiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiZW1haWwiLCJUZXN0QVBJIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbInB3ZCJdfQ.hNskjZz3IBqPg_5T0xVwYEP5RukcMt3l019PRp74vNBkiEr6FLvBADa_eylhNGA8qDd7SwyDkq6APaKxaNt0YybAChZvFW6pzLlfknVVHM1vuN7PDOX9PNGhFK9kSONBypXo6JqV3epactsmJvhr3FZxBSufUDRyV4j_YY3O8TCjJf_5UORc_3ox9clNdjt-Vx-BlcDjVbpBw2P76F3pq2IPPDM139H4qYcyaTzSlEbFd3EdVwO6O85bWM1G8yQ9zQAUk23It29oHxTtwsi5Wg4Zpmt7K7AlvKjKxKoxw_Y32QdBkGY9xU_KXOn4h0WJV3LG-InZc7BveLGHq6ncaQ







      asp.net-core-2.0 identityserver4






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 17:00







      David

















      asked Nov 13 '18 at 16:31









      DavidDavid

      3,082123256




      3,082123256






















          2 Answers
          2






          active

          oldest

          votes


















          2














          Try setting options.JwtValidationClockSkew property to zero in your web api(resource server)



           services.AddAuthentication("Bearer")
          .AddIdentityServerAuthentication(options =>

          options.JwtValidationClockSkew = TimeSpan.Zero;
          options.Authority = "https://localhost:44323";
          options.RequireHttpsMetadata = false;

          options.ApiName = "api1";
          );


          There is a clock skew in the Microsoft JWT validation middleware. It is set by default to 5 mins. And it's suggest to leave it as default (300 seconds/5 minutes).






          share|improve this answer























          • Howcome jwtSecurityToken.ValidTo show the 15s time span? I would think the the authorize attribute will use this date time, compare it to the current utc date and see if the token is expired. I find this to be weird!!! I will have a look now I hope this works

            – David
            Nov 14 '18 at 6:51






          • 1





            The clock skew feature exists to protect you from out of sync clocks. See discussion here .jwtSecurityToken.ValidTo just shows the expire time of access token .

            – Nan Yu
            Nov 14 '18 at 6:57











          • Funny I just read that. I cannot disable the clockskew I'm using IDS4 is there another way. I just need it for test purposes.

            – David
            Nov 14 '18 at 7:48






          • 1





            No , add that codes to your web api , that is during the process of validating the access token in web api

            – Nan Yu
            Nov 14 '18 at 8:10







          • 1





            add options.JwtValidationClockSkew = TimeSpan.Zero; in Resource Server of your provide codes

            – Nan Yu
            Nov 14 '18 at 8:11


















          1














          This is most likely due to the default 5 minute (if memory serves) clock skew allowance. It is however possible to override this setting in IDS4 and the bearer token middleware.






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53285495%2fstop-expired-access-token-from-retrieving-data-from-resource-server%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            Try setting options.JwtValidationClockSkew property to zero in your web api(resource server)



             services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>

            options.JwtValidationClockSkew = TimeSpan.Zero;
            options.Authority = "https://localhost:44323";
            options.RequireHttpsMetadata = false;

            options.ApiName = "api1";
            );


            There is a clock skew in the Microsoft JWT validation middleware. It is set by default to 5 mins. And it's suggest to leave it as default (300 seconds/5 minutes).






            share|improve this answer























            • Howcome jwtSecurityToken.ValidTo show the 15s time span? I would think the the authorize attribute will use this date time, compare it to the current utc date and see if the token is expired. I find this to be weird!!! I will have a look now I hope this works

              – David
              Nov 14 '18 at 6:51






            • 1





              The clock skew feature exists to protect you from out of sync clocks. See discussion here .jwtSecurityToken.ValidTo just shows the expire time of access token .

              – Nan Yu
              Nov 14 '18 at 6:57











            • Funny I just read that. I cannot disable the clockskew I'm using IDS4 is there another way. I just need it for test purposes.

              – David
              Nov 14 '18 at 7:48






            • 1





              No , add that codes to your web api , that is during the process of validating the access token in web api

              – Nan Yu
              Nov 14 '18 at 8:10







            • 1





              add options.JwtValidationClockSkew = TimeSpan.Zero; in Resource Server of your provide codes

              – Nan Yu
              Nov 14 '18 at 8:11















            2














            Try setting options.JwtValidationClockSkew property to zero in your web api(resource server)



             services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>

            options.JwtValidationClockSkew = TimeSpan.Zero;
            options.Authority = "https://localhost:44323";
            options.RequireHttpsMetadata = false;

            options.ApiName = "api1";
            );


            There is a clock skew in the Microsoft JWT validation middleware. It is set by default to 5 mins. And it's suggest to leave it as default (300 seconds/5 minutes).






            share|improve this answer























            • Howcome jwtSecurityToken.ValidTo show the 15s time span? I would think the the authorize attribute will use this date time, compare it to the current utc date and see if the token is expired. I find this to be weird!!! I will have a look now I hope this works

              – David
              Nov 14 '18 at 6:51






            • 1





              The clock skew feature exists to protect you from out of sync clocks. See discussion here .jwtSecurityToken.ValidTo just shows the expire time of access token .

              – Nan Yu
              Nov 14 '18 at 6:57











            • Funny I just read that. I cannot disable the clockskew I'm using IDS4 is there another way. I just need it for test purposes.

              – David
              Nov 14 '18 at 7:48






            • 1





              No , add that codes to your web api , that is during the process of validating the access token in web api

              – Nan Yu
              Nov 14 '18 at 8:10







            • 1





              add options.JwtValidationClockSkew = TimeSpan.Zero; in Resource Server of your provide codes

              – Nan Yu
              Nov 14 '18 at 8:11













            2












            2








            2







            Try setting options.JwtValidationClockSkew property to zero in your web api(resource server)



             services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>

            options.JwtValidationClockSkew = TimeSpan.Zero;
            options.Authority = "https://localhost:44323";
            options.RequireHttpsMetadata = false;

            options.ApiName = "api1";
            );


            There is a clock skew in the Microsoft JWT validation middleware. It is set by default to 5 mins. And it's suggest to leave it as default (300 seconds/5 minutes).






            share|improve this answer













            Try setting options.JwtValidationClockSkew property to zero in your web api(resource server)



             services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>

            options.JwtValidationClockSkew = TimeSpan.Zero;
            options.Authority = "https://localhost:44323";
            options.RequireHttpsMetadata = false;

            options.ApiName = "api1";
            );


            There is a clock skew in the Microsoft JWT validation middleware. It is set by default to 5 mins. And it's suggest to leave it as default (300 seconds/5 minutes).







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 14 '18 at 5:57









            Nan YuNan Yu

            6,5452754




            6,5452754












            • Howcome jwtSecurityToken.ValidTo show the 15s time span? I would think the the authorize attribute will use this date time, compare it to the current utc date and see if the token is expired. I find this to be weird!!! I will have a look now I hope this works

              – David
              Nov 14 '18 at 6:51






            • 1





              The clock skew feature exists to protect you from out of sync clocks. See discussion here .jwtSecurityToken.ValidTo just shows the expire time of access token .

              – Nan Yu
              Nov 14 '18 at 6:57











            • Funny I just read that. I cannot disable the clockskew I'm using IDS4 is there another way. I just need it for test purposes.

              – David
              Nov 14 '18 at 7:48






            • 1





              No , add that codes to your web api , that is during the process of validating the access token in web api

              – Nan Yu
              Nov 14 '18 at 8:10







            • 1





              add options.JwtValidationClockSkew = TimeSpan.Zero; in Resource Server of your provide codes

              – Nan Yu
              Nov 14 '18 at 8:11

















            • Howcome jwtSecurityToken.ValidTo show the 15s time span? I would think the the authorize attribute will use this date time, compare it to the current utc date and see if the token is expired. I find this to be weird!!! I will have a look now I hope this works

              – David
              Nov 14 '18 at 6:51






            • 1





              The clock skew feature exists to protect you from out of sync clocks. See discussion here .jwtSecurityToken.ValidTo just shows the expire time of access token .

              – Nan Yu
              Nov 14 '18 at 6:57











            • Funny I just read that. I cannot disable the clockskew I'm using IDS4 is there another way. I just need it for test purposes.

              – David
              Nov 14 '18 at 7:48






            • 1





              No , add that codes to your web api , that is during the process of validating the access token in web api

              – Nan Yu
              Nov 14 '18 at 8:10







            • 1





              add options.JwtValidationClockSkew = TimeSpan.Zero; in Resource Server of your provide codes

              – Nan Yu
              Nov 14 '18 at 8:11
















            Howcome jwtSecurityToken.ValidTo show the 15s time span? I would think the the authorize attribute will use this date time, compare it to the current utc date and see if the token is expired. I find this to be weird!!! I will have a look now I hope this works

            – David
            Nov 14 '18 at 6:51





            Howcome jwtSecurityToken.ValidTo show the 15s time span? I would think the the authorize attribute will use this date time, compare it to the current utc date and see if the token is expired. I find this to be weird!!! I will have a look now I hope this works

            – David
            Nov 14 '18 at 6:51




            1




            1





            The clock skew feature exists to protect you from out of sync clocks. See discussion here .jwtSecurityToken.ValidTo just shows the expire time of access token .

            – Nan Yu
            Nov 14 '18 at 6:57





            The clock skew feature exists to protect you from out of sync clocks. See discussion here .jwtSecurityToken.ValidTo just shows the expire time of access token .

            – Nan Yu
            Nov 14 '18 at 6:57













            Funny I just read that. I cannot disable the clockskew I'm using IDS4 is there another way. I just need it for test purposes.

            – David
            Nov 14 '18 at 7:48





            Funny I just read that. I cannot disable the clockskew I'm using IDS4 is there another way. I just need it for test purposes.

            – David
            Nov 14 '18 at 7:48




            1




            1





            No , add that codes to your web api , that is during the process of validating the access token in web api

            – Nan Yu
            Nov 14 '18 at 8:10






            No , add that codes to your web api , that is during the process of validating the access token in web api

            – Nan Yu
            Nov 14 '18 at 8:10





            1




            1





            add options.JwtValidationClockSkew = TimeSpan.Zero; in Resource Server of your provide codes

            – Nan Yu
            Nov 14 '18 at 8:11





            add options.JwtValidationClockSkew = TimeSpan.Zero; in Resource Server of your provide codes

            – Nan Yu
            Nov 14 '18 at 8:11













            1














            This is most likely due to the default 5 minute (if memory serves) clock skew allowance. It is however possible to override this setting in IDS4 and the bearer token middleware.






            share|improve this answer



























              1














              This is most likely due to the default 5 minute (if memory serves) clock skew allowance. It is however possible to override this setting in IDS4 and the bearer token middleware.






              share|improve this answer

























                1












                1








                1







                This is most likely due to the default 5 minute (if memory serves) clock skew allowance. It is however possible to override this setting in IDS4 and the bearer token middleware.






                share|improve this answer













                This is most likely due to the default 5 minute (if memory serves) clock skew allowance. It is however possible to override this setting in IDS4 and the bearer token middleware.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 '18 at 17:54









                mackiemackie

                1,92811110




                1,92811110



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53285495%2fstop-expired-access-token-from-retrieving-data-from-resource-server%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Barbados

                    How to read a connectionString WITH PROVIDER in .NET Core?

                    Node.js Script on GitHub Pages or Amazon S3