Missing Claims from within the IdentityServer Website, including all samples - asp.net-core

I am sure this is down to a lack of understanding.
I am trying to access the currently-logged in users claims, within an IdentityServer instance. I am finding that any claims I provide the user are only available to the setup clients, and not the IdentityServer itself.
My issue can be replicated by using any of the quick start samples provided by the IdentityServer4 team (QuickStart Samples)
I am building a site that will provide authentication, using IdentityServer4, and also provide some interface screens to manage your own profile. To facilitate this I will need access to the claims from within the IdentityServer site.
If we look at the test users on the quick starts, we have this user:
new TestUser
{
SubjectId = "1",
Username = "alice",
Password = "password",
Claims = new List<Claim>
{
new Claim("name", "Alice"),
new Claim("website", "https://alice.com")
}
},
We can see it has 2 claims; name and website.
Within the login controller, I also add another claim, just before signing in (by way of experimenting)
user.Claims.Add(new Claim("given_name", "bob"));
// issue authentication cookie with subject ID and username
await HttpContext.SignInAsync(user.SubjectId, user.Username, props);
When the QuickStart site and the MVC Client are running, I can successfully log in. The Secure page then shows me the claims below (after enabling AlwaysIncludeUserClaimsInIdToken)
However, if i visit the Grants section of the IdentityServer4 Quickstart, and inspect the current User I see an entirely different set of claims, shown below:
How, within IdentityServer4 Quickstart, can i access the same list of claims that were returned in the ID Token?
My specific reason is i will be storing an Active Directory UPM as one of the claims and will need access to this when the user is within any secure page in our Identity Server.

Ok - after a day of playing around, I realized there were other overrides for the HttpContext.SignInAsync() method.
Before, I had this - as per tutorial
await HttpContext.SignInAsync(user.SubjectId, user.Username, props);
Changing this to
await HttpContext.SignInAsync(user.SubjectId, user.Username, props, user.Claims.ToArray());
Gives me exactly what i was looking for.
Leaving this here on the off chance others have the same issue.

Related

Can I Combine Identities from two Authentication Schemes in ASP.NET Core 3?

I have a web application that utilizes our organization's CAS servers for authentication. I am currently developing an integration with DocuSign for this application. A user will first come to our site and sign in with CAS. Then, they can go to the DocuSign area of the application, sign in to DocuSign, and then perform some functions tied to the DocuSign API. Each of these pieces works properly within my application.
My current problem is that I cannot access both Identities within the HttpContext simultaneously. I need the CAS Identity to determine user behavior and access to certain functions. I need the DocuSign Identity to get the necessary values to enable the API calls. In Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/Account/Login");
})
.AddCAS(options =>
{
options.CasServerUrlBase = Configuration["CasBaseUrl"];
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOAuth("DocuSign", options ->
{
//necessary DocuSign options
});
I have a HomeController that uses the Authorize attribute and properly requires CAS to access. I can properly access the claims from the CAS Identity. I have a DocusignController where I use Authorize(AuthenticationSchemes = "DocuSign"). An ActionFilter that applies to this controller shows that the DocuSign Identity is coming through properly. Unfortunately, the CAS Identity is not attached, so I cannot check for things such as admin permissions. I examined the cookies, and saw that the .AspNetCore.Cookies value changes when I go between the different Authentication Schemes.
One attempt at a solution was to change the DocusignController to have Authorize(AuthenticationSchemes = "DocuSign, CAS" as its attribute. This seems to be an 'or' rather than an 'and' of the two schemes. If CAS was the most recent scheme, then the CAS Identity is the one seen in my ActionFilter. Same for DocuSign.
Another attempt was to create my own AuthenticationHandler to combine the two Identities. Appended to the AddAuthentication above:
.AddScheme<CombinedSchemeOptions, CombinedHandler>
("Combined", op => { });
Then, within this CombinedHandler:
protected async override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var CasResult = await Context.AuthenticateAsync("CAS");
if(CasResult?.Principal != null)
{
principal.AddIdentities(CasResult.Principal.Identities);
}
var DSResult = await Context.AuthenticateAsync("DocuSign");
if(DSResult?.Principal != null)
{
principal.AddIdentities(DSResult.Principal.Identities);
}
var ticket = new AuthenticationTicket(principal, "Combined");
return AuthenticateResult.Success(ticket);
}
This seems to behave the same way as before. The most recent Scheme I've used, upon entering the Combined scheme, will give a successful Result with an Identity, and the other Result will return with a failed result.
Is it possible for me to have these two Identities within the HttpContext.User simultaneously? Is it otherwise possible for me to combine claims from the two Identities into one and pass that along?
Further research and tinkering has led me to a solution. First, I discovered that I needed the two authentication schemes to write to separate cookies. I then made sure the DocuSign scheme used the new cookie as its SignInScheme.
.AddCookie("DSCookie")
.AddOAuth("DocuSign", options =>
{
options.SignInScheme = "DSCookie";
//further DocuSign options
}
I also learned that the Authorize tag works as an OR statement (if you have CAS OR DocuSign, you are authorized for this action), yet it will pass along all valid identities permitted by the scheme (You have CAS and you have DocuSign? Bring both Identities in with you). Thus, the second part of my solution has a single action that requires DocuSign authentication, prompting the necessary challenge. Then, I move to actions that have both authentication schemes, and both Identities are brought along properly.
EDIT: To elaborate per Dmitriy's request
[Authorize(AuthenticationSchemes = "DocuSign")]
public ActionResult Index()
{
return RedirectToAction("Control");
}
[Authorize(AuthenticationSchemes = "DocuSign,CAS")]
public ActionResult Control()
{
//relevant code
}
I click on a link to go to the Index action. Since I currently do not have a valid DocuSign Identity, it performs the necessary prompt and takes me to the sign in screen. If I linked directly to Control, Authentication would see that I currently had a valid CAS Identity, so would approve my access, even though I did not yet have the DocuSign Identity.
After the sign in, when I arrive at the Index function, only the DocuSign Identity is currently available. I then redirect to Control. That function verifies I have at least one of the specified Identities, grants me access, and passes along any of the listed Identities I currently possess. Thus, inside Control, I can grab information from both CAS and DocuSign.

How to use IdentityServer4 to authenticate local user from local database?

I'm creating SSO solution for multiple existing projects. Most of the applications already use same database, so same users and I use these users in IdentityServer. But there is one app which has its own users DB and login screen. Users from this table are used in one of the tables in this app (FK).
My idea is to leave existing users DB as is. Add a column MasterUserGuid to Users table that will contain "master" user Guid (so the user that IdentityServer uses for authentication) and implement following flow:
User opens the app and is not signed in
User is redirected to IdentityServer and uses global credentials
User is redirected back to the app which gets global user GUID from claims and authenticates local user (with this GUID in the MasterUserGuid column), instead of using global user
The problem is that I don't know how to implement step 3 or if it's even possible/supported in IdentityServer4. At the moment I'm redirected to IdentityServer, am authenticated and redirected back, but then the app tries to use this external user.
While researching I've read that users should be in one table, so maybe this approach is totally wrong and it would be better to remove local users and break FK for mentioned table and do some manual migration of users.
Is the scenario described in the steps I provided possible and sane?
You need to adjust your application to authenticate via IdentityServer first. Remove all the ASP.NET Core Identity logic related to registration, login etc. assuming all of that will be done on IdentityServer side. Then implement the instance of IClaimsTransformation which will either replace your current ClaimsPrincipalor add additional identities to it if needed with the claim values you want (populated from local database). Here is the example:
public class MyClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var claims = new List<Claim>();
claims.Add(new Claim(...)); // put here your claim type and value
var identity = new ClaimsIdentity(claims);
principal.AddIdentity(identity);
return principal;
}
}
Then register your claims transformer in IOC in Startup.ConfigureServices method:
services.AddTransient<IClaimsTransformation, MyClaimsTransformer>();

Should Name Claim remain omitted in JWT Access Token with IdentityServer4 (using Identity) and ASP.Net Core API?

While configuring my IdentityServer4 (using Identity) resource owner grant flow with an asp.net core API backend, I got to thinking that perhaps the "Name" claim should remain omitted in the JWT access token for user security? This claim is not available with out of the box behavior of IS4.
Previously, I had been adding in the "Name" claim for the access token in my IS4 Config.cs file as follows:
var claims = new List<string>
{
JwtClaimTypes.Name
};
return new List<ApiResource>
{
new ApiResource("api1", "Auth API", claims)
};
I was doing this because it allows a straightforward approach to get a logged in user's ClaimsPrincipal.Identity.Name for user look up inside a Controller action.
var name = User.Identity.Name;
var user = await _userManager.FindByNameAsync(name);
However, IS4 access tokens (when using Identity) include the user's GUID id in the "Sub" claim. With this, we can also look up a user using the following:
var userId = User.Claims.FirstOrDefault(u => u.Type == "sub").Value;
var user = await _userManager.FindByIdAsync(userId);
I know there is slightly more processing with the LINQ query (hardly anything tbh), but I was thinking it might be of worth to protect a user's username (email address in my situation) if an access token ever fell into the wrong hands. Especially since JWT's are so easy to decode with the likes of jwt.io.
Do you guys agree or disagree? Or am I looking at this the wrong way and missing something?
JWT usually contain the public data and it is self-contained. i.e. You don't need to communicate with a backend server to construct user's identity. You should prevent the token fell into wrong hand by using https. Also, you should balance your token validity window(usability vs security) and use a nonce for maximizing the security.
I don't think 'name' should be omitted from claim collection. A valid use-case for what you are doing is that you need to make sure that changes to your user store immediately reflect in your web API. In the case of a self-contained token, if you change the 'name' in the data store, the user will not see that change until he was issued a new token. In this case use of a 'reference token' might be a good option.
Also, It looks like you are directly accessing user store from the web API. While you might have valid reasoning behind this, Idea of using token based authentication is to delegate authentication to external party(Identity Server). So common pattern is to
Include every public data that you require in the web API in the
access token.
If token getting too big, include a subset of claims in the token and query user info endpoint when required.
Use reference tokens if you have valid reasons to do so. But this will affect the performance as it will require back channel communication with identity server.

How to use AuthenticationManager SignIn when using OpenId

We have a need to provide Mixed Mode Authentication and we've spent weeks chasing down samples, and bits and pieces and finally we have our ClaimsIdentity properly built, we just need to figure out a way to have OWIN recognize our ClaimsIdentity as the logged in user.
Everything we've found thus far is defining app.UseCookieAutentication in Startup.Auth.ConfigureAuth(). Set AuthenticationType = "Cookies", then set a login path.
However, we use a custom version of Identity Server 3 and in addition to UseCookieAuthentication, we also use app.UseOpenIdConnectAuthentication.
We've had issues with setting the UseCookieAuthentication LoginPath. We've tried putting something in it and leaving it empty.
Code we use to login our Windows users, we make calls to IdentityServer, get our tokens and claims.
We then use UserManager.CreateIdentityAsync as follows.
var _identity = await _userManager.CreateIdentityAsync(_slUser, DefaultAuthenticationTypes.ApplicationCookie);
Everything appears good here.
Then we use that Identity with the following code:
var _ctx = HttpContext.Current.GetOwinContext();
var _authenticationManager = _ctx.Authentication;
_authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, _identity);
The code runs but when we check _ctx.Authentication.User, the identity we created still isn't showing up which results in a user getting redirected to the login page on the Identity Server.
So in summary, we're trying to figure out how to take a ClaimsIdentity we've authenticated and built up in code and have it become of apart of the OwinContexts Authentication.User.Identities so it will be available throughout our application.

How to propagate an administrator's changes to a user's claims

Situation
Let's say an administrator of a site removes a user from the Admin role and adds her to the Contributor role. According to the site's database, that user has been demoted and should no longer have access to Admin-only features. Now the user comes back to the site some time after that change, but had logged in sometime before the change and is still logged in. So long as that user does not log out, she will continue to have claims that say she is in the Admin role. If she logs out, or gets logged out, she loses the claim that she belongs to the Admin role and when she signs back in receives the new claim of belonging to the Contributor role.
Desire
What I would like to happen, perhaps the next time the user requests a page from the site after the administrator made the change, is have that user transparently lose the Admin role claim and gain the Contributor role claim without them having to sign out or do anything special. In fact, I would prefer they are unaware of the change, except that her menu has changed a little because she can no longer perform Admin-only activities.
How would you handle this situation in a way that is invisible to the affected user?
My thoughts
I am using ASP.NET MVC 5 and ASP.NET Identity, but it seems like a solution to this could be easily generalized to other claims based frameworks that utilize cookies. I believe that ASP.NET Identity stores claims in the user's cookies by default in MVC 5 apps.
I have read the following post along with many others on SO and it comes closest to answering this question but it only addresses the case where the user updates herself, not when someone else like an administrator makes the change to her account: MVC 5 current claims autorization and updating claims
There is a feature in Identity 2.0 which addresses this, basically you will be able to do something like this which adds validation at the cookie layer which will reject users who's credentials have changed so they are forced to relogin/get a new cookie. Removing a role should trigger this validation (note that it only does this validation check after the validationInterval has passed, so the cookie will still be valid for that smaller timespan.
app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider {
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});