Getting DiscoveryClient fails with "Issuer name does not match authority" - asp.net

I get the error below when performing a GET using IdentityModel's DiscoveryClient as follows:
var discoveryResponse = await DiscoveryClient.GetAsync("https://localhost/IdentityServer");
Issuer name does not match authority: https://localhost/identityserver
The target URL is an ASP.NET Core web application running on IIS enabled with IdentityServer4. The client application is a classic ASP.NET web application running on the same machine.
Apparently, the GET did manage to retrieve values from the IdentityServer as evidenced by the contents of discoveryResponse.Raw:
{
"issuer": "https://localhost/identityserver",
"jwks_uri": "https://localhost/IdentityServer/.well-known/openid-configuration/jwks",
"authorization_endpoint": "https://localhost/IdentityServer/connect/authorize",
"token_endpoint": "https://localhost/IdentityServer/connect/token",
"userinfo_endpoint": "https://localhost/IdentityServer/connect/userinfo",
"end_session_endpoint": "https://localhost/IdentityServer/connect/endsession",
"check_session_iframe": "https://localhost/IdentityServer/connect/checksession",
"revocation_endpoint": "https://localhost/IdentityServer/connect/revocation",
"introspection_endpoint": "https://localhost/IdentityServer/connect/introspect",
"frontchannel_logout_supported": true,
"frontchannel_logout_session_supported": true,
"scopes_supported": [ "CustomIdentityResources", "profile", "openid", "MyAPI.full_access", "offline_access" ],
"claims_supported": [],
"grant_types_supported": [ "authorization_code", "client_credentials", "refresh_token", "implicit" ],
"response_types_supported": [ "code", "token", "id_token", "id_token token", "code id_token", "code token", "code id_token token" ],
"response_modes_supported": [ "form_post", "query", "fragment" ],
"token_endpoint_auth_methods_supported": [ "client_secret_basic", "client_secret_post" ],
"subject_types_supported": [ "public" ],
"id_token_signing_alg_values_supported": [ "RS256" ],
"code_challenge_methods_supported": [ "plain", "S256" ]
}

authority: https://localhost/IdentityServer
issuer: https://localhost/identityserver
They do not match - it's case sensitive.

In the case when you are unable to change the server code to suit the policy, you can change the policy settings to allow name mismatches.
For example, I am attempting to use DiscoveryClient on the Azure Rest API, and the issuer is https://sts.windows.net/{{ tenant_id }} while the endpoints all start with https://login.microsoft.com/{{ tenant_id }}.
Simply set the fields ValidateIssuerName and ValidateEndpoints to false.
var tenant_id = "8481D2AC-893F-4454-8A3B-A0297D301278"; // Made up for this example
var authority = $"https://login.microsoftonline.com/{tenant_id}";
DiscoveryClient discoveryClient = new DiscoveryClient(authority);
// Accept the configuration even if the issuer and endpoints don't match
discoveryClient.Policy.ValidateIssuerName = false;
discoveryClient.Policy.ValidateEndpoints = false;
var discoResponse = await discoveryClient.GetAsync();
Later Edit
Since this message was posted the DiscoveryClient class has been deprecated.
Here is the new calling syntax:
var client = new HttpClient();
var discoResponse = await client.GetDiscoveryDocumentAsync(
new DiscoveryDocumentRequest
{
Address = authority,
Policy =
{
ValidateIssuerName = false,
ValidateEndpoints = false,
},
}
);

Other answers address the client - making it accept the lowercase issuer.
This changes the case of the issuer in the discovery document:
By default Identity Server seems to change the issuer Uri to lowercase. This leads to the discovery document having lower case for the issuer; and the case you typed in code/publishing for everything else.
I fixed this in my Identity Server app, Startup, ConfigureServices method
var builder = services.AddIdentityServer(options => { options.LowerCaseIssuerUri = false; })
Using this means the case of the issuer in the discovery document is the same as for all the other Uris

This error also happens if the URL of the request to the Discovery Client (or in my case the URL used for introspection of the access tokens during validation) contains escaped spaces (i.e., "%20" rather than " "), which kind of makes sense if the URLs are being compared exactly within Identity Server.

Related

Request ignored because of CORS in IdentityServer4

I have 3 projects:
Client App
ASP.NET API App
IdentityServer4 MVC App
I am able to send a request from API to IDP but trying to send a request from Client to IDP yields
"CORS request made for path: /api/Trial/TrialAction from origin: https://localhost:44389 but
was ignored because path was not for an allowed IdentityServer CORS endpoint"
even though I added the following to the IDP:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", policyBuilder => policyBuilder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
and
// ...
app.UseRouting();
app.UseIdentityServer();
app.UseCors("CorsPolicy");
app.UseAuthorization();
// ...
The interesting part is, I can send a request from API to IDP without adding CORS configuration to IDP. What am I doing wrong?
Config.cs:
public static class Config
{
public static IEnumerable<IdentityResource> Ids =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
};
public static IEnumerable<ApiResource> Apis =>
new ApiResource[]
{
new ApiResource("myapi",
"My API",
new [] { "membershipType" }
)
};
public static IEnumerable<Client> Clients =>
new Client[]
{
new Client
{
ClientId = "mywebclient",
ClientName = "My Web Client",
AllowedGrantTypes = GrantTypes.Code, // Authorization code flow with PKCE protection
RequireClientSecret = false, // Without client secret
RequirePkce = true,
RedirectUris = { "https://localhost:44389/authentication/login-callback" },
PostLogoutRedirectUris = { "https://localhost:44389/authentication/logout-callback" },
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"albidersapi"
},
AllowedCorsOrigins = { "https://localhost:44389" },
RequireConsent = false,
}
};
}
do yo have the client and API in the same project as IdentityServer? I typically recommend that you keep them apart.
A wild guess could be to swap these two lines:
app.UseIdentityServer();
app.UseCors("CorsPolicy");
Because apparently IdentityServer captures the request to the API?
The most likely issue is that your call from your client to your API is not including the access token.
The debug log is coming from this file here. If you look at where your debug statement is originating from you will see that it is checking if the path matches any within IdentityServerOptions.Cors.CorsPaths. Here is an image of what those paths generally are from a debug service I made.
These paths are just the default information and authentication endpoints for IdentityServer4. In other words it thinks your request is unauthenticated because it likely isn't including the access token.
If you are using IdentityServer4's template logging implementation with Serilog, then you can also add this to your appsettings.json to see what the ASP.NET Core CORS middleware has to say. It will be logging after IdentityServer4's log
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.AspNetCore.Authentication": "Debug",
"Microsoft.AspNetCore.Cors": "Information",
"System": "Warning"
}
}
}
Here is what my debug log looked like when I made a request to an endpoint with a proper CORS policy, but the request didn't include its access token.
[21:05:47 Debug] IdentityServer.Hosting.CorsPolicyProvider CORS request made for path: /api/v1.0/users/{guid}/organizations from origin: https://localhost:44459 but was ignored because path was not for an allowed IdentityServer CORS endpoint
[21:05:47 Information] Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware No CORS policy found for the specified request.
So it's not a CORS issue really. It's an access token or authentication issue. It is also possible, however, that your endpoint isn't being hit properly. However, you should be receiving a 404 on the client in addition to the log seen above.

ASP.NET Boilerplate Identity Server API Access Token

I have successfully enabled Identity Server in ASP.Net Boilerplate and called it with a JS client as described by Identity Server docs http://docs.identityserver.io/en/latest/quickstarts/6_javascript_client.html . After logging on and getting an access token I cannot use this access token to access the API as I get 401.
I was unable to complete the final step as shown by Identity Server example. Because My projects throws an error on startup saying Identityserver already registered. I am assuming without this step my token is not generated correctly. However have not been able to work out how I should configure ABP to do the same thing.
services.AddAuthentication("Bearer").AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
Any help appreciated :)
The exact error I get is 401 (Unauthorized). If i exchange the token for one generated through /api/TokenAuth/Authenticate the call works.
The Token generated through Identity server is "eyJhbGciOiJSUzI1NiIsImtpZCI6IjNhODAzNTUzNzNlNDVhMzRmNTI3MzJmM2ZjZWNjZTQ4IiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NTExNTgyMjYsImV4cCI6MTU1MTE2MTgyNiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo2MjExNCIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NjIxMTQvcmVzb3VyY2VzIiwiY2xpZW50X2lkIjoianMiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTUxMTU3MTcwLCJpZHAiOiJsb2NhbCIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiXSwiYW1yIjpbInB3ZCJdfQ.LBJ5KfiOGjMSWlpsWbXLuGBnd0RHq07IWM7npYGPOBm38ENeZkzLErgwalTFH7acOOa8rHymfTFRBVQgO1sEy-nnxn-iPmjstKABu2Xe1o-qlsrU7K7mxN1FLKJWksWBty983TZ-WLrK9pXEHjN9LGeBFY-Qx_RPFOVu4gattjgNI05-J3a2dsnON_bJfvsXPL2ktUa_od-uqi9AXnWY_kJA-5xh1rjMP6pf740tMQJjhMGAIitQHbWiCfmvvPjX6bzBnMXFJpmiVT_hZsZ76zoQskLRQz8Zn-IfVhU9VM-8U7B6PKUaVFs4-VA2ia9VVwxuSs1gJoC9RwMqKYmX_g"
My Client is being registered with these properties.
var client = new Client
{
ClientId = "js",
ClientName = "JavaScript Client",
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = true,
RequireClientSecret = false,
RequireConsent = true,
RedirectUris = { "http://localhost:5003/callback.html" },
PostLogoutRedirectUris = { "http://localhost:5003/index.html" },
AllowedCorsOrigins = { "http://localhost:5003" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"Apps"
}
};

identityserver4 with redux -oidc client requested access token - but client is not configured to receive access tokens via browser

My identityserver4 client looks like this:
new Client {
ClientId = "openIdConnectClient",
ClientName = "Example Implicit Client Application",
//AllowedGrantTypes = GrantTypes.Implicit,
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowOfflineAccess = true,
AllowAccessTokensViaBrowser = true,
AccessTokenLifetime = 30,
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"role",
"customAPI.write"
},
RedirectUris = new List<string> {"http://localhost:8080/callback"},
PostLogoutRedirectUris = new List<string> {"https://localhost:44330"},
AllowedCorsOrigins = new List<string>
{
"http://127.0.0.1:8080",
"http://localhost:8080",
"*"
},
}
In react application, my userManager class looks like this:
import { createUserManager } from 'redux-oidc';
const userManagerConfig = {
client_id: 'openIdConnectClient',
redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}/callback`,
//response_type: 'code id_token token',
response_type: 'token id_token',
scope: 'openid profile email role',
authority: 'http://localhost:50604',
silent_redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}/silent_renew.html`,
automaticSilentRenew: true,
filterProtocolClaims: true,
loadUserInfo: true,
};
const userManager = createUserManager(userManagerConfig);
export default userManager;
The question is: when i try to call my identityserver4 from the redux-oidc example application. I'm getting the following error:
Client requested access token - but client is not configured to receive access tokens via browser
I hope you understood the question. Please someone help me with this. i have provided the link for this example application bellow.
Redux-oidc example app link
Your code contains two different grant types. The different Grant types in Identity server 4 have different requirements. Here is a bit of information to help you understand the different types you are using. It may also help you understand why you were having this problem.
GrantTypes.ClientCredentials
The Client credentials is the simplest grant type and is used for server to server communication - tokens are always requested on behalf of a client, not a user.
With this grant type you send a token request to the token endpoint, and get an access token back that represents the client. The client typically has to authenticate with the token endpoint using its client ID and secret.
new Client
{
ClientId = "client",
// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.ClientCredentials,
// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},
// scopes that client has access to
AllowedScopes = { "api1" }
}
GrantTypes.Implicit
The implicit grant type is optimized for browser-based applications. Either for user authentication-only (both server-side and JavaScript applications), or authentication and access token requests (JavaScript applications).
In the implicit flow, all tokens are transmitted via the browser, and advanced features like refresh tokens are thus not allowed. If you want to transmit access tokens via the browser channel, you also need to allow that explicitly on the client configuration:
Client.AllowAccessTokensViaBrowser = true;
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.Implicit,
// where to redirect to after login
RedirectUris = { "http://localhost:5002/signin-oidc" },
// where to redirect to after logout
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
},
AllowAccessTokensViaBrowser = true
}

Multiple Authentication Middlewares ASP.NET Core

I am relatively new to the concept of middlewares. I am aware that a middleware calls the next middleware when it completes.
I am trying to authenticate a request using either Google or my Identity Server. The user can login on my mobile app with google or a local account. However, I can't figure out how to use both authentication middlewares. If I pass the id_token for google, it passes on the first middleware (UseJwtBearerAuthentication) but fails on the second one (UseIdentityServerAuthentication). How can I make it so that it doesn't throw error when it actually passes on at least 1 authentication middleware? For example, if it passes on the first middleware, the second middleware is ignored?
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
Authority = "https://accounts.google.com",
Audience = "secret.apps.googleusercontent.com",
TokenValidationParameters = new TokenValidationParameters()
{
ValidateAudience = true,
ValidIssuer = "accounts.google.com"
},
RequireHttpsMetadata = false
});
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:1000/",
RequireHttpsMetadata = false,
ScopeName = "MyApp.Api"
});
Normally, when an authentication middleware is failed(i don't mean throwing exception), this doesn't affect another successful authentication middleware. Probably your second middleware throws an exception(not a validation failure). First check error message and try to resolve it. If you can't, use AuthenticationFailed event to handle error. In this case your code should be something like below:
app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
// ...
Events = new JwtBearerEvents()
{
OnAuthenticationFailed = async (context) =>
{
if (context.Exception is your exception)
{
context.SkipToNextMiddleware();
}
}
}
});
However, for your scenerio i wouldn't choose your way. I would use only identity server endpoint. For signing with google you can configure identity server like below:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
AutomaticAuthenticate = false,
AutomaticChallenge = false
});
app.UseGoogleAuthentication(new GoogleOptions
{
AuthenticationScheme = "Google",
SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
ClientId = "",
ClientSecret = ""
});
app.UseIdentityServer();
Edit
It seems AuthenticationFailed event couldn't be used for IdentityServer4.AccessTokenValidation. I am not sure but if you will use identity server for only jwt token, you can use UseJwtBearerAuthentication for validation.

UseIdentityServerBearerTokenAuthentication is not working for IdentityServer3

I have used the IdentityServer v3, now I want one website to be both the identity host and the web api host.
The authority option is not used to validate the token. I have verified the token endpoint and the token validation endpoint is working as expected (I can get and validate a token using postman). I used the [Authorize] attribute to decorate my controller method. Full logging is enabled on IdentityServer, nothing is logged when making an api request with a header name 'Authorization' with the value like 'Bearer mytokenhere'.
This is a vNext website on ASP.NET 5 using the Visual Studio 2015 CTP6.
app.UseMvc();
var certFile = AppDomain.CurrentDomain.BaseDirectory + "\\myawesomesite.pfx";
app.Map("/core", core =>
{
var factory = InMemoryFactory.Create(
users: Users.Get(),
clients: Clients.Get(),
scopes: Scopes.Get());
var idsrvOptions = new IdentityServerOptions
{
SiteName = "Lektieplan",
Factory = factory,
RequireSsl = false,
SigningCertificate = new X509Certificate2(certFile, "lektieplan"),
CorsPolicy = CorsPolicy.AllowAll,
LoggingOptions = new LoggingOptions { EnableWebApiDiagnostics = true,EnableHttpLogging = true, IncludeSensitiveDataInLogs = true, WebApiDiagnosticsIsVerbose = true }
};
core.UseIdentityServer(idsrvOptions);
});
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://localhost:57540/core",
RequiredScopes = new[] { "api1" },
});
And my project.json
My dependencies:
"Microsoft.AspNet.Server.IIS": "1.0.0-beta3",
"Microsoft.AspNet.Mvc": "6.0.0-beta3",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta3",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta3",
"Thinktecture.IdentityServer3": "1.3.0.0",
"Microsoft.AspNet.Owin": "1.0.0.0-beta3",
"Microsoft.AspNet.Security.DataProtection": "1.0.0.0-beta3",
"Thinktecture.IdentityServer3.AccessTokenValidation": "1.2.2",
"Autofac": "4.0.0-alpha1",
"log4net": "2.0.3"
I seems to me that some of the provided samples works because of a cookie based option. I don't want to use the cookies.
Is UseIdentityServerBearerTokenAuthentication your only auth type? Do you have any filters defined for MVC?
I would try to split the apps into separate katana pipelines, so they don't conflict at all.
Pseudo:
app.Map("/core", a => a.UseIdsrv());
app.Map("/somethingweb", a => a.UseMvc());
app.Map("/api", a => {
a.UseBearerTokenAuth();
a.UseWebApi(); //or Mvc from now on, with v5
});
Guessing you would need to add cookieauth to that mvc pipeline as well, depending on what you want to achieve.

Resources