Aceess Token to short. Netcore MVC + WebAPi Netcore 2.0

I’m migrating an asp net mvc application to mvc net core. In asp net I have the following code that works correctly (I get an accesstoken with the correct scopes)

public void Cofiguration(IAppBuilder app)
{
// Configure Auth0 parameters
string auth0Domain = ConfigurationManager.AppSettings[“auth0:Domain”];
string auth0ClientId = ConfigurationManager.AppSettings[“auth0:ClientId”];
string auth0ClientSecret = ConfigurationManager.AppSettings[“auth0:ClientSecret”];
string auth0RedirectUri = ConfigurationManager.AppSettings[“auth0:RedirectUri”];
string auth0PostLogoutRedirectUri = ConfigurationManager.AppSettings[“auth0:PostLogoutRedirectUri”];

		// Enable Kentor Cookie Saver middleware
		app.UseKentorOwinCookieSaver();

		// Set Cookies as default authentication type
		app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
		app.UseCookieAuthentication(new CookieAuthenticationOptions
		{
			AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
			LoginPath = new PathString("/Account/Login")
		});

		// Configure Auth0 authentication
		app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
		{
			AuthenticationType = "Auth0",

			Authority = $"https://{auth0Domain}",

			ClientId = auth0ClientId,
			ClientSecret = auth0ClientSecret,

			RedirectUri = auth0RedirectUri,
			PostLogoutRedirectUri = auth0PostLogoutRedirectUri,

			ResponseType = OpenIdConnectResponseType.CodeIdTokenToken,
			Scope = "openid profile",

			TokenValidationParameters = new TokenValidationParameters
			{
				NameClaimType = "name"
			},

			Notifications = new OpenIdConnectAuthenticationNotifications
			{
				SecurityTokenValidated = notification =>
				{
					notification.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));
					notification.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", notification.ProtocolMessage.AccessToken));

					return Task.FromResult(0);
				},

				RedirectToIdentityProvider = notification =>
				{
					if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
					{
						notification.ProtocolMessage.SetParameter("audience", "https://lxxxxxxx.com/api");
					}
					else
						if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
					{
						var logoutUri = $"https://{auth0Domain}/v2/logout?client_id={auth0ClientId}";

						var postLogoutUri = notification.ProtocolMessage.PostLogoutRedirectUri;
						if (!string.IsNullOrEmpty(postLogoutUri))
						{
							if (postLogoutUri.StartsWith("/"))
							{
								// transform to absolute
								var request = notification.Request;
								postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
							}
							logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
						}

						notification.Response.Redirect(logoutUri);
						notification.HandleResponse();
					}
					return Task.FromResult(0);
				}
			}
		});
	}

Code on webapi netcore works ok (example Auth0 ASP.NET Core Web API SDK Quickstarts: Authorization)

public void ConfigureServices(IServiceCollection services)
{
var certificateData = Configuration[“Auth0:certificate”];
var certificate = new X509Certificate2(Convert.FromBase64String(certificateData));

		string domain = $"https://{Configuration["Auth0:Domain"]}/";

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

		services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
																		 .AllowAnyMethod()
																		 .AllowAnyHeader()));

		services.AddAuthentication(options =>
		{

			options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
			options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

		}).AddJwtBearer(options =>
		{
			options.Authority = domain;
			options.Audience = Configuration["Auth0:ApiIdentifier"];
			

		});

		//Register scopes dynamically
		services.AddSingleton<IAuthorizationPolicyProvider, AuthorizationPolicyProvider>();

		// register the scope authorization handler
		services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();
		services.AddMvc();

		services.AddAutoMapper();
        var connection = myconnectionserver
      

    }

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

		app.UseCors("AllowAll");

		

		app.UseAuthentication();

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

in my mvc net core application. Which does not work and get an accesstoken to short without scopes. (example: Auth0 ASP.NET Core MVC SDK Quickstarts: Login):

public void ConfigureServices(IServiceCollection services)
{
services.Configure(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => HostingEnvironment.IsProduction();
options.MinimumSameSitePolicy = SameSiteMode.None;
});

		// Add authentication services
		services.AddAuthentication(options => {
			options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
			options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
			options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
		})

		
		.AddCookie()
		.AddOpenIdConnect("Auth0", options => {
			// Set the authority to your Auth0 domain
			options.Authority = $"https://{Configuration["Auth0:Domain"]}";
			
		
			// Configure the Auth0 Client ID and Client Secret
			options.ClientId = Configuration["Auth0:ClientId"];
			options.ClientSecret = Configuration["Auth0:ClientSecret"];

			// Set response type to code
			options.ResponseType = "code id_token token";

			// Configure the scope
			options.Scope.Clear();
			options.Scope.Add("openid");
			options.Scope.Add("profile");
		

			

			// Set the callback path, so Auth0 will call back to http://localhost:5000/signin-auth0 
			// Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard 
			options.CallbackPath = new PathString("/signin-auth0");

			// Configure the Claims Issuer to be Auth0
			options.ClaimsIssuer = "Auth0";

			//Get roles from Auth0
			options.TokenValidationParameters = new TokenValidationParameters
			{
				NameClaimType = "name",
				
			};

			// Saves tokens to the AuthenticationProperties
			options.SaveTokens = true;




			options.Events = new OpenIdConnectEvents
			{

			
				// handle the logout redirection 
				OnRedirectToIdentityProviderForSignOut = (context) =>
				{
					var logoutUri = $"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}";

					var postLogoutUri = context.Properties.RedirectUri;
					if (!string.IsNullOrEmpty(postLogoutUri))
					{
						if (postLogoutUri.StartsWith("/"))
						{
							// transform to absolute
							var request = context.Request;
							postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
						}
						logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
					}

					context.Response.Redirect(logoutUri);
					context.HandleResponse();

					return Task.CompletedTask;
				}
			};
		});

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

what do I do wrong in the netcore application and only get a very short accesstoken (and without scopes)?

Note: I use authorization extension

Thanks for help

I found the solution here: Auth0 ASP.NET Core MVC SDK Quickstarts: Login

An additional comment, in the example that is downloaded from the link that, you can not find this part in the code:

Obtain an Access Token for Calling an API

options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = context =>
{
context.ProtocolMessage.SetParameter("audience", "https://xxxxxx.com/api");


            return Task.FromResult(0);
        }
    };  

It would be good to add it
Thanks for the support

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.