I am stuck on a problem that i cannot think my way out of and have searched everywhere online for answers to no avail.
Here is the problem:
I usually embed PowerBI reports in asp.net application. I follow the Microsoft tutorial. Where we registered an azureAD app as service principal. And we use the Microsoft.Identity.Web library to authenticate our users as well as authenticate as the app's service principal for accessing PowerBI reports.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();
builder.Services.AddScoped(typeof(PowerBiServiceApi));
The problem now is that I am building an app that doesn’t authenticate with the Microsoft.Identity.Web but will actually be authenticating users using individual accounts/ ADFS and federation service.
The problem is that I am unable to do token acquisition by authenticating as the app's service principal.
.AddOpenIdConnect(options =>
{
options.ClientId = "xxxxx-xxxxx-xxx-xxx-xxxxxx";
options.Authority = "https://xxxxxxxxxxx";
options.SignedOutRedirectUri = "https://localhost:xxxx/";
options.Events = new OpenIdConnectEvents
{
OnRemoteFailure = OnAuthenticationFailed,
};
})
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();
However when I am unable to run this app and embed successfully.
My main question is:
is it possible to authenticate my users with one authentication provider (ADFS federation service via openID or wsFederation )
whilst also doing using Microsoft.Identity to do token acquisition
Thus far I've had success with using OpenIDConnect directly with ADFS and MSAL library to get tokens (also from ADFS) for downstream api's. For entries in ADFS using a client secret (i.e. server apps) I would use the IConfidentialClientApplicationBuilder, whereas native apps would use IPublicClientApplicaationBuilder.
This means I never need nor can use this code:
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi() .AddInMemoryTokenCaches();
Related
I have an ASP.NET Core (3.1) web API with a couple of client UI apps. Authentication is via Azure AD, everything is working, using:
services.AddAuthentication()
.AddAzureADBearer(options => Configuration.Bind("AzureAD", options))
I also want to allow machine to machine API access using the Client Credentials flow. I can also get this working using the same app registration.
However, I need a way to validate which flow the request is using, as I want to expose functionality using Client Credentials API to API requests that I don't want interactive users to have access to.
What is the best way to make this work?
I have created a separate app registration in AAD that the Client Secret for the Client Credentials grant is on, and I have it adding permissions (as roles) to the token. And in the app registration for the API, I have granted permission to the Client Credentials app registration. But if I obtain a token with this flow, I can't authenticate. I have found that changing the scope in the token request to match the scope on the API app registration gives me a token that allows me to access the API, but then it is missing the app roles.
One the interactive token there are some user specific claims. So one workaround would be to check for the presence of these claims and disallow the functionality I want to restrict if they are present, but this seems a little hacky.
What else can I do? Is there a way to make both login flows work? Or another option that I've missed?
In case anyone else needs to get this working, I got it working by switching from:
services.AddAuthentication()
.AddAzureADBearer(options => Configuration.Bind("AzureAD", options))
to:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MetadataAddress = $"https://login.microsoftonline.com/mydomain.onmicrosoft.com/.well-known/openid-configuration";
options.TokenValidationParameters.ValidateAudience = false;
});
There are some additional steps too, as mentioned in the question. I created a separate app registration in AAD, and in the app registration for the API granted permission to the new app registration. In the new app registration I had to edit the manifest to get the scope I wanted included as a role (scopes are only assigned to user tokens, not tokens obtained with the client credentials grant).
With the token working that has the role data, for requests to my restricted endpoint I can just check that it's there:
public bool ValidateScope(string scopeName)
{
return _httpContextAccessor.HttpContext.User.IsInRole(scopeName);
}
bool authorised = _clientCredentialsService.ValidateScope("restricted");
if (!authorised)
{
throw new UnauthorizedAccessException("Attempt to access restricted functionality as a regular user");
}
(I have a filter that picks up this exception and bubbles it up to the consumer as a 403).
If anyone else is doing this you can see I've set ValidateAudience to false, so you probably want to add some policies if you do this.
Currently, I have created an Identity server 4 web application with external login providers with default client id and secrets.
But my goal is to register the authentication providers like Azure, Google, Facebook based on tenant.
I have used SaasKit multi-tenancy assembly, here I have tried app.usepertenant() middleware. But UseGoogleAuthentication() method is obsolete, so i could not achieve multi-tenant authentication using this usepertenant middleware.
Current code,
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddMicrosoftAccount(option =>
{
option.ClientId = "clientid";
option.ClientSecret = "clientsecret";
option.SaveTokens = true;
});
Expected code is like below,
var authentication = services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
if (tenant.hasMicrosoft)
{
authentication.AddMicrosoftAccount(option =>
{
option.ClientId = "clientid";
option.ClientSecret = "clientsecret";
option.SaveTokens = true;
});
}
if (tenant.hasGoogle)
{
authentication.AddGoogle(option =>
{
option.ClientId = "clientid";
option.ClientSecret = "clientsecret";
option.SaveTokens = true;
});
}
authentication.AddCookie( options =>
{
options.SlidingExpiration = true;
options.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0);
});
See the official MS docs, Authentication providers per tenant
ASP.NET Core framework does not have a built-in solution for multi-tenant authentication. While it's certainly possible for customers to write one, using the built-in features, we recommend customers to look into Orchard Core for this purpose.
Since authentication needs to be configured during DI registration, you will have to setup all external login providers in general during registration of authentication.
During that step, you need to add all schemes. A scheme has a fixed client-id/secret, so you need to bootstrap your IdentityServer with all external login provider credentials, that you support for all of your clients. The scheme name needs to be unique.
As an example, tenant A might have a scheme "A_microsoft", tenant B might have a scheme "B_microsoft", etc.
You can then refer to those authentication schemes, when calling methods in IdentityServer. SignIn, Challenge, SignOut etc.
Be aware, that this will require bootstrapping IdentityServer a complete set of tenants. Depending on your scenario, if tenants are updated regularly, it will also require regular restarts of the IdentityServer to be aware of new authentication schemes.
If that is a problem, you can probably somehow augment the registered authentication schemes during the runtime of IdentityServer, but it's not going to be easy. It might require larger custom implementations of the authentication middleware coming with AspNetCore.
Do you mean you want to add support for multiple authenticate provider? This Document already specified how to add multiple auth provider in config service. No need to use app.UseXXX anymore to config the pipeline by yourself
I have a web application that implements both MVC controllers and webapi controllers. This web application uses Microsoft account authentication based on external cookies.
Now I want to query the webapi from a native (desktop) application using MSAL to authenticate the users against the Microsoft identity platform.
I tried to do this adding the following code to use bearer authentication: app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
}
});
I can authenticate the client through the PublicClientApp.AcquireTokenInteractive method and use the resulting AccessToken for compounding the Authorization header, but the webapp responds with a 401 error code.
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
var response = httpClient.SendAsync(request).Result;
In summary, the goal is not use both cookies and bearer authentication at the same time, but to have a unique web application using MVC that:
Could serve web pages with an authorization mechanism
Could publish a REST based API (through WebAPI) using the same authorization mechanism, that:
Authenticates against Microsoft Azure AD accounts
Could be consumed by Desktop clients
Could be consumed by the previous web app pages for displaying dynamic content.
I'm getting lost in OAuth and OpenIDConnect and aspnet core middleware. Any help on this would be appreciated.
I have multiple UIs (web, native apps) that use the same set of web services, and I'd like to ensure only authenticated users can access the web services. My organization uses Google accounts, so I'd like to use Google authentication restricted to the organization domain.
The web site is properly requiring authentication, following this sample. What I need now is to have the web site (AngularJS 4) invoke my back end web services with an auth token that I can verify with Google.
The back end services are written with aspnet core. I've tried using these approaches: Google middleware and Google OpenIDConnect but these still 1) assume there is a UI that can prompt an unauthorized user to log in, and 2) appear to be cookie-based, and I won't have cookies for the web service calls.
I don't want to prompt the user to log in, since the "user" in this case is a software client. Either they're authenticated or not already. I just need to get the authentication token, validate it, and carry on.
This appears to be the same question, which hasn't been answered yet, either.
Any suggestions are appreciated. Also, suggestions or tips on having native apps do the same!
Got it working. As mentioned, I was getting lost, and the OpenIDConnect, though referenced in several areas as a solution, was a red herring for the web services. Here's what is working for me now, with as complete steps as I can provide (some cleanup required):
Add authentication to the UI following these directions
Obtain the JWT token as shown in the first segment here
On each web service call, include the JWT token in the headers:
Name: Authentication
Value: Bearer {token value}
Install the JwtBearer NuGet package
In the ConfigureServices method of Startup in the web service, after you AddMvc():
services.AddAuthorization(options =>
{ // this policy needed only if you want to restrict to accounts within your domain. otherwise, don't use options. or use whatever options work for you.
options.AddPolicy("hd",
policy => policy.RequireAssertion(context =>
context.User.HasClaim(c =>
c.Type == "hd" &&
("https://accounts.google.com".Equals(c.Issuer) ||
"accounts.google.com".Equals(c.Issuer, StringComparison.CurrentCultureIgnoreCase)) &&
c.Value == "yourdomain.com"
)));
});
In the Configure method, before you UseMvc():
JwtBearerOptions jwtOptions = new JwtBearerOptions();
jwtOptions.Audience = "{the OAuth 2.0 client ID credential from google api developer console}";
jwtOptions.Authority = "https://accounts.google.com";
jwtOptions.TokenValidationParameters = new TokenValidationParameters();
jwtOptions.TokenValidationParameters.ValidIssuers = new List<string>()
{
"https://accounts.google.com",
"accounts.google.com"
};
app.UseJwtBearerAuthentication(jwtOptions);
Perhaps there is a more appropriate way to do this...if there is, I'm interested in trying it out. For now, this is working.
I will try to help.
First you need to look at OpenID Connect (which is built on top of OAuth 2.0) remembering that OAuth 2.0 NOT an Authentication protocol.
1) assume there is a UI
No UI is required for login assuming you are using Google services. You only need to check for the existence of and validate the Access Token, Identity Token (and perhaps the refresh token). If there is no Token, assume the user is NOT Authenticated and redirect them to the Authentication Server with a Authorization Request.
If there is a valid Access Token and Refresh Token, then you can assume the user is Authenticated.
You can also inspect the Access Token for proper "Scopes" to determine if they are Authorized for your specific application.
If you are using Google for Authorization Server, you can validate the the hd parameter within Identity Token has the desired Domain.
BTW: No cookies involved.
Hope that helps.
We have an environment with the following:
Standalone IdentityServer3 instance (issues reference tokens, not jwt)
ASP.NET WebAPI resource server
.NET client applications that authenticate against IdSvr (via resource owner flow)
...and now we'd like to start adding an OWIN-hosted web app that will use NancyFx to serve server-rendered pages as well as a couple AngularJS SPAs. This Nancy website will NOT host any APIs, but may consume data from our existing API. I'd like to add authentication in the OWIN pipeline to help secure our Angular applications from being sent down to users who don't have access.
This would be in contrast to sending down the SPA code, and having Angular determine if the user should see anything. In that case we've already exposed the javascript code base, and this we want to avoid.
I'm trying to understand how I should configure this Nancy site to authenticate users against IdentityServer using the implicit flow. I have implemented this authentication scheme in standalone SPAs before (where all authentication was handled by AngularJS code and tokens were stored in HTML5 local storage), but I'm a bit lost on how to properly tackle this within the OWIN pipeline.
I'm thinking that the OWIN cookie authentication middle-ware is the answer, but does that mean the following?
I need to redirect the user to IdentityServer (using the proper url arguments for implicit flow)?
IdentityServer will redirect the user back to my site on a successful login, so is that where I hook into the OWIN Authorization manager to set the appropriate cookie?
...or am I thinking about this all wrong?
For reference, I've read through the following posts, and they're very helpful but I'm not quite seeing the big picture with OWIN. I'm going to experiment with the UseOpenIdConnectAuthentication middle-ware next, but I would appreciate any guidance SO might have here.
http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/
https://github.com/IdentityServer/IdentityServer3/issues/487
Fundamentally, implementing OpenID Connect authentication in a Nancy app hosted via OWIN is really not different from implementing it in any MVC/Katana app (the Thinktecture team has a sample for this scenario: https://github.com/IdentityServer/IdentityServer3.Samples/tree/master/source/Clients/MVC%20OWIN%20Client)
You basically need 3 things: the cookie middleware, the OpenID Connect middleware and the Nancy middleware:
public class Startup {
public void Configuration(IAppBuilder app) {
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationMode = AuthenticationMode.Active,
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
AuthenticationMode = AuthenticationMode.Active,
// Set the address of your OpenID Connect server:
Authority = "http://localhost:54541/"
// Set your client identifier here:
ClientId = "myClient",
// Set the redirect_uri and post_logout_redirect_uri
// corresponding to your application:
RedirectUri = "http://localhost:56765/oidc",
PostLogoutRedirectUri = "http://localhost:56765/"
});
app.UseNancy(options => options.PerformPassThrough = context => context.Response.StatusCode == HttpStatusCode.NotFound);
}
}
If you're looking for a functional demo, you can take a look at https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev/samples/Nancy/Nancy.Client (note: it doesn't use IdentityServer3 for the OIDC server part but it shouldn't make any difference for the client app).