How to read external identity from the temporary cookie in .net core 2 - identityserver4

[HttpGet("ExternalLoginCallback")]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl)
{
// read external identity from the temporary cookie
var info = await HttpContext.Authentication.GetAuthenticateInfoAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
var tempUser = info?.Principal;
if (tempUser == null)
{
throw new Exception("External authentication error");
}
// retrieve claims of the external user
var claims = tempUser.Claims.ToList();
This is the snippet of external login callback using IdentityServer4. I have migrated to .net core 1 to 2 and i am getting warning HttpContext.Authentication' is obsolete: 'This is obsolete and will be removed in a future version. So, which method is introduce in .net core 2 to get the identity?

Check the updated quickstarts UI:
https://github.com/IdentityServer/IdentityServer4.Quickstart.UI/tree/dev

Related

How to update a User Claim after on a active SAML Session in .Net Core?

Is it possible to update a User Claim during a active SAML Session without a complete relogging to the application?
I want to change a specific claim (activeSite) that we use for authorization in backend and for filtering in queries.
I'm working with an .Net Core API and a Angular/Ionic frontend.
The code we use is from the TestWebAppCoreAngularApi Project with a little adoption by setting some custom user claims.
[Route("AssertionConsumerService")]
public async Task<IActionResult> AssertionConsumerService()
{
var binding = new Saml2PostBinding();
var saml2AuthnResponse = new Saml2AuthnResponse(config);
binding.ReadSamlResponse(Request.ToGenericHttpRequest(), saml2AuthnResponse);
if (saml2AuthnResponse.Status != Saml2StatusCodes.Success)
{
throw new AuthenticationException($"SAML Response status: {saml2AuthnResponse.Status}");
}
binding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnResponse);
var relayStateQuery = binding.GetRelayStateQuery();
var activeSite = relayStateQuery.ContainsKey(relayStateActiveSite) ? relayStateQuery[relayStateActiveSite] : Url.Content("-1");
AddCustomClaims(saml2AuthnResponse, Int32.Parse(activeSite));
await saml2AuthnResponse.CreateSession(HttpContext, claimsTransform: (claimsPrincipal) => ClaimsTransform.Transform(claimsPrincipal));
var returnUrl = relayStateQuery.ContainsKey(relayStateReturnUrl) ? relayStateQuery[relayStateReturnUrl] : Url.Content("~/");
return Redirect(returnUrl);
}
Is it even possible to update that active claim (activeSite) during a active session?
And if so how can I update the claim in .Net?
I tryed something like removing and adding the claim with new value but this seems not to work correctly.
var principle = (ClaimsIdentity)User.Identity;
principle.RemoveClaim(claim);
principle.AddClaim(claim);
It is NOT possible to change claims after a successfully authentication flow. Changing claims require a re-login.
Hovewer, it is possible to change claims after user login in the authentication flow, by calling the ClaimsTransform.Transform, and the ClaimsTransform class.

Login as different user in identity server 4

I am trying to implement the LoginAs/Login as a different user feature using Identity Server 4. My Client Application is developed on top of Angular. I am trying to sign out the existing logged-in user and sign in the user using the provided userId. Maybe I am going the wrong way. Any solutions for that? Here is my code for Identity Server 4.
[HttpPost("login-as")]
public async Task<IActionResult> LoginAsAsync([FromBody] LoginAsViewModel model)
{
await HttpContext.SignOutAsync();
var user = await userManager.FindByIdAsync(model.UserId);
if (user == null)
{
return BadRequest();
}
await signInManager.SignInAsync(user,false);
return Redirect("/connect/authorize");
}

Azure AD v2.0-specific optional claims missing from ID Token

I'm trying to add optional claims using Microsoft Identity Web - NuGet for user authentication in NET Core 3.1 WebApp. Reading the MS Docs, it seems that the only steps needed are to declare the optional claims within the App Registration Manifest file in Azure. But when testing the login process using two different apps (my own code and an MS project example) it looks like the optional claims are not being added to the ID Token when returned from Azure following a successful login i.e they're not present at all when viweing the token details in Debug.
I'm not sure how to diagnose this and where to trace the issue i.e am I missing any required steps in Azure setup?
Side Note: Just to confirm it is the jwt ID Token I want to receive the additional claims, NOT the jwt access token used for calling the graph or another Web API endpoint.
MS Docs reference: v2.0-specific optional claims set
Below is the extract from the Manifest file: (note I've even declared the "accessTokenAcceptedVersion": 2, given that optional claims I'm using are not available in ver.1, which if the above was left at default 'null' value then Azure will assume we're using legacy ver.1 - a possible gotcha)
"accessTokenAcceptedVersion": 2,
"optionalClaims": {
"idToken": [
{
"name": "given_name",
"source": "user",
"essential": false,
"additionalProperties": []
},
{
"name": "family_name",
"source": "user",
"essential": false,
"additionalProperties": []
}
],
"accessToken": [],
"saml2Token": []
},
Extract from startup class:
public void ConfigureServices(IServiceCollection services)
{
// Added to original .net core template.
// ASP.NET Core apps access the HttpContext through the IHttpContextAccessor interface and
// its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor
// when you need access to the HttpContext inside a service.
// Example usage - we're using this to retrieve the details of the currrently logged in user in page model actions.
services.AddHttpContextAccessor();
// DO NOT DELETE (for now...)
// This 'Microsoft.AspNetCore.Authentication.AzureAD.UI' library was originally used for Azure Ad authentication
// before we implemented the newer Microsoft.Identity.Web and Microsoft.Identity.Web.UI NuGet packages.
// Note after implememting the newer library for authetication, we had to modify the _LoginPartial.cshtml file.
//services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
// .AddAzureAD(options => Configuration.Bind("AzureAd", options));
///////////////////////////////////
// Add services required for using options.
// e.g used for calling Graph Api from WebOptions class, from config file.
services.AddOptions();
// Add service for MS Graph API Service Client.
services.AddTransient<OidcConnectEvents>();
// Sign-in users with the Microsoft identity platform
services.AddSignIn(Configuration);
// Token acquisition service based on MSAL.NET
// and chosen token cache implementation
services.AddWebAppCallsProtectedWebApi(Configuration, new string[] { Constants.ScopeUserRead })
.AddInMemoryTokenCaches();
// Add the MS Graph SDK Client as a service for Dependancy Injection.
services.AddGraphService(Configuration);
///////////////////////////////////
// The following lines code instruct the asp.net core middleware to use the data in the "roles" claim in the Authorize attribute and User.IsInrole()
// See https://learn.microsoft.com/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 for more info.
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
// The claim in the Jwt token where App roles are available.
options.TokenValidationParameters.RoleClaimType = "roles";
});
// Adding authorization policies that enforce authorization using Azure AD roles. Polices defined in seperate classes.
services.AddAuthorization(options =>
{
options.AddPolicy(AuthorizationPolicies.AssignmentToViewLogsRoleRequired, policy => policy.RequireRole(AppRole.ViewLogs));
});
///////////////////////////////////
services.AddRazorPages().AddMvcOptions(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
// Adds the service for creating the Jwt Token used for calling microservices.
// Note we are using our independant bearer token issuer service here, NOT Azure AD
services.AddScoped<JwtService>();
}
Sample Razor PageModel method:
public void OnGet()
{
var username = HttpContext.User.Identity.Name;
var forename = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "given_name")?.Value;
var surname = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "family_name")?.Value;
_logger.LogInformation("" + username + " requested the Index page");
}
UPDATE
Getting closer to a solution but not quite there yet. Couple of issues resolved:
I originally created the Tenant in Azure to use B2C AD, even though I was no longer using B2C and had switched to Azure AD. It wasn't until I deleted the tenant and created a new one before I started to see the optional claims come through to the webapp correctly. After creating the new tenant and assigning the tenant type to use Azure AD, I then found that the 'Token Configuration' menu was now available for configuring the optional claims through the UI, it seems that modifying the App manifest is still required as well, as shown above.
I had to add the 'profile' scope as type 'delegated' to the webapp API Permissions in Azure.
The final issue still unresolved is that although I can see the claims present during Debug, I cant figure out how to retrieve the claim values.
In the method below, I can see the required claims when using Debug, but can't figure out how to retrieve the values:
public void OnGet()
{
var username = HttpContext.User.Identity.Name;
var forename = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "given_name")?.Value;
var surname = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "family_name")?.Value;
_logger.LogInformation("" + username + " requested the Index page");
}
Debug Screenshots shows the given_name & family_name are present:
I've tried different code examples using the claims principal to try and get the values out, but nothing is working for me. Hoping this final riddle is fairly simple to someone who knows the required syntax, as said we now have the required optional claims present, its just not knowing how to actually get the values out.
Big thanks to 'Dhivya G - MSFT Identity' for their assistance (see comments below my original question) method below now allows me to access the required claim values from the Token ID returned from Azure following successful login.
public void OnGet()
{
var username = HttpContext.User.Identity.Name;
var forename = HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName)?.Value;
var surname = HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname)?.Value;
_logger.LogInformation("" + username + " requested the Index page");
}

Identity Server 4 GetSchemeSupportsSignOutAsync returns incorrect response

I've setup an open id connect provider, Google in this case, using the AddOpenIdConnect extension method in dotnet core. From the discovery document:
https://accounts.google.com/.well-known/openid-configuration
it does not seem that google supports federated sign-out because there is no end_session endpoint. However, in Identity Server 4, the call:
var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp);
returns true. So during Logout it tries to sign out of google using:
return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
which throws an exception:
InvalidOperationException: Cannot redirect to the end session endpoint, the configuration may be missing or invalid.
Is this a bug in Identity Server 4 or is there a configuration property that needs to be set when setting up the Oidc provider so that this extension method will pickup that the provider does not support signout?
Doesn't appear to be a bug in Identity Server 4. The code behind this extension calls out to get the underlying authentication scheme handler.
public static async Task<bool> GetSchemeSupportsSignOutAsync(this HttpContext context, string scheme)
{
var provider = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
var handler = await provider.GetHandlerAsync(context, scheme);
return (handler != null && handler is IAuthenticationSignOutHandler);
}
In this case, your handler will be OpenIdConnectHandler which appears to implement IAuthenticationSignOutHandler so that's why regardless of what is in the discovery document (end session endpoint supported or not), if you use the AddOpenIdConnect(...), it will always register a handler which seemingly supports sign out, but as you have pointed out, does not actually enforce the actual idp validation for that kind of functionality support (link to handler source).
And lastly, worthwhile to mention, that Identity Server 4 check is rightful here as according to Microsoft docs, the IAuthenticationSignOutHandler is indeed basically a marker interface used to determine if a handler supports SignOut.
So I guess you just simply can't use the generic AddOpenIdConnect(...), instead perhaps you should use AddGoogle(...) which does not implement IAuthenticationSignOutHandler so will work as expected with Identity Server 4 (link to source).
As Vidmantas Blazevicius mentioned, using .AddOpenIdConnect will make the extension method default to true because of the interface. I have changed my code to explicity check for the support of an end_session_endpoint by doing:
var discoveryClient = new IdentityModel.Client.DiscoveryClient("https://accounts.google.com/.well-known/openid-configuration")
{
Policy = new IdentityModel.Client.DiscoveryPolicy
{
ValidateEndpoints = false, //this is needed for google, if set to true then will result in error response
ValidateIssuerName = false //this is needed for Microsoft, if set to true then will result in error response
}
};
var discoveryResult = await discoveryClient.GetAsync();
if (!discoveryResult.IsError)
{
if (!String.IsNullOrWhiteSpace(discoveryResult.EndSessionEndpoint))
supportsFederatedSignOut = true;
}
I then save an additional property on the model "SupportsFederatedSignOut" and then use this to determine whether external identity provider signout (SignOut) should be called.

Identity server claims asp.net API

I'm currently writing an angular application that first authenticates against think texture identityserver3.
This works fine, and I receive the bearer token without any issues.
When I use my token on an call to my API, I'm authenticated. I can see my userid, but have lost my claims (username, roles,...).
What do I have to do for transferring my claims with my token, or getting the roles from the identityserver?
You can tell Identity Server to include specific claims in an access token by adding that claim to your API's Scope.
Example:
var apiScope = new Scope {
Name = "myApi",
DisplayName = "My API",
Type = ScopeType.Resource,
Claims = new List<ScopeClaim> {
new ScopeClaim("myClaimType")
}
};
You can also use the AlwaysIncludeInIdToken property of ScopeClaim to include the claims in identity tokens as well as access tokens.
See https://identityserver.github.io/Documentation/docsv2/configuration/scopesAndClaims.html for more info.
We are doing something very similar using MS Web API 2 and a Thinktecture Identity Server v3.
To verify the user's claims we created an Authentication Filter, and then called the Identity server directly to get the user's claims. The bearer token only grants authentication and it is up to the API to get the claims separately.
protected override bool IsAuthorized(HttpActionContext actionContext)
{
string identityServerUrl = WebConfigurationManager.AppSettings.Get("IdentityServerUrl") + "/connect/userinfo";
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = actionContext.Request.Headers.Authorization;
var response = httpClient.GetAsync(identityServerUrl).Result;
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
Dictionary<string, string> claims = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString.ToLower());
... Do stuff with your claims here ...
}
}
}

Resources