by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Sep 21 09:32
    GDreyV opened #1097
  • Sep 20 15:06

    kevinchalet on dev

    Update the ProcessHostRedirecti… (compare)

  • Sep 20 15:06
    kevinchalet closed #1096
  • Sep 20 14:49
    kevinchalet labeled #1096
  • Sep 20 14:49
    kevinchalet assigned #1096
  • Sep 20 14:49
    kevinchalet milestoned #1096
  • Sep 20 14:49
    kevinchalet opened #1096
  • Sep 19 18:31

    kevinchalet on dev

    Fix the ProcessHostRedirectionR… (compare)

  • Sep 19 18:31
    kevinchalet closed #1095
  • Sep 19 18:11
    kevinchalet assigned #1095
  • Sep 19 18:11
    kevinchalet labeled #1095
  • Sep 19 18:11
    kevinchalet milestoned #1095
  • Sep 19 18:11
    kevinchalet opened #1095
  • Sep 19 14:06
    kevinchalet commented #1053
  • Sep 19 06:57
    lahma commented #1053
  • Sep 18 18:51

    kevinchalet on dev

    Change the resource identifiers… (compare)

  • Sep 18 18:51
    kevinchalet closed #1094
  • Sep 18 17:31
    kevinchalet commented #1093
  • Sep 18 17:23
    aviatoredb commented #1093
  • Sep 18 17:19
    kevinchalet closed #1093
robertovaldesperez
@robertovaldesperez

System.InvalidOperationException: The authorization request was not handled. To handle authorization requests, create a class implementing 'IOpenIddictServerHandler<HandleAuthorizationRequestContext>' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'.
Alternatively, enable the pass-through mode to handle them at a later stage.
at OpenIddict.Server.OpenIddictServerHandlers.Authentication.HandleAuthorizationRequest.HandleAsync(ProcessRequestContext context) in //src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.cs:line 311
at OpenIddict.Server.OpenIddictServerProvider.DispatchAsyncTContext in /
/src/OpenIddict.Server/OpenIddictServerProvider.cs:line 54
at OpenIddict.Server.OpenIddictServerProvider.DispatchAsyncTContext in //src/OpenIddict.Server/OpenIddictServerProvider.cs:line 52
at OpenIddict.Server.AspNetCore.OpenIddictServerAspNetCoreHandler.HandleRequestAsync() in /
/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs:line 65
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS

Cache-Control: no-cache
Connection: keep-alive
Pragma: no-cache
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/plain, /
Accept-Encoding: gzip, deflate, br
Accept-Language: es-ES,es;q=0.9
Host: localhost:5000
Referer: http://localhost:9527/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36
Origin: http://localhost:9527
Content-Length: 182
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty

Kévin Chalet
@kevinchalet
services.AddOpenIddict().AddServer(options => options.UseAspNetCore().DisableTransportSecurityRequirement()).
Regarding the last error, call services.AddOpenIddict().AddServer(options => options.UseAspNetCore().EnableAuthorizationEndpointPassthrough()) and create a MVC action for the authorization endpoint, like in the samples.
robertovaldesperez
@robertovaldesperez
I am trying to logout but it gives me a 400 Bad request error
        services.AddOpenIddict().AddServer(options =>
        {
            options/*.SetAuthorizationEndpointUris(new PathString(TokenEndpointPath))*/.SetTokenEndpointUris(new PathString(TokenEndpointPath)).SetUserinfoEndpointUris(new PathString(UserinfoEndpointPath)).SetLogoutEndpointUris(new PathString(LogoutEndpointPath));
            options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles);
            options/*.AllowAuthorizationCodeFlow()*/.AllowClientCredentialsFlow().AllowPasswordFlow().AllowRefreshTokenFlow();
            options.AddDevelopmentEncryptionCertificate().AddDevelopmentSigningCertificate();
            options.EnableDegradedMode();
            options.UseAspNetCore()/*.EnableAuthorizationEndpointPassthrough()*/.EnableTokenEndpointPassthrough().EnableUserinfoEndpointPassthrough().EnableLogoutEndpointPassthrough().DisableTransportSecurityRequirement();
            //options.SetAccessTokenLifetime(TimeSpan.FromMinutes(30));
            options.AddEventHandler<ValidateTokenRequestContext>(builder => builder.UseInlineHandler(context =>
            {
                if (context.Request.GrantType != GrantTypes.Password && context.Request.GrantType != GrantTypes.RefreshToken)
                {
                    context.Reject(Errors.UnsupportedGrantType, "Only grant_type=password and refresh_token requests are accepted by this server.");
                    return default;
                }

                if (context.ClientId == null)
                {
                    context.Reject("invalid_clientId", "ClientId should be sent.");
                    return default;
                }

                var client = ApplicationContextHolder.GetApplicationContext().GetObject<IClientProxy>().Get(context.ClientId);
                if (client == null)
                {
                    context.Reject("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                    return default;
                }

                if (client.ApplicationType == ApplicationTypes.NativeConfidential)
                {
                    if (string.IsNullOrWhiteSpace(context.ClientSecret))
                    {
                        context.Reject("invalid_clientId", "Client secret should be sent.");
                        return default;
                    }
                    else
                    {
                        if (client.Secret != HelperMethods.GetHash(context.ClientSecret))
                        {
                            context.Reject("invalid_clientId", "Client secret is invalid.");
                            return default;
                        }
                    }
                }

                if (!client.Active)
                {
                    context.Reject("invalid_clientId", "Client is inactive.");
                    return default;
                }

                return default;
            }));
        }).AddValidation(options =>
        {
            options.UseLocalServer();
            options.UseAspNetCore();
        });
    [HttpPost("~/api/logout")]
    public IActionResult Logout()
    {
        return SignOut(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
    }
Kévin Chalet
@kevinchalet
Where's your handler to validate logout requests? It's mandatory when using the degraded mode.
robertovaldesperez
@robertovaldesperez
Yes, I was missing the handler. thank you
robertovaldesperez
@robertovaldesperez
I am getting this error by logout: The userinfo request was successfully validated.
fail: OpenIddict.Server.OpenIddictServerProvider[0]
The request was rejected because an invalid 'Content-Type' header was specified: application/json.
any idea?
Kévin Chalet
@kevinchalet
The error sounds clear to me?
robertovaldesperez
@robertovaldesperez
What content type should I specify?
Daniel Mangowi
@mangowi

Hello guys,

I've upgrade from 2.1 to 3.0 beta version.

But when I am using the access token that was issued from 'connect/token', to access an Authorize action from the API.

I get unauthorized error, 401. The token is invalid

Errors
PostMan erro Bearer error="invalid_token"

Also when I decode the access token on jwt.io. I get an Invalid Signature

Any ideas on how to solve the issue?

Environment.
ASP.NET Core 3.1 web API, ASP.NET Identity
Openiddict-core 3.0 beta version

Client - PostMan

Thank you in advance.

Startup Gist
https://gist.github.com/mangowi/b2b89d304b1cb9dcbbfb9645a1e51346

@kevinchalet

Kévin Chalet
@kevinchalet
Hey. Remove the JWT handler, the Openddict validation handler is now compatible with JWTs: https://kevinchalet.com/2020/06/11/introducing-openiddict-3-0-beta1/
Kévin Chalet
@kevinchalet
Daniel Mangowi
@mangowi

Hi @kevinchalet , thank you for a quick reply and the reference link.

I did remove the JWT handler just after AddAuthentication()

but what I am experiencing right now is a not found status code 404.
the client (PostMan) can not find the resource controller that has an Authorize filter .

services.AddAuthentication(options =>
{
//options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;

        });

my app confige method

app.UseEndpoints(options =>
{
options.MapControllers();
options.MapDefaultControllerRoute();
});

The client passes the Bearer access_token as part of Authorization header.

Kévin Chalet
@kevinchalet
Decorate your API controller with [Authorize(AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)].
Daniel Mangowi
@mangowi

@kevinchalet thank you so much man.
It works now.

I real appreciate that.. Thank you

Kévin Chalet
@kevinchalet
You're welcome :smile:
Daniel Mangowi
@mangowi
:)
vincesocal
@vincesocal_gitlab
hi I am new with OpenIddict and am very excited to try it out. Been trying to craft together a core-less with the latest 3.0 beta by following examples. One thing I noticed is that HandleTokenRequest is not a part of OpenIddictServerEvents anymore. My question is how do I write an inline handler to return the token back to the client? Really appreciate the help!
Kévin Chalet
@kevinchalet
Hey.
It's still there, but all the classes are now suffixed with Context, like in ASOS.
So the class you're looking for is HandleTokenRequestContext.
vincesocal
@vincesocal_gitlab
here is my implementation, but it does not return the token. what did I do wrong?
                builder.AddEventHandler<OpenIddictServerEvents.HandleTokenRequestContext>(configuration =>
                    configuration.UseInlineHandler(context =>
                    {
                        var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType);
                        identity.AddClaim(Claims.Subject, "Demo User", Destinations.AccessToken, Destinations.IdentityToken);
                        identity.AddClaim(Claims.Role, "demo", Destinations.AccessToken, Destinations.IdentityToken);
                        identity.AddClaim(Claims.Audience, "app-api-bnl", Destinations.AccessToken, Destinations.IdentityToken);

                        var claimsPrinciple = new ClaimsPrincipal(identity);
                        claimsPrinciple.SetScopes(Scopes.OpenId, Scopes.Email, Scopes.Profile, Scopes.Roles);

                        context.Principal = claimsPrinciple;

                        return default;
                    }));
vincesocal
@vincesocal_gitlab
Do I have to manually set the context.Response? How is the context.Response populated before returning to the client?
Kévin Chalet
@kevinchalet
Your snippet is fine. What does it return? Anything interesting in the logs?
vincesocal
@vincesocal_gitlab
@kevinchalet only the following
info: OpenIddict.Server.OpenIddictServerProvider[0]
The token request was successfully extracted: {
"grant_type": "password",
"username": "Demo",
"password": "[redacted]"
}.
info: OpenIddict.Server.OpenIddictServerProvider[0]
The token request was successfully validated.
same thing happened when I used UseInMemoryDatabase with AddCore()
Kévin Chalet
@kevinchalet
Share your Startup, please.
vincesocal
@vincesocal_gitlab
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

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

        // openid
        services.AddOpenIddict()
            // Register the OpenIddict server components.
            .AddServer(builder =>
            {
                // Enable the password flow
                builder.AllowPasswordFlow();

                // Enable the token endpoint
                builder.SetTokenEndpointUris($"/api/v1.0/connect/token");

                // Register the signing and encryption credentials.  Used dev for now until we have a pfx
                builder.AddDevelopmentEncryptionCertificate()
                    .AddDevelopmentSigningCertificate();

                // Register the ASP.NET Core host and configure the ASP.NET Core specific options
                builder.UseAspNetCore()
                    .EnableTokenEndpointPassthrough()
                    .DisableTransportSecurityRequirement(); // During development ONLY!

                #region Disable openiddict core features like database-backed store

                // Enabled, all the features that rely on the OpenIddict application, authorization, scope
                // and token managers (contained in the OpenIddict.Core package) are automatically disabled
                builder.EnableDegradedMode();

                builder.AddEventHandler<OpenIddictServerEvents.ValidateTokenRequestContext>(configuration =>
                    configuration.UseInlineHandler(context =>
                    {
                        if (!context.Request.IsPasswordGrantType())
                        {
                            context.Reject(error: Errors.UnsupportedGrantType, description: "The specified grant type is not supported");
                            return default;
                        }

                        if (string.Compare(context.ClientId, "demo_app", StringComparison.OrdinalIgnoreCase) != 0)
                        {
                            context.Reject(error: Errors.InvalidClient, description: "The specified 'client_id' doesn't match a registered application.");
                            return default;
                        }

                        if (context.Request.Username != "Demo" || context.Request.Password != "DemoTest123!")
                        {
                            context.Reject(error: Errors.InvalidGrant, description: "Invalid username or password");
                            return default;
                        }

                        return default;
                    }));

                builder.AddEventHandler<OpenIddictServerEvents.HandleTokenRequestContext>(configuration =>
                    configuration.UseInlineHandler(context =>
                    {
                        var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType);
                        identity.AddClaim(Claims.Subject, "Demo User", Destinations.AccessToken, Destinat
it seems to be cut off. Paste the set up again
        services.AddOpenIddict()
            // Register the OpenIddict server components.
            .AddServer(builder =>
            {
                // Enable the password flow
                builder.AllowPasswordFlow();

                // Enable the token endpoint
                builder.SetTokenEndpointUris($"/api/v1.0/connect/token");

                // Register the signing and encryption credentials.  Used dev for now until we have a pfx
                builder.AddDevelopmentEncryptionCertificate()
                    .AddDevelopmentSigningCertificate();

                // Register the ASP.NET Core host and configure the ASP.NET Core specific options
                builder.UseAspNetCore()
                    .EnableTokenEndpointPassthrough()
                    .DisableTransportSecurityRequirement(); // During development ONLY!

                #region Disable openiddict core features like database-backed store

                // Enabled, all the features that rely on the OpenIddict application, authorization, scope
                // and token managers (contained in the OpenIddict.Core package) are automatically disabled
                builder.EnableDegradedMode();

                builder.AddEventHandler<OpenIddictServerEvents.ValidateTokenRequestContext>(configuration =>
                    configuration.UseInlineHandler(context =>
                    {
                        if (!context.Request.IsPasswordGrantType())
                        {
                            context.Reject(error: Errors.UnsupportedGrantType, description: "The specified grant type is not supported");
                            return default;
                        }

                        if (string.Compare(context.ClientId, "demo_app", StringComparison.OrdinalIgnoreCase) != 0)
                        {
                            context.Reject(error: Errors.InvalidClient, description: "The specified 'client_id' doesn't match a registered application.");
                            return default;
                        }

                        if (context.Request.Username != "Demo" || context.Request.Password != "DemoTest123!")
                        {
                            context.Reject(error: Errors.InvalidGrant, description: "Invalid username or password");
                            return default;
                        }

                        return default;
                    }));

                builder.AddEventHandler<OpenIddictServerEvents.HandleTokenRequestContext>(configuration =>
                    configuration.UseInlineHandler(context =>
                    {
                        var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType);
                        identity.AddClaim(Claims.Subject, "Demo User", Destinations.AccessToken, Destinations.IdentityToken);
                        identity.AddClaim(Claims.Role, "demo", Destinations.AccessToken, Destinations.IdentityToken);
                        identity.AddClaim(Claims.Audience, "app-api-bnl", Destinations.AccessToken, Destinations.IdentityToken);

                        var claimsPrinciple = new ClaimsPrincipal(identity);
                        claimsPrinciple.SetScopes(Scopes.OpenId, Scopes.Email, Scopes.Profile, Scopes.Roles);

                        context.Principal = claimsPrinciple;
                        context.HandleRequest();

                        return default;
                    }));

                #endregion Disable openiddict core features like database-backed store
            })

            // Register the OpenIddict validation components.
            .AddValidation(options =>
            {
                // Import the configuration from the local OpenIddict server instance
                options.UseLocalServer();
            .AddValidation(options =>
            {
                // Import the configuration from the local OpenIddict server instance
                options.UseLocalServer();

                // Register the ASP.NET Core host
                options.UseAspNetCore();
            });
if I took out by commenting //context.HandleRequest(); I got 404
Kévin Chalet
@kevinchalet
Remove EnableTokenEndpointPassthrough().
It indicates to OpenIddict that you don't want to use the events model to handle token requests and that you want the requests to be handled later in the ASP.NET Core pipeline.
Typically, in a MVC controller.
vincesocal
@vincesocal_gitlab
@kevinchalet thanks Kevin!
Kévin Chalet
@kevinchalet
You're welcome :smile:
@vincesocal_gitlab out of curiosity, are you migrating from ASOS or is it for a completely new app?
vincesocal
@vincesocal_gitlab
@kevinchalet I have been using my own brewed implementation but I found yours! :D
so it is a completely new app
thanks again. It helps!
robertovaldesperez
@robertovaldesperez
hi @kevinchalet is posible decorate a proxy layer (layer between controller layer and services layer) with [Authorize(AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)].
I have four layers Controller, Proxy, Service and Repository
Kévin Chalet
@kevinchalet
Hey. It’s not exactly an OpenIddict-specific question, but anyway: no, that attribute has no effect outside ASP.NET Core. But nothing prevents you from flowing the principal from the controller to your proxy layer.
Alexey
@askalione
Hi, @kevinchalet, i'm trying to use OpenIddict 3.0 and i have two questions:
  1. What i should configure in prod instead of AddDevelopmentEncryptionCertificate()? (i'm new on encryption)
  2. How can i configure scheme name to "Bearer" (for example) instead of OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme ("OpenIddict.Validation.AspNetCore")?