Identityserver unauthorized_client error in implicit flow - asp.net

My Identity Server works well in some weeks after that I have gotten an unauthorized_client error, I don't know why.
Identity Server host in http://localhost:5001
Angular Started with .Net Core project in http://localhost:4200
The exact error is:
Sorry, there was an error: unauthorized_client
Unknown client or client not enabled
In the Identity Server, my client defined as follow:
var clients = new List<Client>
{
new Client
{
ClientId = "app.spa.client",
ClientName = "Client Application",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RequireConsent = false,
RedirectUris =
{
"http://localhost:4200/assets/oidc-login-redirect.html",
"http://localhost:4200/assets/silent-redirect.html"
},
PostLogoutRedirectUris = { "http://localhost:4200/?postLogout=true" },
AllowedCorsOrigins = new[] { "http://localhost:4200/" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"webapi"
},
IdentityTokenLifetime = 120,
AccessTokenLifetime = 120
}
};
And in Angular project, I'm using from oidc-client and my config is like follow:
var config = {
authority: "http://localhost:5001/",
client_id: "app.spa.client",
redirect_uri: `http://localhost:4200/assets/oidc-login-redirect.html`,
scope: "openid profile webapi",
response_type: "id_token token",
post_logout_redirect_uri: `http://localhost:4200/?postLogout=true`,
userStore: new WebStorageStateStore({ store: window.localStorage }),
automaticSilentRenew: true,
silent_redirect_uri: `http://localhost:4200/assets/silent-redirect.html`
};
Have you ever been this error?
How I can find more details of this error?

Actually, I found the problem, The IdentityServer4 package in Identity service updated from version 2.4.0 to 2.5.0 but I can't resolve this problem.
Eventually, I'm forced to be down-grade to 2.4.0 version and my problem solved.
Any Idea to solve this problem in IdentityServer4 version 2.5.0?

Related

Correlation failed on Identity Server 4

I have an Identity Server 4 configured with OpenIdConnect to Azure AD.
When user clicks on login button, IS4 redirects to Azure AD and on callback to IS4, it shows this error:
This is how I request token from postman:
Note that callback url is mobile application format.
This is my configuration:
services.AddAuthentication()
.AddCookie(options => new CookieAuthenticationOptions
{
ExpireTimeSpan = TimeSpan.FromHours(12),
SlidingExpiration = false,
Cookie = new CookieBuilder
{
Path = "",
Name = "MyCookie"
}
}).AddOpenIdConnect(options =>
{
options.ClientId = configuration["OpenIdConnect:ClientId"];
options.Authority = configuration["OpenIdConnect:Authority"];
options.SignedOutRedirectUri = configuration["OpenIdConnect:PostLogoutRedirectUri"];
options.CallbackPath = configuration["OpenIdConnect:CallbackPath"];
options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
options.Resource = configuration["OpenIdConnect:Resource"];
options.ClientSecret = configuration["OpenIdConnect:ClientSecret"];
options.SaveTokens = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
});
And this are my parameters:
"OpenIdConnect": {
"ClientId": "xxxxxxxxxx",
"Authority": "https://login.microsoftonline.com/xxxxxxxxxx/",
"PostLogoutRedirectUri": "https://uri-of-my-identity-server.azurewebsites.net",
"CallbackPath": "/signin-oidc",
"ResponseType": "code id_token",
"Resource": "https://graph.microsoft.com/",
"ClientSecret": "my-secret"
},
Note: this error only occurs on Azure environment (not locally)
Note: on Xamarin application, when Azure returns to IS4 consent screen, it shows this message:
It could be that there is an issue with the networking between your client and Azure. A certain port has not been opened or a load balancer is in between.
When decryption fails, state is null, thus resulting in a Correlation failed: state not found error. In our case, decryption failed because different keys were used for encryption/decryption, a pretty common problem when deploying behind a load balancer.

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

WordPress Login via Identity Server 4

Wordpress is to be given the opportunity to log on via Identity Server 4: We have entered the necessary data in Wordpress (most recently with the plugin "OAuth Single Sign On - SSO (OAuth client)") and tried to address the Identity Server. Please note the picture attached.
Settings of the WordPress plugin:
Unfortunately we always get the message
Error: Sorry, there was an error : unauthorized_client. The plugin
sends the following request URL:
http://yyyyyy.com/connect/authorize?client_id=wp-internal&scope=openid%20email&redirect_uri=https://xxxxxx.com/wp-admin/admin-ajax.php?action=openid-connect-authorize&response_type=code&state=V29yZHByZXNzIENsaWVudCBJbnRlcm5hbA===
As far as we can see, the statement is correct - and now we have no meaningful idea what we can do. Can you help or do you have an idea?
Configuration on IdentityServer4 is:
new Client
{
ClientId = "wp-internal",
ClientName = "Wordpress Client Internal",
AllowedGrantTypes = GrantTypes.Code,
AllowAccessTokensViaBrowser = false,
RequireConsent = true,
ClientSecrets =
{
new Secret("#dfmsgmwpgdidsa2019".Sha256())
},
RedirectUris = { "https://xxxxxx.com/wp-admin/admin-ajax.php?action=openid-connect-authorize" },
PostLogoutRedirectUris = { "https://xxxxxx.com/" },
FrontChannelLogoutUri = "https://xxxxxx.com/logout",
LogoUri = "https://xxxxxx.com/logout",
AllowedCorsOrigins = { "https://xxxxxx.com" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email
},
AllowOfflineAccess = true,
AlwaysIncludeUserClaimsInIdToken = true
},

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
}

Getting DiscoveryClient fails with "Issuer name does not match authority"

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.

Resources