Identity Server Client:
//wpf sample
new Client
{
ClientId = "native.code",
ClientName = "Native Client (Code with PKCE)",
RedirectUris = { "http://127.0.0.1/sample-wpf-app" },
//PostLogoutRedirectUris = { "https://notused" },
RequireClientSecret = false,
AllowedGrantTypes = GrantTypes.Code,
AllowAccessTokensViaBrowser = true,
RequirePkce = true,
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.OfflineAccess,
"fiver_auth_api"
},
AllowOfflineAccess = true,
//Access token life time is 7200 seconds (2 hour)
AccessTokenLifetime = 7200,
//Identity token life time is 7200 seconds (2 hour)
IdentityTokenLifetime = 7200,
RefreshTokenUsage = TokenUsage.ReUse
}
WPF app:
var options = new OidcClientOptions()
{
//redirect to identity server
Authority = "http://localhost:5000/",
ClientId = "native.code",
Scope = "openid profile offline_access fiver_auth_api",
//redirect back to app if auth success
RedirectUri = "http://127.0.0.1/sample-wpf-app",
ResponseMode = OidcClientOptions.AuthorizeResponseMode.FormPost,
Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
Browser = new WpfEmbeddedBrowser()
};
I am trying to connect the identity server with wpf app but i always get back a 401.
Identity server is running on : http://localhost:5000/
WPF: http://127.0.0.1/sample-wpf-app
I check the token and is the good one. I also enable AllowOfflineAccess = true.
Why do i always get that error?
Edit: Web Api:
var accessToken = token;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
//on button click call Web api Get movies
//Initialize HTTP Client
client.BaseAddress = new Uri("http://localhost:5001");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = client.GetAsync("/movies/get").Result;
MessageBox.Show(response.Content.ReadAsStringAsync().Result);
}
catch (Exception)
{
MessageBox.Show("Movies not Found");
}
WPF app need to be async in order to wait for the answer from api.
Related
I have a Blazor web app that connects to a different Identity Server 4 server. I can get the login to work correctly and pass the access token back the Blazor. However, when the token expires I don't know how to go out and get a new access token? Should I be getting a refresh token and then an access token? I am confused on how this all works.
Blazor Code
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = AzureADDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(AzureADDefaults.AuthenticationScheme, options =>
{
options.Authority = "https://localhost:44382";
options.RequireHttpsMetadata = true;
options.ClientId = "client";
options.ClientSecret = "secret";
options.ResponseType = "code id_token token";
options.SaveTokens = true;
options.Scope.Add("IdentityServerApi");
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Scope.Add("roles");
options.Scope.Add("offline_access");
});
IdentityServer4 Setup
...
new Client
{
ClientId = "client",
ClientSecrets = { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Hybrid,
AllowAccessTokensViaBrowser = true,
RequireClientSecret = true,
RequireConsent = false,
RedirectUris = { "https://localhost:44370/signin-oidc" },
PostLogoutRedirectUris = { "https://localhost:44370/signout-callback-oidc" },
AllowedScopes = { "openid", "profile", "email", "roles", "offline_access",
IdentityServerConstants.LocalApi.ScopeName
},
AllowedCorsOrigins = { "https://localhost:44370" },
AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true,
AllowOfflineAccess = true,
AccessTokenLifetime = 1,//testing
UpdateAccessTokenClaimsOnRefresh = true
},
...
UPDATE:
I have updated my code to offline_access for the client and server (thanks for the update below). My next question is how do I inject the request for the refresh token in Blazor once I get rejected because the access token is expired?
I have the Blazor app making calls back to the API (which validates the access token).
public class APIClient : IAPIClient
{
private readonly HttpClient _httpClient;
//add the bearer token to the APIClient when the client is used
public APIClient(IHttpContextAccessor httpAccessor, HttpClient client, IConfiguration configuration)
{
var accessToken = httpAccessor.HttpContext.GetTokenAsync("access_token").Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestVersion = new Version(2, 0);
client.BaseAddress = new Uri(configuration["Api_Location"]);
_httpClient = client;
_logger = logger;
}
What do I need to add to my API calls to validate?
Yes, you should obtain a refresh token as well to keep getting new access tokens. To get a refresh token from IdentityServer you need to add the 'offline_access' scope in the 'AllowedScopes' property of your client. You also need to set the 'AllowOfflineAccess' property on your client to true.
After that you need to include 'offline_access' to the scopes sent by the client and you should receive a refresh token in the response.
To use the refresh token, send a request to the token endpoint with everything you sent for the code exchange except replace the 'code' param with 'refresh_token' and change the value for 'grant_type' from 'code' to 'refresh_token'. The IdentityServer4 response to this request should contain an id_token, an access_token, and a new refresh_token.
I think I have found an answer (given the push from Randy). I did something familiar to this post, where I created a generic method in my APIClient.
public async Task<T> SendAsync<T>(HttpRequestMessage requestMessage)
{
var response = await _httpClient.SendAsync(requestMessage);
//test for 403 and actual bearer token in initial request
if (response.StatusCode == HttpStatusCode.Unauthorized &&
requestMessage.Headers.Where(c => c.Key == "Authorization")
.Select(c => c.Value)
.Any(c => c.Any(p => p.StartsWith("Bearer"))))
{
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "refresh_token"),
new KeyValuePair<string, string>("refresh_token", _httpAccessor.HttpContext.GetTokenAsync("refresh_token").Result),
new KeyValuePair<string, string>("client_id", "someclient"),
new KeyValuePair<string, string>("client_secret", "*****")
};
//retry do to token request
using (var refreshResponse = await _httpClient.SendAsync(
new HttpRequestMessage(HttpMethod.Post, new Uri(_authLocation + "connect/token"))
{
Content = new FormUrlEncodedContent(pairs)})
)
{
var rawResponse = await refreshResponse.Content.ReadAsStringAsync();
var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Data.Models.Token>(rawResponse);
var info = await _httpAccessor.HttpContext.AuthenticateAsync("Cookies");
info.Properties.UpdateTokenValue("refresh_token", x.Refresh_Token);
info.Properties.UpdateTokenValue("access_token", x.Access_Token);
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", x.Access_Token);
//retry actual request with new tokens
response = await _httpClient.SendAsync(new HttpRequestMessage(requestMessage.Method, requestMessage.RequestUri));
}
}
if (typeof(T).Equals(typeof(HttpResponseMessage)))
return (T)Convert.ChangeType(response, typeof(T));
else
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync());
}
I don't like that I have to call AuthenticateAsync. Yet, that seems to be the way I have found to get access to the UpdateTokenValue method to delete and then re-add the new access token.
I am implementing EF for Identity framework 4 so that i can store tokens in database. My question is, does it store code, Access token and Refresh token all in database (http://docs.identityserver.io/en/latest/reference/ef.html).
After i implemented code from the document link, that i pasted above, i am getting refresh token data in database but not access token. Also when i try to get a new access token from refresh token, i get new refresh token as well for which i dont see a new entry in database (PersistedGrants) table.
StartUp:
services.AddIdentityServer()
.AddDeveloperSigningCredential(filename: "key.rsa")
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString);
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30; // interval in seconds
})
.AddConfigurationStoreCache()
Client:
ClientId = "testclient",
ClientName = "testclient",
ClientSecrets = { "password" },
AllowedGrantTypes = GrantTypes.Implicit,
RequireConsent = false,
RedirectUris = { "https://testapp.azurewebsites.net/signin-oidc"},
PostLogoutRedirectUris = { "https://testapp.azurewebsites.net/signout-callback-oidc" },
FrontChannelLogoutUri = "https://testapp.azurewebsites.net/FrontChannelLogout",
//FrontChannelLogoutUri = "https://testapp.azurewebsites.net/signout-callback-oidc",
AllowedScopes = new List<string>
{
"OpenId",
"Profile",
},
AllowOfflineAccess = true
My JavaScript SignalR client routinely connects to my asp.net core implementation of IdentityServer4.
On the client I see:
Information: WebSocket connected to wss://localhost:5001/signal/satellite?
idsrv.session=4ec93d2f4c3b9a970ff82a537ae04d97&id=0eUBg2-xobp4CNttuIQJcg
But, it also doesn't connect much of the time, with an error that there was an unexpected token in JSON at position 0.
It seems like it runs well for a bit and then poorly, even if I re-login, it still throws the error. In the browser, the call always looks more or less like:
https://localhost:5001/signal/satellite?
idsrv.session=89364018a975e4fefff9ad0869b1ae09
I don't seem to need the middleware for it to move the querystring value into the header, I still get the user in my hub during onConnect with their sub claim, etc. However, if I do put in the middleware before app.UseAuthentication() and watch for:
context.Request.QueryString.Value
when it successfully handshakes with the server, I see:
idsrv.session=89364018a975e4fefff9ad0869b1ae09
but when it doesn't, I see this:
?client_id=internal&redirect_uri=https%3A%2F%2Flocalhost%3A5001%2Fsignin-oidc&response_type=code%20id_token&scope=openid%20profile%20offline_access%20Harvey&response_mode=form_post&nonce=636817245670169226.ZWM2OWQ0ZWEtOTQzMC00YTJlLWI4MzQtYmIxZDZjOWVlYjg5ZTA4NTU2M2QtNjczZi00MTlmLThjYmQtZWUzZTQ1ODMzNDQ0&state=CfDJ8MCxOjJiJLdKqZrnPwOHDhqMnzWz6MqRb03SxToClqQ1F3n9g8yLdW683HRpZSHd-5wkN-6je4tHJkA8sc5i6YoKRxtMHwnWqxVW5-nXFaaH0TfOLUeqfxDzXLxnftmWFXLjK3Y7b6R2WzcDLEjChU1_Fk6X64SAHNRqeizGDPzRhxpV0U5w19Bbt7pUyRbYymn2WNedCS1F7g_wtwtJXDjCzWKBxqvPZ5Dtg99gxKkANalKYs7C4-fm7YdD0gFvsuV4CXsu0T06MjzID_zpA_F7TmSue4vGI-0_qY55Swc5mbLWUwKHtj6ZTfOG4UmTEP_hbj2PO9w2oNg9TWqTPtDC3-qSl1fTUkY0EtCwbA7F&x-client-SKU=ID_NETSTANDARD1_4&x-client-ver=5.2.0.0
so I'm stuck either not needing to do it because it succeeds on its own or the querystring never makes it to the middleware to move over (which is probably why it can't do it on its own)
What am I missing for it to consistently work?
Add Hybrid Client to IdentityServer4:
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
AllowOfflineAccess = true
}
and then in startup on the mvc client:
ServiceCollection.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "https://localhost:5001";
options.RequireHttpsMetadata = false;
options.ClientSecret = "secret";
options.ClientId = "mvc";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("offline_access");
options.Scope.Add("api1");
options.ClaimActions.MapJsonKey("website", "website");
});
This is modeled after the example: Quickstart5_HybridAndApi
In SignalR on server:
[Authorize]
public class SignalRSignalHub : Hub
{
public override Task OnConnectedAsync()
{
var context = Context.GetHttpContext();
return base.OnConnectedAsync();
}
}
SignalR JavaScript Client:
self.signalRConnection = new signalR.HubConnectionBuilder()
.withUrl("/signal/satellite?" + document.cookie).build();
I can not get ClaimsPrincipal after login in azure Ad Web API,
Below is my code added in startup.auth.cs
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Scope= OpenIdConnectScope.OpenIdProfile,
ResponseType = OpenIdConnectResponseType.IdToken,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
return Task.FromResult(0);
}
},
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false
},
});
I get Access Token in
result = await authContext.AcquireTokenAsync(todoListResourceId, clientCredential);
but can not get ClaimsPrincipal. I get AuthenticationType = null, IsAuthenticated = null, Name = null.
My application use adal.js for UI side to get user information, and get user information successfully.
I got Solution for this problem.replace startup.auth.cs code with
app.UseWindowsAzureActiveDirectoryBearerAuthentication( new WindowsAzureActiveDirectoryBearerAuthenticationOptions { TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true, ValidAudience = ConfigurationManager.AppSettings["ida:ClientId"], AuthenticationType = "Bearer" }, Tenant = ConfigurationManager.AppSettings["ida:Tenant"], });
this code and it working fine
Does identity server 4 doesn't allow implicit flow to access API Resource.
Identity Server 4 config.cs
new Client
{
ClientId = "implicit",
ClientName = "Implicit Client",
AllowAccessTokensViaBrowser = true,
RedirectUris = { "https://notused" },
PostLogoutRedirectUris = { "https://notused" },
FrontChannelLogoutUri = "http://localhost:5000/signout-idsrv", // for testing identityserver on localhost
AccessTokenLifetime = 10,
AllowedGrantTypes = GrantTypes.Implicit,
AllowedScopes = { "openid", "profile", "email", "ProxyServer", "api" }
}
Api Resouce
new ApiResource("api", "Custom"),
new ApiResource("ProxyServer", "Proxy Server")
In Mvc Client I am using this code ConfigureServices
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
})
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.Cookie.Name = "mvcimplicit";
})
.AddOpenIdConnect("oidc", options =>
{
options.Authority = Constants.Authority;
options.RequireHttpsMetadata = false;
options.ClientId = "implicit";
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("ProxyServer");
options.Scope.Add("profile");
options.Scope.Add("email");
options.SaveTokens = true;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role,
};
});
When I try in browser I get "Sorry, there was an error : invalid_scope ". But if I remove options.Scope.Add("ProxyServer"); it works fine and Identity server 4 take me to login page.
OK I found the issue but posting just in case someone else face the same problem.
Response type needs to be specified explicitly otherwise it wont work.
options.ResponseType = "id_token token";
Modify the response type accordingly.