How to update Claim.Principal after login a user with Azure B2C - azure

I currently have a project that user B2C Azure for login. In azure I use 3 customs int fields that contains the result of a selection in some dropdownList. after the login occurs in my HOME Controller, I can read the customfield value in my claimsPrincipal like this:
System.Security.Claims.Claim claim = ClaimsPrincipal.Current.Claims.Where(c => c.Type == "extension_RegistrationComplete").SingleOrDefault();
if (claim != null)
retour = Convert.ToBoolean(claim.Value);
So I can test if all custom fields are completed before continuing. If RegistrationComplete are false, I redirect to a Step2 form page asking the user to choose options in dropdownlist. Then I save it to Azure with the B2C Graph API. But the local ClaimsPrincipal do not have the update so the user stuck in a loop because the local RegistrationConplete is always false.
How can we update the ClaimsPrincipal without re-logging the user? Currently I log the user with
HttpContext.GetOwinContext().Authentication.Challenge(authenticationProperties);
Thanks.
Finaly I use this code:
var Identity = HttpContext.User.Identity as ClaimsIdentity;
Identity.RemoveClaim(Identity.FindFirst("AnnounceCount"));
Identity.AddClaim(new Claim("AnnounceCount", "Updated Value"));
var authenticationManager =
System.Web.HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new
AuthenticationResponseGrant(new ClaimsPrincipal(Identity), new
AuthenticationProperties() { IsPersistent = true });

I'm not sure what framework you're using, but I've done this in the past by handling SecurityTokenValidated in IAppBuilder.UseWindowsAzureActiveDirectoryBearerAuthentication
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
SecurityTokenValidated = context =>{
//some stuff
Claim newClaim = new Claim("something", "special");
context.AuthenticationTicket.Identity.AddClaim(newClaim);
}
});
}

Related

OWIN Authentication with Azure AD B2C OP: SIgnOut Doesn't Remove Cookie when Called from External iFrame

I have an authentication module in Umbraco using OWIN/OIDC, authenticating against our Azure AD B2C resource. As part of this module, there is a LogOut controller method, which is working correctly.
We are trying to develop single sign out for applications within our Azure tenant. We are still working on having Azure AD B2C call the logout method for each application. In order to test initiation of sign out from other applications, I have set up an iframe in one of our custom applications (also authenticating via Azure AD B2C) that calls the LogOut method in our Umbraco implementation when users sign out from that application. I can see that the LogOut method is being called when the external method opens the iframe, and all of the objects look the same as when the method is called from within Umbraco. However, the user is not logged off of the application. The authentication cookie, which is .AspNet.ApplicationCookie, has SameSite as None, Secure as true and HttpOnly as false, but it is not removed as it is when Umbraco calls the method.
Any tips on how to get the LogOut method to work from the external application would be appreciated.
Here is my configuration:
private void ConfigureAzureB2CAuthentication(object sender, OwinMiddlewareConfiguredEventArgs args) {
//get appbuilder
AppBuilder app = (AppBuilder)args.AppBuilder;
app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ApplicationCookie);
app.UseCookieAuthentication(Current.Factory.GetInstance<FrontEndCookieAuthenticationOptions>(), PipelineStage.Authenticate);
//Set configuration on appbuilder
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions {
MetadataAddress = string.Format(
ConfigurationManager.AppSettings["ida:AzureInstance"],
ConfigurationManager.AppSettings["ida:Tenant"],
ConfigurationManager.AppSettings["ida:SignUpSignInPolicyId"]),
ClientId = ConfigurationManager.AppSettings["ida:ClientId"],
RedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"],
PostLogoutRedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"],
Notifications = new OpenIdConnectAuthenticationNotifications {
RedirectToIdentityProvider = OnRedirectToIdentityProvider,
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
AuthenticationFailed = OnAuthenticationFailed
},
TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
NameClaimType = ConfigurationManager.AppSettings["ida:ClaimsLabelEmail"],
ValidateIssuer = false
},
Scope = ConfigurationManager.AppSettings["ida:ScopesOpenIDConnect"],
});
//reafirm backoffice and preview authentication
app.UseUmbracoBackOfficeCookieAuthentication(_umbracoContextAccessor, _runtimeState, _userService, _globalSettings, _securitySection, PipelineStage.Authenticate)
.UseUmbracoBackOfficeExternalCookieAuthentication(_umbracoContextAccessor, _runtimeState, _globalSettings, PipelineStage.Authenticate)
.UseUmbracoPreviewAuthentication(_umbracoContextAccessor, _runtimeState, _globalSettings, _securitySection, PipelineStage.PostAuthenticate);
}
and this is the LogOut method:
public void LogOut(string redirectUrl = "/") {
if (Request.IsAuthenticated) {
RemoveLoggedInMemberAccessToken();
IEnumerable<AuthenticationDescription> authTypes = HttpContext.GetOwinContext().Authentication.GetAuthenticationTypes();
AuthenticationProperties authenticationProperties = new AuthenticationProperties { RedirectUri = redirectUrl };
HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, authTypes.Select(t => t.AuthenticationType).ToArray());
}
}

IdentityServer4 - is it possible to use local login form with external provider and no round trip?

I'm trying to use a local login form to authenticate a user credentials against its external provider (Azure Active Directory).
I understand that, per client, you can enable local login. That helps, as when set to true, I'll get the local login form but but I'm still unclear as to how to fire off the middle ware for that external provider. Is there a way to send client credentials to the external provider to receive an ID token? My current code redirects to the Microsoft login; and then back to my identity server, and then the client application. I want the user to login in through identity server but not have them know it's really authenticating against Azure.
Here's my start up:
var schemeName = "Azure-AD";
var dataProtectionProvibder = app.ApplicationServices.GetRequiredService<IDataProtectionProvider>();
var distributedCache = app.ApplicationServices.GetRequiredService<IDistributedCache>();
var dataProtector = dataProtectionProvider.CreateProtector(
typeof(OpenIdConnectMiddleware).FullName,
typeof(string).FullName, schemeName,
"v1");
var dataFormat = new CachedPropertiesDataFormat(distributedCache, dataProtector);
///
/// Azure AD Configuration
///
var clientId = Configuration["AzureActiveDirectory:ClientId"];
var tenantId = Configuration["AzureActiveDirectory:TenantId"];
Redirect = Configuration["AzureActiveDirectory:TenantId"];
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = schemeName,
DisplayName = "Azure-AD",
SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
ClientId = clientId,
Authority = $"https://login.microsoftonline.com/{tenantId}",
ResponseType = OpenIdConnectResponseType.IdToken,
StateDataFormat = dataFormat,
});
app.UseIdentity();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
This is the login.
[HttpGet]
public async Task<IActionResult> ExternalLogin(string provider, string returnUrl)
{
var context = this.HttpContext.Authentication;
List<AuthenticationDescription> schemes = context.GetAuthenticationSchemes().ToList();
returnUrl = Url.Action("ExternalLoginCallback", new { returnUrl = returnUrl });
// start challenge and roundtrip the return URL
var props = new AuthenticationProperties
{
RedirectUri = returnUrl,
Items = { { "scheme", provider } }
};
//await HttpContext.Authentication.ChallengeAsync(provider, props);
return new ChallengeResult(provider, props);
}
In my opinion ,we shouldn't directly pass the username/password directly from other Idp to azure AD for authentication as a security implementation .And even Azure AD supports the Resource Owner Password Credentials Grant ,it's only available in native client. I suggest you keep the normal way and don't mix them .

Sign up event from Azure B2C

How would I know that a person on my website has just completed the 'Sign Up' process in Azure B2C? Would I have to store my own list of object ids and check against it? I get the feeling I am going to have to do that in any case...
You receive the 'newUser' boolean claim if you have this selected in the signup policy. This will only be sent once, so you need to act on this.
Yes you need to store a list of object id's & verify accordingly in your business logic.
Managed to solve this...
Step 1 (Azure Portal)
In Azure Portal navigate to ADB2C, click on your Sign up and sign in policy
Click on Application claims and make sure to Tick the "User is new" claim
The "User is new" claim will be sent only if the user has just signed-up
Step 2 (Code)
//Using OpenIdConnectOptions
options.Events = new OpenIdConnectEvents()
{
OnRedirectToIdentityProvider = OnRedirectToIdentityProvider,
OnRemoteFailure = OnRemoteFailure,
OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
OnAuthenticationFailed = OnAuthenticationFailed,
OnMessageReceived = OnMessageReceived,
OnRedirectToIdentityProviderForSignOut = OnRedirectToIdentityProviderForSignOut,
OnRemoteSignOut = OnRemoteSignOut,
OnSignedOutCallbackRedirect = OnSignedOutCallbackRedirect,
OnTicketReceived = _onTicketReceivedInternal,
OnTokenResponseReceived = OnTokenResponseReceived,
OnTokenValidated = OnTokenValidated,
OnUserInformationReceived = OnUserInformationReceived
};
Notice the _onTicketReceivedInternal Task...
private Task _onTicketReceivedInternal(TicketReceivedContext context)
{
this.OnTicketReceived(context);
//Check if new user
Claim newUserClaim = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "newUser");
bool newUser = newUserClaim == null ? false : true;
//Trigger event
if (newUser)
this.OnSignUp(context);
return Task.FromResult(0);
}
//Custom method OnSignUp where an application can do something on user sign up
protected virtual Task OnSignUp(TicketReceivedContext context)
{
return Task.FromResult(0);
}

OWIN with LDAP Authentication

Here is my scenario. I have an MVC 5 application that uses Owin as an authentication mechanism. The default template calls the SignInManager.PasswordSignInAsync in the Login action which I would like to overwrite to use LDAP to validate the user instead of looking into the database.
I am able to do the validation via:
PrincipalContext dc = new PrincipalContext(ContextType.Domain, "domain.com", "DC=domain,DC=com", "user_name", "password");
bool authenticated = dc.ValidateCredentials(userName, password);
Then I can retrieve the UserPrincipal using:
UserPrincipal user = UserPrincipal.FindByIdentity(dc, IdentityType.SamAccountName, userName);
However, I am stuck here and I am not sure how to continue with signing in the user. The goal is that after I sign in the user, I would have access to User.Identity including all the roles the user is in. Essentially, the app should behave as if it uses Windows Authentication, but the credentials are provided by the user on the Login page.
You would probably ask why not user Windows Authentication directly. The app will be accessed from the outside of the network, but the requirements are to use AD authentication and authorization. Hence my predicament.
Any suggestions are highly appreciated.
Thank you.
After many hours of research and trial and error, here is what I ended up doing:
AccountController.cs - Create the application user and sign in
ApplicationUser usr = new ApplicationUser() { UserName = model.Email };
bool auth = await UserManager.CheckPasswordAsync(usr, model.Password);
if (auth)
{
List claims = new List();
foreach (var group in Request.LogonUserIdentity.Groups)
{
string role = new SecurityIdentifier(group.Value).Translate(typeof(NTAccount)).Value;
string clean = role.Substring(role.IndexOf("\\") + 1, role.Length - (role.IndexOf("\\") + 1));
claims.Add(new Claim(ClaimTypes.Role, clean));
}
claims.Add(new Claim(ClaimTypes.NameIdentifier, model.Email));
claims.Add(new Claim(ClaimTypes.Name, model.Email));
ClaimsIdentity ci = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties()
{
AllowRefresh = true,
IsPersistent = false,
ExpiresUtc = DateTime.UtcNow.AddDays(7),
}, ci);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid login credentials.");
return View(model);
}
IdentityConfig.cs (CheckPasswordAsync) - Authenticate against LDAP
public override async Task CheckPasswordAsync(ApplicationUser user, string password)
{
PrincipalContext dc = new PrincipalContext(ContextType.Domain, "domain", "DC=domain,DC=com", [user_name], [password]);
bool authenticated = dc.ValidateCredentials(user.UserName, password);
return authenticated;
}
Global.asax - if you are using the Anti Forgery Token in your login form
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
At this point, you will are logged in and can access the User.Identity object. You can also mark controllers and actions with [Authorize(Roles = "some_role"]
It turned out that it was easier than I thought, it is just that not much is really written on the topic (at least I could not find anything).
Also, this code presumes that you are running the app from a server which has access to the Domain Controller on your network. If you are on a DMZ server, you need to discuss this strategy with your network admin for other options.
I hope this saves you some time. I am also eager to hear what the community thinks of this. Maybe there is a better way of handling this situation. If so, please share it here.
Thanks.
Daniel D.

Using the MVC Authorize attribute with roles using Azure Active Directory + OWIN

I'm building a multi-tenant MVC5 app that follows very closely the sample guidance: https://github.com/AzureADSamples/WebApp-MultiTenant-OpenIdConnect-DotNet/
I'm authenticating against Azure Active Directory and have my own role names that I inject as a Role claim during the SecurityTokenvalidated event:
SecurityTokenValidated = (context) =>
{
// retriever caller data from the incoming principal
string upn = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
string tenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
var databaseConnectionString = RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString");
AppAnalyzerUser appAnalyzerUser = null;
using (CloudContext dbContext = new CloudContext(databaseConnectionString))
{
if (dbContext.Office365Accounts.FirstOrDefault(x => x.AzureTokenId == tenantId) == null)
throw new GeneralErrorException("Account not found", "The domain that you used to authenticate has not registered.");
appAnalyzerUser = (from au in dbContext.AppAnalyzerUsers
.Include(x => x.Roles)
where au.UserPrincipalName == upn && au.AzureTokenId == tenantId
select au).FirstOrDefault();
if (appAnalyzerUser == null)
throw new AccountNotFoundException();
}
foreach (var role in appAnalyzerUser.Roles)
{
Claim roleClaim = new Claim(ClaimTypes.Role, role.RoleName);
context.AuthenticationTicket.Identity.AddClaim(roleClaim);
}
return Task.FromResult(0);
},
I've decorated some methods with the Authorize attribute like this:
[Authorize(Roles = "SystemAdministrator"), HttpGet]
public ActionResult Index()
{
return View();
}
and the authorize attribute correctly detects that a user is not in that role and sends them back to Azure to authenticate.
However what I see is that the user is already authenticated against Azure AD and is logged in to the app. They don't get the chance to choose a new user account on the Azure screen to log in. So when it bounces them back to Azure AD, Azure AD says "you're already logged in" and sends them right back to the app. The SecurityTokenValidated event fires repeatedly, over and over.
But the user still doesn't have the role required for the method, so they get bounced back to Azure for authentication, and obviously we get stuck in a loop.
Other than writing my own implementation of the Authorize attribute, is there some other approach to solve this problem?
Unfortunately you stumbled on a known issue of [Authorize]. For a description and possible solutions see https://github.com/aspnet/Mvc/issues/634 - at this point writing a custom attribute is probably the most streamlined workaround.

Resources