How do implement multi domain Identity server? - azure-active-directory

I've a question!.. I need implement IdentityServer with N-tenant and its authentication provider(Azure AD all..).
For example:
Tenant1 ... AzureAD-1
Tenant2 ... AzureAD-2
Tenant3 ... AzureAD-3
(...)
TenantN ... Redirect AzureAD-N
Is possible it?
In addition, I need get information tenant from data base(it's clientId, client secret, callbackPath, etc..).
My first approach is:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
(...)
IEnumerable<AuthenticationSchema> schemas = repository.GetAuthenticationSchemas();
if (schemas != null && schemas.Count() > 0)
{
foreach (AuthenticationSchema schema in schemas)
builder.AddOpenIdConnect(schema.Id, options =>
{
options.Authority = schema.Authority;
options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false };
options.ClientId = schema.ClientId;
options.ClientSecret = schema.ClientSecret;
options.CallbackPath = schema.CallBackPath;
});
}
(...)
}
}
this approach has problem that if i add a new openidconnect in database i need reset server bacause the registration is in startup application..
Is it possible do it dinamically?
Do they could help me ?

I think you can better solve the business need with multitenant application and here are some resources that would help you on multi tenant application.
Authentication flows and application scenarios
Sign in any Azure Active Directory user using the multi-tenant application pattern
Code sample
Recorded walkthrough

Related

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

.Net Core authorize authenticated users with Azure AD

Hi,
We have a .Net Core 2.0 app, with Azure AD authentication.
At the moment we have some users associated with the app that have been given a role for the app in the Azure AD, and are using policies to check authorisation. Due business requirements we want to open the app to any user on the company, so we only need to check that the user is authenticated.
As an experienced C# developer, I went to the controller that had the following code
[Authorize(Policy = PolicyNames.RequireLinecardsUser)]
public class LinecardController : Controller
{
//controller code here
}
and changed it to this
[Authorize]
public class LinecardController : Controller
{
//controller code here
}
and for may user, that still has the role of LinecardUser, it works. it can access the app (the main entry point is inside that controller). But when we tested it with a user that does not have a role in the app, it gets an access denied exception.
So next step we went into startup, and removed the authorisation configurations ( it only had 2 now unused policies).
public void ConfigureServices(IServiceCollection services)
{
try
{
services.AddDbContext(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("LinecardsContext"), opt => opt.UseRowNumberForPaging());
});
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultForbidScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.AccessDeniedPath = "/Account/AccessDenied/";
options.LoginPath = "/Account/Login/";
})
.AddOpenIdConnect(options =>
{
configuration.GetSection("AzureAd").Bind(options);
});
services.AddAuthorization(options =>
{
options.AddPolicy(PolicyNames.RequireLinecardsUser,
policy =>
{
policy.AddRequirements(new LinecardsWebUserRequirement());
policy.RequireAuthenticatedUser(); // Adds DenyAnonymousAuthorizationRequirement
// By adding the CookieAuthenticationDefaults.AuthenticationScheme, if an authenticated
// user is not in the appropriate role, they will be redirected to a "forbidden" page.
policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
});
options.AddPolicy(PolicyNames.RequireLinecardsAdmin,
policy =>
{
policy.AddRequirements(new LinecardsWebAdminRequirement());
policy.RequireAuthenticatedUser(); // Adds DenyAnonymousAuthorizationRequirement
// By adding the CookieAuthenticationDefaults.AuthenticationScheme, if an authenticated
// user is not in the appropriate role, they will be redirected to a "forbidden" page.
policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
});
});
services.AddScoped();
services.RegisterTypes();
services.AddReact();
services.AddAutoMapper();
services.Configure(x => x.ValueCountLimit = 100000);
services.AddMvc();
}
catch (Exception ex)
{
Log.Error(ex, "Error happened on configuring services");
throw;
}
}
That means that in the previous code we removed the services.AddAuthentication(); block. Same result, users that have roles can access the app, users that don't cannot. (tried with the browser in anonymous mode too, to make sure no caching problems were in action here).
Finally we tried to change the RequireLinecardsUser policy, so it didn't have the policy.AddRequirements(new LinecardsWebUserRequirement()); line (and changed the controller to the original authorization line with the policy.
Once again, same results, works fine for me, access denied for users that don't have a role.
Am I missing something obvious? Something that changed in Core 2.0? Something Azure related?
Because every documentation that I found says that the [Authorize] annotation without any arguments should work and intended, and only verify that user is authenticated before allowing the code to procede...
As some of you may have noticed the app has a react frontend that I haven't touched, feel free to point any problems that may be related with that.
PPS: Sorry if the formatting is not up to standard, but it's my first question
After some more tests with this app, an exception pointed to Azure being the culprit for this.
On the app properties in Azure there is an option asking "User assignment required?". That particular setting was set to yes for this app.
Changing it to no solved the problem.

Inviting a User in Azure AD through Microsoft Graph API doesn't work

Below is the code that I have put to invite a user in Azure AD.
I get an "unauthorized" response. I am not sure what permission/setting are missing. Do anyone have the idea.
string accessToken = await AuthenticationHelper.GetTokenForApplication ();
InvitationModel invite = new InvitationModel ();
invite.invitedUserEmailAddress = user.Email;
invite.inviteRedirectUrl = ConfigurationManager.AppSettings["InviteRedirectUrl"];
invite.sendInvitationMessage = true;
using (HttpClient client = new HttpClient ()) {
client.BaseAddress = new Uri ("https://graph.microsoft.com");
client.DefaultRequestHeaders.Accept.Add (
new MediaTypeWithQualityHeaderValue ("application/json"));
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue ("Bearer", accessToken);
HttpResponseMessage response =
client.PostAsJsonAsync<InvitationModel> ("v1.6/invitations", invite).Result;
dynamic inviteResult =
response.Content.ReadAsAsync<dynamic> ().Result;
if (inviteResult.status != "Error") { }
}
You're problem is that you conflating Microsoft Graph and Azure AD Graph here. These are two distinct APIs with different calling conversions and permission scopes.
In order to create an Invitation you will need one of the following permission scopes (Note that the first is the most restrictive permission (globally), the last the most permissive):
User.Invite.All
User.ReadWrite.All
Directory.ReadWrite.All
Note that all of these scopes are admin-restricted and will require Admin Consent before you can use them
Once you have a valid token, you'll need to make a POSTcall to https://graph.microsoft.com/v1.0/invitations with the following body:
{
"invitedUserEmailAddress": "yyy#test.com",
"inviteRedirectUrl": "https://myapp.com"
}
Since you're using C#, I would strongly recommend using Microsoft Graph Client Library rather than hand-rolling your own HttpClient calls.

How do I renew the timeout of my ApplicationCookie in Identity 2.0

Is there a way to renew the authentication timeout of a cookie as part of a particular web request? I have an Angular app on top of my MVC 5 project and I need it to keep my server session alive in between requests. I've got the Angular part working, but it appears that hitting a URL on my server is not sufficient to reset the Auth timeout. I am new to Identity so I am probably missing something simple?
My Startup.Auth.cs code:
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
ExpireTimeSpan = TimeSpan.FromSeconds(30),
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(20),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
}
And my simple method (authorization is set up globally for all requests that do not have [AllowAnonymous]):
[HttpGet]
public HttpResponseMessage KeepAuthAlive()
{
// Renew Auth Cookie - how?
}
Re-SignIn the User (this code assumes you have UserManager and SignInManager available as per the default Account controller and an async ActionResult). I haven't tested this, but it should hopefully work:
ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}

Azure Active Directory: Consent Framework has stopped granting consent

I have just written an app with Azure Active Directory Single Sign-On.
The consent framework is handled in the AccountController, in the ApplyForConsent action listed below. Until recently, everything has worked seamlessly. I could grant consent as an admin user of an external tenant, then sign out of the app, and sign in again as a non-admin user.
My Azure Active Directory app requires the following delegated permissions:
Read directory data
Enable sign-on and read users' profiles
Access your organisation's directory
Now, after I have gone through the consent framework (by POSTing from a form to ApplyForConsent as an admin user), signing in as a non-admin user fails with the error message AADSTS90093 (This operation can only be performed by an administrator). Unhelpfully, the error message doesn't say what "this operation" actually is, but I suspect it is the third one (Access your organisation's directory).
I stress again, this has only recently stopped working. Nothing has changed in this part of the code, although I grant it is possible that other changes elsewhere in the codebase may have had knock-on effects of which I remain blissfully ignorant.
Looking at the documentation, it seems that this use of the consent framework is already considered "Legacy", but I'm having a difficult time finding a more up-to-date implementation.
The requested permissions in the code sample below is the single string "DirectoryReaders".
I have three questions for helping me debug this code:
What is the difference between "Read directory data" and "Access your organisation's directory"? When would I need one rather than another?
Do I need to request more than just "DirectoryReaders"?
Is there now a better way to implement the Consent Framework?
This is the existing code:
private static readonly string ClientId = ConfigurationManager.AppSettings["ida:ClientID"];
[HttpPost]
public ActionResult ApplyForConsent()
{
string signupToken = Guid.NewGuid().ToString();
string replyUrl = Url.Action("ConsentCallback", "Account", new { signupToken }, Request.Url.Scheme);
DatabaseIssuerNameRegistry.CleanUpExpiredSignupTokens();
DatabaseIssuerNameRegistry.AddSignupToken(signupToken, DateTimeOffset.UtcNow.AddMinutes(5));
return new RedirectResult(CreateConsentUrl(ClientId, "DirectoryReaders", replyUrl));
}
[HttpGet]
public ActionResult ConsentCallback()
{
string tenantId = Request.QueryString["TenantId"];
string signupToken = Request.QueryString["signupToken"];
if (DatabaseIssuerNameRegistry.ContainsTenant(tenantId))
{
return RedirectToAction("Validate");
}
string consent = Request.QueryString["Consent"];
if (!String.IsNullOrEmpty(tenantId) && String.Equals(consent, "Granted", StringComparison.OrdinalIgnoreCase))
{
if (DatabaseIssuerNameRegistry.TryAddTenant(tenantId, signupToken))
{
return RedirectToAction("Validate");
}
}
const string error = "Consent could not be provided to your Active Directory. Please contact SharpCloud for assistance.";
var reply = Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action("Consent", new { error });
var config = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration;
var signoutMessage = new SignOutRequestMessage(new Uri(config.Issuer), reply);
signoutMessage.SetParameter("wtrealm", config.Realm);
FederatedAuthentication.SessionAuthenticationModule.SignOut();
return Redirect(signoutMessage.WriteQueryString());
}
private static string CreateConsentUrl(string clientId, string requestedPermissions, string consentReturnUrl)
{
string consentUrl = String.Format(CultureInfo.InvariantCulture, ConsentUrlFormat, HttpUtility.UrlEncode(clientId));
if (!String.IsNullOrEmpty(requestedPermissions))
{
consentUrl += "&RequestedPermissions=" + HttpUtility.UrlEncode(requestedPermissions);
}
if (!String.IsNullOrEmpty(consentReturnUrl))
{
consentUrl += "&ConsentReturnURL=" + HttpUtility.UrlEncode(consentReturnUrl);
}
return consentUrl;
}
I think this link addresses your issue:
http://blogs.msdn.com/b/aadgraphteam/archive/2015/03/19/update-to-graph-api-consent-permissions.aspx
The quick summary is that now only admins can grant consent to a web app for '•Access your organisation's directory'.
This change was made back in March. Native apps are not affected by the change.
My suspicion was correct. I was using legacy tech in the question. By moving to Owin and Identity 2.0, all issues were solved.
The new approach is summarised by https://github.com/AzureADSamples/WebApp-GroupClaims-DotNet

Resources