The specified 'redirect_uri' is not valid for this client application

12.5k Views Asked by At

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?

3

There are 3 best solutions below

2
On

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:

0
On

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?

0
On

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.