I am trying to get Azure AD connected service working for my dotnet framework applications. I went through the wizard and it added the necessary dependencies and files I need for it to work. The issue I am having is it does not reliably work. So I've rolled back and I am just working locally. If I type in localhost/Athena it does not work, however, it leaves /signin-oidc at the end of the URL. When I manually delete that last part the page works fine. The error I am getting is
IDX21323: RequireNonce is 'System.Boolean'.
OpenIdConnectProtocolValidationContext.Nonce was null.
If I type in https://localhost/Athena it works every time. Below is the code from my Startup.Auth.cs file.
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = "8675309",
Authority = authority,
CallbackPath = new PathString("/signin-oidc"),
//Tried with the below redirecturi and I still have the same issues.
//RedirectUri = "https://localhost/Athena/signin-oidc"
});
}
This exception is occured when an OpenIdConnect middleware encounters an invalid nonce or a missing nonce cookie.
Try making following configurations.
Configure startup.cs as below
AuthenticationType = “ApplicationCookie”,
CookieSameSite = SameSiteMode.None,
CookieSecure = CookieSecureOption.Always
Check/configure web.config:
<system.web>
<sessionState cookieSameSite=”None”/>
<httpCookies requireSSL=”true” />
</system.web>
note:Make sure all your website traffic is over https.
The initialization code is different depending on the platform. For ASP.NET Core and ASP.NET, signing in users is delegated to the OpenID Connect middleware. Some configuration is required to adapt them to the Microsoft identity platform.
The code related to authentication in an ASP.NET web app and web APIs is located in the App_Start/Startup.Auth.cs file.
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// Authority` represents the identity platform endpoint - https://login.microsoftonline.com/common/v2.0.
// `Scope` describes the initial permissions that your app will need.
// See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/.
ClientId = clientId,
Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"),
RedirectUri = redirectUri,
Scope = "openid profile",
PostLogoutRedirectUri = redirectUri,
});
}
You can refer the following document to know detailed information
/configuration in web.config file related to above Startup.auth.cs configuration
https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-web-app-sign-user-app-configuration?tabs=aspnet
The Microsoft identity platform implementation of OpenID Connect has
a few well-defined scopes .You can refer this
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent
to know scopes and permissions in microsoft identity platform
Related
I have implemented Azure Active Directory authentication in my asp.net web app.
startup.auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = redirectUri,
RedirectUri = redirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
//
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
//
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
AuthenticationFailed = OnAuthenticationFailed
}
});
}
when i hit application url , its going to AD authentication, when i enter my credentials after completing two factor authentication it keeps trying to connect and finally says "we couldnt signin you, please try again later". please help
Authentication issue
its single page application created in asp.net mvc with type script.
please help me to resolve this issue. thanks!!!
(Moving from Comments to answer)
The above issue is resolved by following in the Document and GitHub Sample.
My objective is to have an Asp.Net Mvc action secured with OpenId authentication, and support 2 types of clients: browser and a native WPF application. The STS I will use is ADFS 2016.
Currently clients browsers works well. For this, I have UseOpenIdConnectAuthentication configured in my startup class.
I'm able to call my Mvc action (secured with Authorize attribute), user is redirected to STS, and once authentication is done, I come back to my Mvc action with a ClaimsIdentity properly filled.
Now I'm trying to have a native WPF app able to authenticate to the same Mvc action in the same Web app, and things are getting tricky.
On the client side (my WPF application), I'm using ADAL and the following code:
var authContext = new AuthenticationContext("<MySTSUri>");
var authResult = await authContext.AcquireTokenAsync(
"http://localhost:1276/openid/login",
"MyNativeAppId",
new Uri("myapp://openid"),
new PlatformParameters(PromptBehavior.Auto),
UserIdentifier.AnyUser,
"");
if (!string.IsNullOrEmpty(authResult.AccessToken))
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(authResult.AccessTokenType, authResult.AccessToken);
HttpResponseMessage response = await httpClient.GetAsync("http://localhost:1276/openid/login");
if (response.IsSuccessStatusCode)
{
var text = await response.Content.ReadAsStringAsync();
}
}
}
The problem is basically that I can't tell the Web app to be able to validate this type of ADAL request.
I've tried various things in the Web application Owin startup file configuration:
leaves UseOpenIdConnectAuthentication: it doesn't seem sufficient, I'm redirected to STS with the ClientId of the Web application
UseActiveDirectoryFederationServicesBearerAuthentication api since I know my STS will always be an ADFS
UseOAuthBearerAuthentication
None of them are working.
Please can someone help how to achieve this?
Am I going in the right direction?
Any ideas/pointers would be greatly appreciated.
Thanks,
Alex
I've managed to get it working. I post the answer for the record.
What helped me a lot is to enable Owin logs in the web.config:
<system.diagnostics>
<switches>
<add name="Microsoft.Owin" value="Verbose" />
</switches>
</system.diagnostics>
Then with Owin, you can simply chain multiple authentication methods. So in my case, I've just used:
app.UseActiveDirectoryFederationServicesBearerAuthentication(
new ActiveDirectoryFederationServicesBearerAuthenticationOptions
{
MetadataEndpoint = adfsMetadataEndpoint,
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudiences = new[] { validAudience }
}
});
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
AuthenticationType = "OpenId",
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
ResponseType = OpenIdConnectResponseTypes.CodeIdToken,
Scope = "openid",
SignInAsAuthenticationType = "Cookies"
});
Cheers,
Alex
I am trying to implement authentication using Azure AD. In the application setting I am setting the Reply URLs as https://example.com/myapp/login.aspx.
When I login it redirects me to https://example.com and not specified URL https://example.com/myapp/login.aspx
How can I make sure that it redirects at proper URL? Following is the code for Startup.
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = ConfigurationManager.AppSettings["owin:ClientId"].ToString(),
Authority = "https://login.microsoftonline.com/yz5036e3-2951-4c11-af4d-da019fa6a57d",
RedirectUri = ConfigurationManager.AppSettings["RedirectUri"].ToString()
});
}
How do you trigger the sign in flow? If you are following the samples and initiating the sign in by invoking Challenge as shown in https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect/blob/master/WebApp-OpenIDConnect-DotNet/Controllers/AccountController.cs, you might want to make sure that the RedirectUri in the AuthenticationProperties points to the URL you ultimately (as in, AFTER auth) want to land on.
I know, it's incredibly confusing - the RedirectUri property in the OIDC options point to the redirect you want to use in the auth protocol, the one on which you want to receive the auth token- and the one in the AuthenticationProperties is local URL you want to be redirected to after your exchange with the identity provider successfully concluded. The proerties have the same name for historical reasons.
In my case website was under virtual directory (converted in application). For login URL e.g. http://example.com/myapp/login.aspx, it was redirecting user to http://example.com. If I set RedirectUri as myapp/AfterLogin.aspx, it worked.
HttpContext.Current.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "myapp/AfterLogin.aspx", },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
I have a bunch of web apps that I've created. Some of them use old-style webforms authentication, and some other sites at our company use different authentication patterns.
I'm trying to consolidate this, under one SSO pattern using Azure Active Directory. I've been trying to following guides/tutorials but it's not clicking for me.
My tech is currently ASP 4/MVC 5, although if ASP 5/MVC 6 is easier then I have the freedom to go that route as well. All web apps are hosted in Azure currently.
The confusion for me comes in that while looking through documentation, there seem to be so many ways to authentication and authorize users (also, authenticate vs authorize isn't absolutely clear to me).
I went to the Active Directory area of Azure Management portal (the old one). I added a new application called TestApp. I set the app URL to https://localhost:44320/, then sign-on URL to https://localhost:44320/, the tenant name to testapp. And my reply URL is https://localhost:44320/
This makes my app id uri https://localhost:44320/testapp I think? I also have my client ID guid.
The tutorial has an AccountController with a SignIn method like this:
public void SignIn()
{
// Send an OpenID Connect sign-in request.
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
When navigating to this, I receive the following in the browser:
[InvalidOperationException: IDX10803: Unable to create to obtain configuration from: 'https://localhost:44320/testapp/.well-known/openid-configuration'.]
I have a feeling it's because Azure is unable to redirect this all to back to my localhost? How can I set this up so I can test it out on Azure itself? And even further than that, will this solution be usable from multiple webapps? I'd assume they'd each be different applications in my Active Directory, but they'd all need to use a SSO procedure, where users can sign into multiple apps with one identity.
Sorry for any confusion, this is all very convoluted to me but I am trying to learn it as best I can.
Edit:
In the Startup of the webapp, I am calling this:
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,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
Which utilizes these app.config settings:
<add key="ida:ClientId" value="[my client id here]" />
<add key="ida:Tenant" value="testapp" />
<add key="ida:AADInstance" value="https://localhost:44320/{0}" />
<add key="ida:PostLogoutRedirectUri" value="https://localhost:44320/" />
Azure is able to redirect to localhost, it will just pop up a security confirmation asking if its ok to navigate to localhost.
Your tenant in app.config doesn't look right, change these app settings:
<add key="ida:Tenant" value="[YOUR TENANT].onmicrosoft.com" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />
To find out more about your tenant see this article: How to get an Azure Active Directory tenant
You can also try adding this code to your Notifications in Startup (just under AuthenticationFailed), try putting breakpoints on the handlers to see what happens:
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
},
SecurityTokenValidated = (context) =>
{
return Task.FromResult(0);
}
Put an [Authorize] attribute on one of your controllers and it should redirect to the AAD authentication when you browse to it.
AFAIK each app would need a separate application in Azure AD and you would need to implement this Authentication in each separate app. I have managed to have a seamless sign in experience when I link via url from one app to another.
This answer sums up authentication vs authorization nicely: Authentication versus Authorization
If I have an existing project in Visual Studio 2013, how do I change the authentication? During a new project setup, there is a "Change Authentication" button, but I cannot find the equivalent for an existing project.
This can be done from project properties. I'm posting a link to the article which explains how to do this.
Until someone comes up with a better answer:
Edit your web.config and FederationMetadata.xml manually.
If your project is ASP.NET MVC and is using the new template in 2013 it should be running on OWIN so there is a partial class Startup look inside and in case you have it there is a file
Startup.Auth.cs that is partial of Startup there I have this
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Authentication/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication();
}
}
There, is your authentication configuration