I want to validate user credential from Azure AD. It works for users who haven't enable MFA.but MFA enabled users getting below error.
Due to a configuration change made by your administrator, or because
you moved to a new location, you must use multi-factor authentication
to access
So it need a way to ignore MFA ,when we accessing though the graph API
this is my code.
var values = new Dictionary<string, string>
{
{ "grant_type", "password" },
{ "client_secret", appKey },
{ "client_id", clientId },
{ "username", userName },
{ "password", password },
{ "scope", "User.Read openid profile offline_access" },
};
HttpClient client = new HttpClient();
string requestUrl = $"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token";
var content = new FormUrlEncodedContent(values);
var response = client.PostAsync(requestUrl, content).Result;
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
return false;
}
The correct way to validate user credentials is have the user authenticate interactively through a browser.
This will allow them to go through MFA, login through federation with ADFS etc.
And most importantly, the users do not have to give their password to your app.
The flow you are trying to use only exists in the spec as an upgrade path for legacy applications.
Its usage becomes essentially impossible once MFA is enabled.
Related
I have a WPF app (.net 462 & API .net5.0).
I have set the openid on the api and this work, the permission work, but on the WPF app i have to check the permission for app element (menu access, button access).
Getting the token work, but i don't know how to valid a scope when openid
Key clock config :
Realm => demo-test
Client => demo-test-client
Client Role => DemoRole
Authorization Scope => demo:read
Associated Permissions => Permission demo:read
Associated Policy for role => DemoRole - Positive
I have create two user "user-test-ok" & "user-test-ko", "user-test-ok" have the client role "DemoRole".
I have test to user the introspection for validate the user have the scope "demo:read", but this not work.
I don't want use keycloak API, i want use the openid system for possibly change keycloak by other OAuth2.0 system.
This is my code to try to check the authorization scope :
var requestUri = new Uri($"https://localhost:8443/auth/realms/{realm}/protocol/openid-connect/token/introspect");
using (var client = new HttpClient())
{
var req = new HttpRequestMessage(HttpMethod.Post, requestUri);
req.Headers.Add("cache-control", "no-cache");
req.Headers.Add("accept", "application/x-www-form-urlencoded");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
req.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "token_type_hint", "requesting_party_token" },
{ "token", tokenResult.AccessToken },
{ "client_id", clientId },
{ "client_secret", clientSecret },
{ "scope", "test:read" },
});
var response = client.SendAsync(req).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception();
}
var responseString = response.Content.ReadAsStringAsync().Result;
}
Did you have any idea how to do it?
If I read the token introspection endpoint documentation here, then it says nothing about passing the scope ({ "scope", "test:read" },) as a parameter. Instead you take what you get back from that request and then you first check if the active claim is true. That signals that the token is still active and valid..
Then you just examine the data that is returned. Or you just use the scope value inside the access or ID-token to give the user access to the features in the application.
Do, check what the request returns in a tool like Fiddler.
I'm using .NET Core 3.1 with Identity Server 4 and connecting to Azure AD via OpenIdConnect. I'm using a Vue.js front-end and .NET Core API. IdentityServer, the front-end, and the API are all hosted on-prem on the same server (same domain). Everything uses https. I'm using an Oracle database with EF model first, with fully-customized IdentityServer stores and a custom user store (I implemented the interfaces). I'm using IdentityServer's Quickstart, edited a little to hook up my custom user store instead of the test user. I'm running this in my dev environment.
If I type in the url to the IdentityServer, I'm redirected to Azure AD, signed-in successfully, and shown this page:
Grants - successful login
The claims are coming back from Azure AD and the auto-provisioning is successful. It is written successfully to the database.
Authenticating through my JS client hits IdentityServer, redirects to Azure AD, I sign-in, then it redirects to IdentityServer's ExternalController, then redirects back to a Microsoft url, then proceeds to repeat until it finally fails with this page:
Sign-in failure from Azure AD
My guess is I messed up a redirect uri somewhere. Here is my code and the IdentityServer log:
IdentityServer Log
That block of logging repeats 6-10 times. No errors or anything different at the end.
I had to break up the C# code because the site couldn't handle one of my long options lines.
IdentityServer Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
options.UserInteraction.LoginUrl = "/Account/Login";
options.UserInteraction.LogoutUrl = "/Account/Logout";
options.Authentication = new AuthenticationOptions()
{
CookieLifetime = TimeSpan.FromHours(10),
CookieSlidingExpiration = true
};
}).AddClientStore<ClientStore>()
.AddCorsPolicyService<CorsPolicyService>()
.AddResourceStore<ResourceStore>()
.AddPersistedGrantStore<PersistedGrantStore>()
.AddProfileService<UserProfileService>();
services.AddScoped<IUserStore, UserStore>();
if (env.IsDevelopment())
{
// not recommended for production
builder.AddDeveloperSigningCredential();
}
else
{
// TODO: Load Signing Credentials for Production.
}
services.AddAuthentication()
.AddOpenIdConnect("aad", "Azure AD", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.SignOutScheme = IdentityServerConstants.SignoutScheme;
options.Authority = "https://login.windows.net/[authority]";
options.CallbackPath = "/callback-aad";
options.ClientId = "[ClientId]";
options.RemoteSignOutPath = "/signout-aad";
options.RequireHttpsMetadata = true;
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.SaveTokens = true;
options.SignedOutCallbackPath = "/signout-callback-aad";
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};
options.UsePkce = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseStaticFiles();
app.UseSerilogRequestLogging();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Client OIDC config:
const oidcSettings = {
authority: '[IdentityServerUrl]',
client_id: '[ClientId]',
post_logout_redirect_uri: '[front-end url]/logout-aad',
redirect_uri: '[front-end url]/callback-aad',
response_type: 'code',
save_tokens: true,
scope: 'openid profile',
}
Callback method being hit for ExternalController:
[HttpGet]
public async Task<IActionResult> Callback()
{
// read external identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
if (_logger.IsEnabled(LogLevel.Debug))
{
var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}");
_logger.LogDebug("External claims: {#claims}", externalClaims);
}
// lookup our user and external provider info
var (user, provider, providerUserId, claims) = await FindUserFromExternalProvider(result);
if (user == null)
{
// this might be where you might initiate a custom workflow for user registration
// in this sample we don't show how that would be done, as our sample implementation
// simply auto-provisions new external user
user = await AutoProvisionUser(provider, providerUserId, claims);
}
// this allows us to collect any additional claims or properties
// for the specific protocols used and store them in the local auth cookie.
// this is typically used to store data needed for signout from those protocols.
var additionalLocalClaims = new List<Claim>();
var localSignInProps = new AuthenticationProperties();
ProcessLoginCallback(result, additionalLocalClaims, localSignInProps);
// issue authentication cookie for user
var isuser = new IdentityServerUser(user.SubjectId)
{
DisplayName = user.Username,
IdentityProvider = provider,
AdditionalClaims = additionalLocalClaims
};
await HttpContext.SignInAsync(isuser, localSignInProps);
// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
// retrieve return URL
var returnUrl = result.Properties.Items["returnUrl"] ?? "~/";
// check if external login is in the context of an OIDC request
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.SubjectId, user.Username, true, context?.Client.ClientId));
if (context != null)
{
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", returnUrl);
}
}
return Redirect(returnUrl);
}
Azure AD config:
redirect uri: [IdentityServer url]/callback-aad
Database table data:
Client table IMG1
Client table IMG2
ClientScopes table
ClientRedirectUris table
Please let me know if you need any additional information. Thank you
The problem was in my custom UserStore. I was getting the user by the Azure AD SubjectId instead of the UserSubjectId. So in the ExternalController, the ApplicationUser object was coming up as null. Instead of an exception, it kept going back to Azure AD to try to get the user again, but obviously that just creates an infinite loop. I didn't think to look there since my user was successfully provisioned with Id's and claims.
I want to protect all of my APIs using only one identityserver4 applcation.
My sirst resource api and client applications:
CustomerManagementApi
CustomerManagement.JavascriptApplication
CustomerManagement.iOSApp
CustomerManagement.AndroidApp
My Second resource api and applications:
HumanResourceApi
HumanResource.MVCApplication
My Other resource api and applicaitons:
DashboardApi
Dashboard.AngularApplication
I want to create only one IdentityServer4 and secure my reousrces (DashboardApi,HumanResourceApi,CustomerManagementApi) and I want save my client applications on same IdentityServer4 applicaitons.
Is this possible? Should I create different ApiResources and Scopes on identityserver? How can I do this?
Yes, it is possible because IdentityServer4 enables you to define Resource Apis, Client applications, Users, Scopes and you can configure these data using in memory data for initial tests or even other storage mechanism like Entity Framework for example.
It is not simple to explain here, but in the official documentation there are some quickstarts that you can do to learn more.
You can see above some examples of configurations for Resource Apis, Client applications, Users in memory (using a Config.cs class) just to give you an idea about how it can be simple to start:
Resource Apis: the protected apis that Clients wants to access
public static IEnumerable<ApiResource> GetApis()
{
return new List<ApiResource>
{
new ApiResource("CustomerManagementApi", "My CustomerManagementApi"),
new ApiResource("DashboardApi", "My DashboardApi"),
// others ...
};
}
Clients: applications that wants to access the Resource Apis
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes = GrantTypes.ClientCredentials,
// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},
// scopes that client has access to
AllowedScopes = { "CustomerManagementApi" }
}
};
}
Users: end users that wants to access some resource
public static List<TestUser> GetUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId = "1",
Username = "alice",
Password = "password"
},
new TestUser
{
SubjectId = "2",
Username = "bob",
Password = "password"
}
};
}
I have an application web MVC that uses AAD to authenticate, But I need the same application to be used as B2C.
Is there any way to configure it or should I create a page for the user to choose by which directory to authenticate.
Is there any way to configure it or should I create a page for the user to choose by which directory to authenticate.
Based on my understanding, we need to provide a way to provide users to choose the identity data provider they want to authentication if the web app provide multiple identity data providers. For example, we can provide two buttons or a custom login page as you mentioned in above.
Here is a piece of custom code which provide users select the login way using two buttons from the code sample here.
_LoginPartial.cshtml(Add the UI to choose identity data provider):
<ul class="nav navbar-nav navbar-right">
<li>#Html.ActionLink("Sign up", "SignUp", "Account", routeValues: null, htmlAttributes: new { id = "signUpLink" })</li>
<li>#Html.ActionLink("Sign in", "SignIn", "Account", routeValues: new { b2c=false}, htmlAttributes: new { id = "loginLink" })</li>
<li>#Html.ActionLink("Sign in B2C", "SignIn", "Account", routeValues: new { b2c = true }, htmlAttributes: new { id = "loginLink" })</li>
</ul>
Startup.Auth.cs(Provider two identity data providers)
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
// Configure OpenID Connect middleware for each policy
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpPolicyId));
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
//config for normal azure ad
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = "{AzureADClientId}",
Authority = "https://login.microsoftonline.com/xxx.onmicrosoft.com",
PostLogoutRedirectUri = redirectUri,
RedirectUri = redirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
AccountController.cs( Redirect to the identity data provider based on the choosing of users)
public void SignIn(bool b2c)
{
if (!Request.IsAuthenticated)
{
if (b2c)
{
// To execute a policy, you simply need to trigger an OWIN challenge.
// You can indicate which policy to use by specifying the policy id as the AuthenticationType
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties() { RedirectUri = "/" }, Startup.SignInPolicyId);
}
else
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
Hope it helps.
I am using Azure B2C with one identity provider configured (LinkedIn). I have a Web API (b2c bearer auth) and a Web App MVC (b2c Open Id).
I'm trying to create a persistent login - meaning the user can login via LinkedIn once every 90 days from the given device+browser.
The closest I've gotten is when I added IsPersistent = true code in the web app to enable that:
Update: Updated code based on Azure B2C GA. To achieve where I was at with Preview, I still use a custom authorize attribute, but the code was updated:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties()
{
IsPersistent = true
});
base.HandleUnauthorizedRequest(filterContext);
}
However, this is only valid for about 1 hour. Perhaps it is following the Access & ID policy? With no bounds on the refresh token - I am not sure why only 1 hour for "IsPersistent".
Token Session Config in Azure
So that leads to these questions:
Is a Persistent session (60-90 days) something I can achieve with Azure B2C (OpenId Connect)?
If so, any pointers on what I am missing? Do I need to do some custom cookie validation? Something with refresh tokens (I use them for the web api, but nothing custom in the web app).
Any thoughts or input would be great!
I have been able to achieve a persistent session with B2C after doing the following:
Custom Authorization Attribute
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.HttpContext.GetOwinContext()
.Authentication.Challenge(
new AuthenticationProperties() { IsPersistent = true }
);
base.HandleUnauthorizedRequest(filterContext);
}
Use Microsoft.Experimental.IdentityModel.Clients.ActiveDirectory instead of BootstrapContext (basically went with the pre-GA code sample (view change history) -> https://github.com/AzureADQuickStarts/B2C-WebApp-WebAPI-OpenIDConnect-DotNet). The ADAL library handles the getting a proper token transparent to my code.
Implemented custom TokenCache (based the EFADAL example here: https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-multitenant-openidconnect/blob/master/TodoListWebApp/DAL/EFADALTokenCache.cs)
Changed Startup.Auth.cs:
return new OpenIdConnectAuthenticationOptions
{
MetadataAddress = String.Format(aadInstance, tenant, policy),
AuthenticationType = policy,
UseTokenLifetime = false,
ClientId = clientId,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed,
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
},
Scope = "openid offline_access",
ResponseType = "code id_token",
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
SaveSigninToken = true,
},
}