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
Related
I want to modify a legacy ASP.NET WebForms application to use Azure SAML authentication. I found SAML authentication sample for ASP.NET Core on Microsoft site and want to modify this code to fit in my Web Forms application Startup class.
The below code I want to change:
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = "Saml2";
})
.AddSaml2(options =>
{
options.SPOptions.EntityId = new EntityId("https://localhost:44342/Saml2");
options.IdentityProviders.Add(
new IdentityProvider(
new EntityId("https://sts.windows.net/63eb1bcb-f74f-4703-8243-6f73d78ebf52/"), options.SPOptions)
{
MetadataLocation = "https://login.microsoftonline.com/63eb1bcb-f74f-4703-8243-6f73d78ebf52/federationmetadata/2007-06/federationmetadata.xml?appid=9fd05134-d507-479b-a432-580541125356"
});
})
.AddCookie();
This code uses 'services' which is not available in my startup class. My existing code looks like this:
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
//interactive logon process
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
//name of the authentication type
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
//Login path should be below
// LoginPath = new PathString("login"),
//TODO: Enable this to always send and receive cookies in SSL when in production
CookieSecure = CookieSecureOption.Always,
//enable sliding expiration
SlidingExpiration = true,
//Cookie expires in 4 hours
ExpireTimeSpan = TimeSpan.FromTicks(DateTime.Now.AddHours(4).Ticks)
});
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
{
MetadataAddress = adfsMetadata,
Wtrealm = realm
});
//This will set ADFS as the default authentication provider
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseStageMarker(PipelineStage.Authenticate);
}
Update
Below article should be easy than previous. You can refer it.
Code Your C#/ASP.NET App to Provide SSO via OneLogin
sample code : https://github.com/onelogin/dotnet-saml
Previous
You can refer this doc learn how to fit your Web Forms application in Startup.Auth.cs class.
Official doc :
Sustainsys.Saml2 --ASP.NET Web Forms
You also can refer this code.
SampleOwinApplication
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
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.
I am devoloping Asp.net mvc application with Asp.net Identity framework with a requirement of user should be autologout after 10 mins only when the user is inactive(With out mouse movement/Click).I have tried with code which works as user logsout even when the user is active in the application,Can any one help me out in accomplishing these ASAP.Response would be appreciated
Please find my Starup.cs file code here:
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using ADFV2External.Models;
using ADFV2External;
namespace ADFV2ExternalLogin
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
CookieSecure = CookieSecureOption.Always,
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
},
ExpireTimeSpan = TimeSpan.FromMinutes(10)
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
// 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(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
app.UseMicrosoftAccountAuthentication
(
clientId: "f10e6987-f527-4eb2-a7d4-61a9d5175117",
clientSecret: "qedLHH977-:ivxfAZNQ90:_"
);
}
}
}
ExpireTimeSpan based on request/response mechanism. That means, that user will log out if there wouldn't be any HTTP request from user in 10 minutes from last response.
So I see 2 ways to solve your task:
You can initiate HTTP requests from page by mouse/keyboard events;
You can run timer (setTimeout function) on client side with its reset on mouse/keyboard events & send log out request when it stops. ExpireTimeSpan must be disabled.
But there may be trouble when user opens some pages.
I'm using
New browser only clients on the same domain
Identity 2.0
WebAPI 2.1
Owin 2.1
AngularJS front-end for registration, login and data display
In a WebAPI application with an AngularJS front-end.
I'm reading about token authentication but I am very confused now and I cannot find any good examples out there that use my combination. What I would like to know is should I be using cookies or tokens for the authentication. Should I be using a Userfactory or the CreatePerOwinContext?
Here's what I have in my Startup.Auth.cs
public partial class Startup {
public void ConfigureAuth(IAppBuilder app) {
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/"),
Provider = new CookieAuthenticationProvider {
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
}
Here's my WebAPI config:
public static class WebApiConfig
{
public static void CustomizeConfig(HttpConfiguration config)
{
config.Formatters.Remove(config.Formatters.XmlFormatter);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
json.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-ddTHH:mmZ" });
}
I saw some examples using this code but I am not sure how I can call this:
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
Could I just replace the cookie authentication with this?
Not an expert, but in my dabbling I've found that tokens work great for api and from javascript to api, and traditional cookies lean mostly for a ui. Either or both will work depending on what your trying to do.
You can follow something like this link that does cookie for the ui and token for the api http://blog.iteedee.com/2014/03/asp-net-identity-2-0-cookie-token-authentication/
app.CreatePerOwinContext(ApplicationSession.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Token Authentication
app.UseOAuthBearerAuthentication(new OAuthBearerOptions());
I think you can set the cookie authentication options authentication type to bearer if you want bearer for both, but you would have to play with it. The token would be in the owincontext under ".AspNet.ExternalBearer".
I also think if you register the Identity 2.0 middleware i think it also registers the oauth middleware stuff so you don't need to register the oauthserver middleware yourself. Thats the OAuthAuthorizationServerOptions code you posted. You dont need it.
if the ui and api are in separate then its a bit harder if you want to do some sort of single sign on from the ui pass to the api. I would recommend looking at opensource identity server or authorization server from thinktecture.
If your set on owin middleware and Identity 2.0 you would need to make sure the token can be read by both application and api and you probably would need to implement ISecureDataFormat. But remember, decryption doesn't mean you can 100% trust a token, it should be signed and verified. Depends on your needs.
Sorry, I guess thats a long ramble... Good luck.