Following the documentation example on microsoft for the adfs setup.
ADFS microsoft setup
I have the following application .Net 4.6.
startup.cs
app.UseMyAppApiAuthentication(config);
in the class
//setup OpenIdConnect Authentication
var options = config.DependencyResolver.GetService<OpenIdConnectAuthenticationAndNotificationOptions>();
app.UseOpenIdConnectAuthentication(options);
In the options class i have
ClientId = configProvider.GetOpenIdConnectClientId();
Authority = configProvider.GetOpenIdConnectAuthority();
PostLogoutRedirectUri = configProvider.GetOpenIdConnectPostLogoutRedirectUri();
RedirectUri = configProvider.GetOpenIdConnectRedirectUri();
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthorizationCodeReceived = authenticationNotificationProcessor.OnAuthorizationCodeReceived,
AuthenticationFailed = authenticationNotificationProcessor.OnAuthenticationFailed
};
where authority is
public string GetOpenIdConnectAuthority()
{
var instance = ConfigurationManager.AppSettings["moto:AADInstance"];
var tenant = ConfigurationManager.AppSettings["moto:Tenant"];
return String.Format(CultureInfo.InvariantCulture, instance, tenant);
}
In the webconfig, I have the clientid and client secret set, I have the AADinstance set and tenant is blank.
If I put in the ADFS URI. I get the following error:
Now if I edit the AADinstance and add /.well-known/Openid-configuration i get a different error...
I have also changed the config and removed authority and replace with "MetadataAddress" still no change.
What do I need todo to resolve this issue?
Note: if I change the redirect URI to something different when running the app, I manage to get to the adfs login screen with the error that there is a mismatch with the redirect.
I recommend you to open a support case since it needs deep troubleshooting in order to isolate the issue.
Related
I'm trying to connect to an Azure AD server with an Umbraco website.
To start off, I have no knowledge of Azure. There is a third party who administers the Azure part.
We use OWIN to connect to Azure via OpenID.
OnStartup:
public void ConfigureAuth(IAppBuilder app){
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions{
// Sets the ClientId, authority, RedirectUri as obtained from web.config
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Scope = OpenIdConnectScope.OpenIdProfile,
ResponseType = OpenIdConnectResponseType.IdToken,
TokenValidationParameters = new TokenValidationParameters(){
ValidateIssuer = false
},
Notifications = new OpenIdConnectAuthenticationNotifications{
AuthenticationFailed = OnAuthenticationFailed
}
});
}
The SignIn function in the SurfaceController:
public void SignIn(string ReturnUrl = "/"){
if (!Request.IsAuthenticated) {
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = ReturnUrl },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
Here come the non-working part.
If I test this site at a local domain (only available from within our office), it works.
If I test this site on a publicly-available staging domain, it works.
If I test this site on a live domain, it works.
But as soon as I change a sub-domain, I get send to the working domain with a "RequireNonce" error.
So for example:
https://customer.localdomain.com -> login -> I return logged in at https://customer.localdomain.com.
https://test.localdomain.com -> login -> I return to https://customer.localdomain.com (notice the domain), with a "Nonce-error".
https://customer.stagingdomain.com -> login -> I return logged in at https://customer.stagingdomain.com.
https://test.stagingdomain.com -> login -> I return to https://customer.stagingdomain.com (notice the domain), with a "Nonce-error".
https://www.livedomain.com -> login -> I return logged in at https://www.livedomain.com.
https://test.livedomain.com -> login -> I return to https://www.livedomain.com (notice the domain), with a "Nonce-error".
The complete error is:
IDX21323:
RequireNonce is '[PII is hidden]'.
OpenIdConnectProtocolValidationContext.Nonce was null,
OpenIdConnectProtocol.ValidatedIdToken.Payload.Nonce was not null.
The nonce cannot be validated.
If you don't need to check the nonce, set OpenIdConnectProtocolValidator.
RequireNonce to 'false'. Note if a 'nonce' is found it will be evaluated.
What can we do to resolve this problem? Our customer has a couple of subdomains (seperate sites) that all need this login functionality.
We've tried adding subdomains to a reply-list in Azure (well, the third party added them for us), but that didn't solve the problem.
Is it possible to just turn RequireNonce off somewhere?
Thank you JamesHamil-MSFT Posting your suggestion as an answer to help other community members .
"The problem was that the time or automatic reference program service binding a custom domain name.
After the application network management is configured. The Host IP that modifies the custom domain name points to a public IP that is gateway."
Please try checking that your domain is configured correctly and points to the correct gateway."
Please refer the below links for further information:
. Configure App Service with Application Gateway using PowerShell | MS DOC .
. SO THREAD for similar issue.
This follows on from a previous post which started as a general issue and is now more specific.
In short, I've been following guidance (such as this from Microsoft, this from Scott Hanselman, and this from Barry Dorrans) to allow me to share the authentication cookie issued by a legacy ASP.NET web app with a new dotnet core app running on the same domain.
I'm confident that I'm using the recommended Microsoft.Owin.Security.Interop library correctly. On that side (the old ASP.NET app), the CookieAuthenticationOptions are configured with AuthenticationType and CookieName both set to the same value - SiteIdentity. This same value is also used in the interop data protector setup:
var appName = "SiteIdentity";
var encryptionSettings = new AuthenticatedEncryptorConfiguration
{
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
};
var interopProvider = DataProtectionProvider.Create(
new DirectoryInfo(keyRingSharePath),
builder =>
{
builder.SetApplicationName(appName);
builder.SetDefaultKeyLifetime(TimeSpan.FromDays(365 * 20));
builder.UseCryptographicAlgorithms(encryptionSettings);
if (!generateNewKey)
{
builder.DisableAutomaticKeyGeneration();
}
});
ShimmedDataProtector = new DataProtectorShim(
interopProvider.CreateProtector(
"Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
appName,
"v2"));
I log in using this app, confirm I have a cookie named SiteIdentity then switch to a new dotnet core app running on the same domain.
There, without adding authentication middleware I can confirm that I can unprotect and deserialize the cookie. I do this by setting up data protection in Startup to match the other app:
var appName = "SiteIdentity";
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(keyRingSharePath))
.SetDefaultKeyLifetime(TimeSpan.FromDays(365 * 20))
.DisableAutomaticKeyGeneration()
.UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration()
{
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
})
.SetApplicationName(appName);
Then in my controller I can use a data protector to manually unprotect the cookie:
var appName = "SiteIdentity";
var protector = _dataProtectionProvider.CreateProtector(
"Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
appName,
"v2");
var cookieValue = Request.Cookies[appName];
var format = new TicketDataFormat(protector);
var ticket = format.Unprotect(cookieValue);
I can confirm that ticket.Principal does indeed reference a claims principal representing the account which I signed in with on the other app.
However, I've found it impossible to wire up the cookie authentication middleware to properly protect my endpoints using this cookie. This is what I've added to Startup, after the data protection code above:
var protectionProvider = services.BuildServiceProvider().GetService<IDataProtectionProvider>();
var dataProtector = protectionProvider.CreateProtector(
"Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
appName,
"v2");
services
.AddAuthentication(appName)
.AddCookie(appName, options =>
{
options.TicketDataFormat = new TicketDataFormat(dataProtector);
options.Cookie.Name = appName;
});
By my understanding this is telling the middleware that I have an authentication scheme named "SiteIdentity" (the advice is that authentication scheme must match the ASP.NET authentication type) which expects a cookie also called "SiteIdentity" which will contain protected data that the supplied data protector can interpret.
But when I add the attribute [Authorize(AuthenticationSchemes = "SiteIdentity")] to my controller I'm kicked away to a login page.
I can't understand what I'm doing wrong. As I've shown, I can confirm that it is indeed possible to use this data protector and ticket format to interpret the authentication cookie, so I guess I must have something wrong in this middleware wiring, but I'm not sure what.
Please ignore. It turns out that my code is actually correct. I had been working on this solution for long enough that the session represented by the cookie value I was using to test had expireed. Will leave this question here in case the code benefits anyone trying to achieve the same.
I know there are several other posts listed about this topic but I cannot seem to find any useful info in them to apply to my own application. I am building a .Net MVC Web App that uses the Microsoft Graph API. I followed another project (https://github.com/microsoftgraph/aspnet-snippets-sample) but when I launch the application, it redirects to https://login.microsoftonline.com where it attempts to log in using a Microsoft work account, and redirects back to the homepage. However, after entering Microsoft account credentials and before being redirected back, I am shown an error:
.
Below is a section from my Startup.Auth.cs that I believe is causing the problems. If anyone can see anything that seems off or has any insight on this topic, I would greatly appreciate it. I have been spinning my wheels just trying to sign-in to this application using Open Id Connect to be able to use the Microsoft Graph API. Thanks!
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
// The `Authority` represents the v2.0 endpoint - https://login.microsoftonline.com/common/v2.0
// The `Scope` describes the permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/
ClientId = appId,
* * Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"), * *
RedirectUri = redirectUri,
Scope = scopes,
PostLogoutRedirectUri = redirectUri,
TokenValidationParameters = new TokenValidationParameters {
ValidateIssuer = false,
},
Notifications = new OpenIdConnectAuthenticationNotifications {
AuthorizationCodeReceived = async(context) => {
var code = context.Code;
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
string graphScopes = nonAdminScopes;
string[] scopes = graphScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
ConfidentialClientApplication cca = new ConfidentialClientApplication(appId, redirectUri,
new ClientCredential(appSecret),
new SessionTokenCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(), null);
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
// Check whether the login is from the MSA tenant.
// The sample uses this attribute to disable UI buttons for unsupported operations when the user is logged in with an MSA account.
var currentTenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
if (currentTenantId == "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") {
HttpContext.Current.Session.Add("AccountType", "msa");
}
// Set IsAdmin session variable to false, since the user hasn't consented to admin scopes yet.
HttpContext.Current.Session.Add("IsAdmin", false);
},
AuthenticationFailed = (context) => {
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
This error is usually caused by an incompatibility between your app registration and the authentication library you are using.
The code in that sample is using the Microsoft Authentication Library (MSAL), which uses the Azure V2 OAuth endpoints, which supports converged auth (both Azure AD accounts and Microsoft accounts). In order for the v2 auth endpoints to work, your app registration MUST come from https://apps.dev.microsoft.com.
If you register your app on the Azure portal (https://portal.azure.com), you'll see this error. That's because the Azure portal registers the app using the Azure v1 OAuth schema.
There is also a case where the https://apps.dev.microsoft.com portal can create a v1 registration. If you login to that portal and you see more than one grouping of apps, with multiple "Add an app" buttons, you need to choose the "Add an app" button for Converged Apps.
If you are using microsoftgraph/msgraph-sdk-dotnet-auth for getting access token, then /common endpoint is valid.
If you are using AzureAD/microsoft-authentication-library-for-java for getting access token, then use /organizations endpoint instead of /common.
Unfortunatelly adding Converged Apps from https://apps.dev.microsoft.com/ is no longer supported by MS. They redirect to Azure portal from there.
I have a subscription to azure and an already developed application, I'm trying to use Azure AD as authentification mechanism.
I created the application in Azure, added Azure AD as authentification mechanism and when I try to log in I get this error.
AADSTS65005: The app needs access to a service
("http://rts.powerapps.com") that your organization
"123-32323-323232-3233" has not subscribed to or enabled. Contact your
IT Admin to review the configuration of your service subscriptions.
This is my Startup Class.
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
RedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
}
Any ideas?
EDIT 1:
After removing some app from my required permissions that appeared deleted now I get this error.
Error Img
EDIT 2:
Fixed after removing and adding the permissions again.
It seems that you were developing with Common Data Service, based on the service("http://rts.powerapps.com"). Please ensure that that your organization doesn't have the subscribed the service ("http://rts.powerapps.com").
Please note the prerequisites of Common Data Service:
If you've already signed up for PowerApps, you can go to PowerApps and sign in. If you haven't yet signed up, you can follow these instructions to sign up.
Make sure that you have admin access to an environment that contains a Common Data Service database. Go to the PowerApps portal, click the gear icon in the upper right of the page, and then click Admin center. If you don't have admin access to any environments that contain a database, follow these instructions to create a database.
And below is helpful document to help get started:
Get started with the Common Data Service SDK
I taken the sample code from the GIT for multi-tenant.
https://github.com/OfficeDev/O365-WebApp-MultiTenant
In https://manage.windowsazure.com/ i enabled MULTI-TENANT to YES. But when ever i tried to login with different organization i am getting error as follows.
User account 'vtest#someconsuting.onmicrosoft.com' from identity provider 'https://sts.windows.net/xxxxxxxxxxxxxxxxxxxxxxxxxxx/' does not exist in tenant 'My Test App ' and cannot access the application 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
How can i resolve this??
Finally i found the solution to my problem. From this URL https://github.com/dream-365/OfficeDev-Samples/blob/master/samples/Office365DevQuickStart/AspNetMvc-MultiTenant/
I copied the following files to my project
TokenCacheDBContext.cs
SqlDBTokenCache.cs
ServiceConstants.cs
App_Start/Startup.auth.cs
I ran the project and got one error for Office365AssertedFailedException. For that i created one more class file like
Office365AssertedFailedException.cs
I rebuild the code again and got success. Now i am able to login with multi-tenants.
Please ensure your authority url is "https://login.windows.net/common".
If your authority url is "https://login.windows.net/{tenant_id}", you will get the error as following:
To fix this issue, in the Startup.Auth.cs, config the authority url as "https://login.windows.net/common".
var authority = string.Format("{0}/{1}", ServiceConstants.AzureADEndPoint, "common");
var options = new OpenIdConnectAuthenticationOptions {
ClientId = OAuthSettings.ClientId,
Authority = authority,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters {
ValidateIssuer = false
}
};
sample Startup.Auth.cs
I had the same issue. Just replaced
string authorityUri = "https://login.microsoftonline.net/common/";
with
string authorityUri = "https://login.windows.net/common";