Search code examples
c#.netoauth-2.0asp.net-web-api2asp.net-authorization

Authentication failed - OWIN - OAuth - Webapi 2.0


I have created a WebAPI 2.0 service and a Windows Forms client. I can create a valid token request by the client.

But when I try to use that bearer token for accessing the WebAPI I get the following error:

Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware Error: 0 : Authentication failed Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey, KeyId: 'djaskjd', InternalId: 'djaskjd'. , KeyId: djaskjd '. Number of keys in TokenValidationParameters: '16'. Number of keys in Configuration: '0'. Matched key was in 'TokenValidationParameters'.

Server Validation:

     public partial class Startup
        {
            public void Configuration(IAppBuilder app)
            {
    
                ConfigureAuth(app);
            }
    
            private void ConfigureAuth(IAppBuilder app)
            {
              public void Configuration(IAppBuilder app)
              {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience = ConfigurationManager.AppSettings["Audience"],
                Tenant = ConfigurationManager.AppSettings["Tenant"],
                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidIssuers = new[] { "https://login.microsoftonline.com/{ConfigurationManager.AppSettings[\"Tenant\"]}/v2.0" }
                }
            });
        }            }
        }

Client Authentication

 private static void GetAuth()
        {

            autth = PublicClientApplicationBuilder.Create(ClientId)
                    .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                    .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
                    .Build();
        }

How can I solve the problem?


Solution

  • The client code was correct. Just the scopes was not correct. You have to use the API of the client that references the server / backend.