1

I'm using OIDC client and I'm calling below line to siginin,

await this.userManager.signinRedirect(this.createArguments(state));
            return this.redirect();

after this I see in the network tab it is navigated to:

https://localhost:5001/connect/authorize?client_id=WebPriorTrainingAuth&redirect_uri=https%3A%2F%2Flocalhost%3A5001%2Fauthentication%2Flogin-callback&response_type=code&scope=openid%20profile&state=9a061d073a424b76bfee25c9bad535d4&code_challenge=ElP_Qtwl8skk13ZyhkzWbnQqU04Y_xYAQXN09cyLY_E&code_challenge_method=S256&response_mode=query

with an error message:

error:invalid_request
error_description:The specified 'redirect_uri' is not valid for this client application.
error_uri:https://documentation.openiddict.com/errors/ID2043

This should have redirected to /Account/Login page (https://localhost:5001/Account/Login?ReturnUrl=%2Fconnect%2) I guess, but that is not happening. Can someone pls help on this?

In the Authorizationcontroller, the client parameters will have the below value set.

var result = new Dictionary<string, string>();

            var application = await applicationManager.FindByClientIdAsync(clientId, cancellationToken);
            if (application != null)
            {
                result.Add("authority", httpContext.GetBaseUrl());
                result.Add("client_id", application.ClientId);
                result.Add("redirect_uri", "https://localhost:5001/authentication/login-callback");
                result.Add("post_logout_redirect_uri", "https://localhost:5001/authentication/logout-callback");
                result.Add("response_type", "code");
                result.Add("scope", $"openid profile");
                //result.Add("response_mode", "query");
            }

            return result;

In the startup.cs, the below code for OpenIddict settings,

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => 
                {
                    options.LoginPath = "/Identity/Account/Login";
                    options.LogoutPath = "/Identity/Account/Logout";
                })
                .AddOpenIdConnect(options =>
                {
                    options.SignInScheme = "Cookies";
                    options.ForwardSignIn = "Cookies";

                    options.Authority = baseUrl;
                    options.SignedOutRedirectUri = baseUrl;

                    options.ClientId = AuthenticationClient.WebClientId;

                    options.RequireHttpsMetadata = true;
                    options.GetClaimsFromUserInfoEndpoint = true;
                    options.SaveTokens = true;
                    options.UsePkce = true;

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

                    options.Scope.Add(Scopes.OpenId);
                    options.Scope.Add(Scopes.Profile);
                    options.Scope.Add(AuthenticationClient.WebClientApiScope);

                    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";


                    options.Events = new OpenIdConnectEvents
                    {

                        /// Add Code Challange
                        OnRedirectToIdentityProvider = context =>
                        {
                            /// Set ProjectId
                            context.ProtocolMessage.SetParameter("project_id", context.HttpContext.User.Identity.Name);
                            
                            /// Only modify requests to the authorization endpoint
                            if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                            {
                                /// Generate code_verifier
                                var codeVerifier = CryptoRandom.CreateUniqueId(32);

                                /// Store codeVerifier for later use
                                context.Properties.Items.Add("code_verifier", codeVerifier);

                                /// Create code_challenge
                                string codeChallenge;
                                using (var sha256 = SHA256.Create())
                                {
                                    var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                                    codeChallenge = Base64Url.Encode(challengeBytes);
                                }

                                /// Add code_challenge and code_challenge_method to request
                                context.ProtocolMessage.Parameters.Add("code_challenge", codeChallenge);
                                context.ProtocolMessage.Parameters.Add("code_challenge_method", "S256");
                            }

                            return Task.CompletedTask;
                        },

Can some one pls tell me why the signinredirect call is not redirecting to /Account/Login page?

fighter code
  • 11
  • 1
  • 3

3 Answers3

1

This error is returned when the specified redirect_uri is not recognized by OpenIddict.

Are you sure you added https://localhost:5001/authentication/login-callback to the list of allowed redirect_uris for your WebPriorTrainingAuth client?

Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
0

I think the redirect URL should be to the Callbackpath of the OpenIDConnect handler in the ASP.NET core client. This path is by default set to:

CallbackPath = new PathString("/signin-oidc");

This is the path where the autorization code is sent to after a successfull authentication in IdentityServer.

See the source code here:

Tore Nestenius
  • 16,431
  • 5
  • 30
  • 40
  • options.CallbackPath = new PathString("/authentication/login-callback"); I have tried this didnot work – fighter code May 07 '21 at 04:05
  • The redirct must be to /signin-oidc, this is a special URL that the OpenIDConnect handler listens for and it must be the recipient of this request. As OpenIDConnect starts the authentication flow, it also needs to end it. – Tore Nestenius May 07 '21 at 07:11
0

I know this is an old question and already answered .. and this answer not for this case.
But you are a new user getting this error message and you are working on 127.0.0.1 .... please make sure that your OpenIddictApplication has localhost AND 127.0.0.1 as valid rediect urls in RedirectUris list.

TECNO
  • 162
  • 2
  • 3
  • 15