public static void EnsureRealmAudienceUri(WSFederationAuthenticationModule fam, string realm) { Uri realmUri = new Uri(realm); if (!fam.FederationConfiguration.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Contains(realmUri)) { fam.FederationConfiguration.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(realmUri); } }
/// <summary> /// Initializes a new instance of the <see cref="PermissionClaimsManager"/> class. /// </summary> /// <param name="federatedAuthenticationProvider">The federated authentication provider.</param> /// <param name="systemRoleRepository">The system role repository.</param> /// <param name="systemPermissionService">The system permission service.</param> public PermissionClaimsManager( IFederatedAuthenticationProvider federatedAuthenticationProvider, ISystemRoleRepository systemRoleRepository, ISystemPermissionService systemPermissionService ) { _systemRoleRepository = systemRoleRepository; _systemPermissionService = systemPermissionService; _federationAuthenticationModule = federatedAuthenticationProvider.GetFederationAuthenticationModule (); }
public ActionResult IssueResponse() { var fam = new WSFederationAuthenticationModule(); fam.FederationConfiguration = new FederationConfiguration(); if (fam.CanReadSignInResponse(Request)) { var responseMessage = fam.GetSignInResponseMessage(Request); return ProcessSignInResponse(responseMessage, fam.GetSecurityToken(Request)); } return View("Error"); }
public ActionResult SignOut() { AuthDataManager.CleanupCookies(Response); if (User == null || !User.Identity.IsAuthenticated) { return(View()); } else { var stsUri = FederatedAuthentication.WSFederationAuthenticationModule.Issuer; var backUrl = FederatedAuthentication.WSFederationAuthenticationModule.Realm; WSFederationAuthenticationModule.FederatedSignOut(new Uri(stsUri, UriKind.RelativeOrAbsolute), new Uri(backUrl, UriKind.RelativeOrAbsolute)); return(new EmptyResult()); } }
protected void Page_Load(object sender, EventArgs e) { if (User.Identity.IsAuthenticated) { // Remove the application cookies, etc. WSFederationAuthenticationModule WsFam = FederatedAuthentication.WSFederationAuthenticationModule; WsFam.SignOut(false); // Issue a sign out request to remove the STS session, etc. This will trigger an SSOut. SignOutRequestMessage signOutRequestMessage = new SignOutRequestMessage(new Uri(WsFam.Issuer), WsFam.Reply); String signOutRequest = signOutRequestMessage.WriteQueryString() + "&wtrealm=" + WsFam.Realm; Response.Redirect(signOutRequest); return; } Response.Redirect("/"); }
//will delete session and call the identity provider public ActionResult Logout() { //delete authentication session Session[Const.CLAIM.USER_ACCESS_LEVEL] = null; Session[Const.CLAIM.USER_ACCOUNT] = null; Session[Const.CLAIM.USER_ID] = null; Session[Const.CLAIM.USER_FIRST_NAME] = null; Session[Const.CLAIM.USER_LAST_NAME] = null; // Load Identity Configuration FederationConfiguration config = FederatedAuthentication.FederationConfiguration; // Sign out of WIF. WSFederationAuthenticationModule.FederatedSignOut(new Uri(ConfigurationManager.AppSettings["ida:Issuer"]), new Uri(config.WsFederationConfiguration.Realm)); return(View()); }
public virtual ActionResult ChangeUser() { var federationModule = FederatedAuthentication.WSFederationAuthenticationModule; if (federationModule != null) { if (!string.IsNullOrEmpty(federationModule.Reply) && !string.IsNullOrEmpty(federationModule.Issuer)) { var replyUrl = new Uri(FederatedAuthentication.WSFederationAuthenticationModule.Reply); var issuer = new Uri(FederatedAuthentication.WSFederationAuthenticationModule.Issuer); WSFederationAuthenticationModule.FederatedSignOut(issuer, replyUrl); } } return(View()); }
public static bool TryHandleSignInResponse( this WSFederationAuthenticationModule fam, HttpContext context, string returnUrl, string invitationCode, string challengeAnswer, IUserRegistrationSettings registrationSettings) { var signInContext = new Dictionary <string, string> { { registrationSettings.ReturnUrlKey ?? DefaultReturnUrlKey, returnUrl }, { registrationSettings.InvitationCodeKey ?? DefaultInvitationCodeKey, invitationCode }, { registrationSettings.ChallengeAnswerKey ?? DefaultChallengeAnswerKey, challengeAnswer }, }; return(TryHandleSignInResponse(fam, context, signInContext, registrationSettings)); }
public void GivenNoClaimsIdentityExists_WhenIAuthenticate_ThenCorrectRedirectResponseIssued() { AuthorizationContext authorizationContext = CreateAuthorizationContext(true, "whatever"); authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf"); WSFederationAuthenticationModule module = new WSFederationAuthenticationModule { Issuer = "http://blah.com", HomeRealm = "http://blah.com", Realm = "http://site.com" }; IAuthenticationModuleProvider provider = MockRepository.GenerateMock <IAuthenticationModuleProvider>(); provider.Expect(m => m.GetModule()).Return(module); AuthenticationUtility.SetModuleProvider(provider); Target.OnAuthorization(authorizationContext); Assert.IsInstanceOfType(authorizationContext.Result, typeof(RedirectToRouteResult)); ((RedirectToRouteResult)authorizationContext.Result).AssertActionRedirection("Login", "Account"); }
public static void RedirectToSignIn( this WSFederationAuthenticationModule fam, HttpContext context, string returnUrl, string invitationCodeValue, string challengeAnswerValue, IUserRegistrationSettings registrationSettings) { RedirectToSignIn( fam, context, returnUrl, invitationCodeValue, challengeAnswerValue, registrationSettings.ReturnUrlKey, registrationSettings.InvitationCodeKey, registrationSettings.ChallengeAnswerKey); }
public static void RedirectToSignIn( this WSFederationAuthenticationModule fam, HttpContext context, IDictionary <string, string> signInContext = null) { var ctx = signInContext != null?ToConnectionString(signInContext) : null; var baseUrl = new Uri(fam.Issuer); var signIn = new SignInRequestMessage(baseUrl, fam.Realm) { Context = ctx }; var url = signIn.RequestUrl; TraceInformation("RedirectToSignIn", "url={0}", url); context.RedirectAndEndResponse(url); }
/// <summary> /// Gets the logout page URL. /// </summary> /// <returns>The logout page's URL.</returns> public string GetLogoutPageUrl() { WSFederationAuthenticationModule federationAuthenticationModule; if (FederatedAuthentication.WSFederationAuthenticationModule != null) { _logger.Debug("Returning current {0}.", typeof(WSFederationAuthenticationModule).Name); federationAuthenticationModule = FederatedAuthentication.WSFederationAuthenticationModule; } else { _logger.Debug("Returning a new {0}.", typeof(WSFederationAuthenticationModule).Name); federationAuthenticationModule = new WSFederationAuthenticationModule(); } return(new SignOutRequestMessage(new Uri(federationAuthenticationModule.Issuer), federationAuthenticationModule.Realm).WriteQueryString()); }
public void GivenNoClaimsIdentityExists_WhenIAuthenticate_ThenNoUserEntityIsSet() { AuthorizationContext authorizationContext = CreateAuthorizationContext(true, "whatever"); authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf"); WSFederationAuthenticationModule module = new WSFederationAuthenticationModule { Issuer = "http://blah.com", HomeRealm = "http://blah.com", Realm = "http://site.com" }; IAuthenticationModuleProvider provider = MockRepository.GenerateMock <IAuthenticationModuleProvider>(); provider.Expect(m => m.GetModule()).Return(module); AuthenticationUtility.SetModuleProvider(provider); Target.OnAuthorization(authorizationContext); Assert.IsNull(Target.UserEntity); }
public ActionResult SignOut() { WSFederationAuthenticationModule fam = FederatedAuthentication.WSFederationAuthenticationModule; try { FormsAuthentication.SignOut(); } finally { FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie(); fam.SignOut(true); } // Return to home after LogOff //SignOutRequestMessage signOutRequest = new SignOutRequestMessage(new Uri(fam.Issuer), fam.Realm); //return Redirect(signOutRequest.WriteQueryString()); return(RedirectToAction("Index", "Home")); }
public static void RedirectToSignIn( this WSFederationAuthenticationModule fam, HttpContext context, string returnUrl, string invitationCodeValue, string challengeAnswerValue, string returnUrlKey = DefaultReturnUrlKey, string invitationCodeKey = DefaultInvitationCodeKey, string challengeAnswerKey = DefaultChallengeAnswerKey) { var ctx = new Dictionary <string, string> { { returnUrlKey ?? DefaultReturnUrlKey, returnUrl }, { invitationCodeKey ?? DefaultInvitationCodeKey, invitationCodeValue }, { challengeAnswerKey ?? DefaultChallengeAnswerKey, challengeAnswerValue }, }; RedirectToSignIn(fam, context, ctx); }
public override ActionResult Login(ControllerContext controllerContext, Uri returnUrl) { Uri landingUrl = GenerateLandingUrl(controllerContext, new { returnUrl }); WSFederationAuthenticationModule module = new WSFederationAuthenticationModule { Realm = landingUrl.ToString(), Issuer = IssuerUrl }; SignInRequestMessage signInMessage = module.CreateSignInRequest(Guid.NewGuid().ToString(), landingUrl.ToString(), false); if (!String.IsNullOrEmpty(HomeRealm)) { signInMessage.Parameters.Add(HomeRealmParameter, HomeRealm); } AddParametersToSignInMessage(signInMessage); return new RedirectResult(signInMessage.RequestUrl); }
protected void Page_Load(object sender, EventArgs e) { if (Thread.CurrentPrincipal.Identity.IsAuthenticated) { IClaimsIdentity identity = (IClaimsIdentity)Thread.CurrentPrincipal.Identity; /* For illustrative purposes this sample application simply shows all the parameters of * claims (i.e. claim types and claim values), which are issued by a security token * service (STS), to its clients. In production code, security implications of echoing * the properties of claims to the clients should be carefully considered. For example, * some of the security considerations are: (i) accepting the only claim types that are * expected by relying party applications; (ii) sanitizing the claim parameters before * using them; and (iii) filtering out claims that contain sensitive personal information). * DO NOT use this sample code ‘as is’ in production code. */ ShowName(identity); ShowClaimsIdentityAsIIdentity(identity); ShowClaimsFromClaimsIdentity(identity); } else { // use WS-Federation WSFederationAuthenticationModule authModule = new WSFederationAuthenticationModule(); authModule.Realm = "https://localhost/PassiveRP/Default.aspx"; authModule.Issuer = "https://localhost/PassiveFPSTS/Default.aspx"; string uniqueId = Guid.NewGuid().ToString(); // create a request message SignInRequestMessage signInMsg = authModule.CreateSignInRequest(uniqueId, authModule.Realm, false); string homeRealmSts = Page.Request.QueryString["whr"]; if (!String.IsNullOrEmpty(homeRealmSts)) { signInMsg.Parameters.Add("whr", homeRealmSts); } // Redirect to the FP STS for token issuance Page.Response.Redirect(signInMsg.RequestUrl); } }
public static string GetSignInResponseMessageAsFormPost( this WSFederationAuthenticationModule fam, HttpContext context, Uri uri) { var message = fam.GetSignInResponseMessage(context.Request); message.BaseUri = uri; // clean out the non-WIF parameters var parametersToRemove = GetUnknownParameters(message).Select(parameter => parameter.Key).ToList(); foreach (var parameter in parametersToRemove) { message.RemoveParameter(parameter); } var post = message.WriteFormPost(); return(post); }
public ActionResult ProcessWSFedResponse() { var fam = new WSFederationAuthenticationModule(); fam.FederationConfiguration = new FederationConfiguration(); if (ConfigurationRepository.Keys.DecryptionCertificate != null) { var idConfig = new IdentityConfiguration(); idConfig.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection <SecurityToken>(new SecurityToken[] { new X509SecurityToken(ConfigurationRepository.Keys.DecryptionCertificate) }), false); fam.FederationConfiguration.IdentityConfiguration = idConfig; } if (fam.CanReadSignInResponse(Request)) { var token = fam.GetSecurityToken(Request); return(ProcessWSFedSignInResponse(fam.GetSignInResponseMessage(Request), token)); } return(View("Error")); }
protected void Page_Load(object sender, EventArgs e) { if (User != null && User.Identity != null && User.Identity.IsAuthenticated) { var ub = new UriBuilder(this.Request.Url); ub.Path = "/"; ub.Query = ""; ub.Fragment = ""; var issuerSignoutUrl = new UriBuilder(new Uri(FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Issuer, UriKind.Absolute)); if (Request.Url.Host == "www.grean.id") { issuerSignoutUrl.Host = "easyid.www.grean.id"; } WSFederationAuthenticationModule.FederatedSignOut( issuerSignoutUrl.Uri, ub.Uri); } else { Response.Redirect("/"); } }
public void GivenAnAuthenticatedUserWasAlreadyAuthorized_AndNoClaimsIdentityExists_WhenIAuthenticate_ThenNoUserEntityIsSet() { string userKey = "whatever"; AuthorizationContext authorizationContext = CreateAuthorizationContext(false, userKey); authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf"); MockAccountManager.Expect(m => m.EnsureUserEntity(authorizationContext.HttpContext.User.Identity as System.Security.Claims.ClaimsIdentity)).Return(new User()); Target.OnAuthorization(authorizationContext); authorizationContext = CreateAuthorizationContext(true, userKey); authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf"); WSFederationAuthenticationModule module = new WSFederationAuthenticationModule { Issuer = "http://blah.com", HomeRealm = "http://blah.com", Realm = "http://site.com" }; IAuthenticationModuleProvider provider = MockRepository.GenerateMock <IAuthenticationModuleProvider>(); provider.Expect(m => m.GetModule()).Return(module); AuthenticationUtility.SetModuleProvider(provider); Target.OnAuthorization(authorizationContext); Assert.IsNull(Target.UserEntity); }
public static bool TryHandleSignInResponse( this WSFederationAuthenticationModule fam, HttpContext context, IDictionary <string, string> signInContext, IUserRegistrationSettings registrationSettings = null) { var handler = registrationSettings != null ? new FederationAuthenticationHandler(registrationSettings) : new FederationAuthenticationHandler(); try { return(handler.TryHandleSignInResponse(context, fam, signInContext)); } catch (Exception exception) { if (!handler.TryHandleException(context, fam, exception)) { throw new FederationAuthenticationException("Federated sign-in error.", exception); } } return(false); }
public List <HrdIdentityProvider> GetProviders(string contextUri) { WSFederationAuthenticationModule fam = FederatedAuthentication.WSFederationAuthenticationModule; HrdRequest request = new HrdRequest(fam.Issuer, fam.Realm, context: contextUri); WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.UTF8; string response = client.DownloadString(request.GetUrlWithQueryString()); JavaScriptSerializer serializer = new JavaScriptSerializer(); var providers = serializer.Deserialize <List <HrdIdentityProvider> >(response); foreach (var item in providers) { if (item.Name.StartsWith("Windows Live")) { item.Name = "Windows Live"; } } return(providers); }
private void DoFederatedSignOut() { string providerName = GetProviderNameFromCookie(); SPTrustedLoginProvider loginProvider = null; SPSecurity.RunWithElevatedPrivileges(delegate() { loginProvider = GetLoginProvider(providerName); }); if (loginProvider != null) { string returnUrl = string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}://{1}/_layouts/SignOut.aspx", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host); HttpCookie signOutExpiredCookie = new HttpCookie(SignOutCookieName, string.Empty); signOutExpiredCookie.Expires = new DateTime(1970, 1, 1); HttpContext.Current.Response.Cookies.Remove(SignOutCookieName); HttpContext.Current.Response.Cookies.Add(signOutExpiredCookie); WSFederationAuthenticationModule.FederatedSignOut(loginProvider.ProviderUri, new Uri(returnUrl)); } }
public static string GetHomeRealmDiscoveryMetadataFeedUrl( this WSFederationAuthenticationModule fam, string path = "/v2/metadata/IdentityProviders.js", string protocol = "wsfederation", string version = "1.0", string replyTo = null, string callback = null, IDictionary <string, string> context = null) { var ctx = context != null?ToConnectionString(context) : null; var query = "?protocol={0}&realm={1}&reply_to={2}&context={3}&version={4}&callback={5}".FormatWith( HttpUtility.UrlEncode(protocol), HttpUtility.UrlEncode(fam.Realm), HttpUtility.UrlEncode(replyTo), HttpUtility.UrlEncode(ctx), HttpUtility.UrlEncode(version), HttpUtility.UrlEncode(callback)); var baseUri = new Uri(fam.Issuer); var url = baseUri.GetLeftPart(UriPartial.Authority) + path + query; return(url); }
public SignOutRequestMessage Logout() { WSFederationAuthenticationModule federationAuthenticationModule; if (FederatedAuthentication.WSFederationAuthenticationModule != null) { Logger.Debug("Returning current {0}.", typeof(WSFederationAuthenticationModule).Name); federationAuthenticationModule = FederatedAuthentication.WSFederationAuthenticationModule; } else { Logger.Debug("Returning a new {0}.", typeof(WSFederationAuthenticationModule).Name); federationAuthenticationModule = new WSFederationAuthenticationModule(); } Logger.Debug( "Initiating: SignOff. Calling the SignOff method of the WSFederationAuthenticationModule. DateTime Utc: " + DateTime.UtcNow); federationAuthenticationModule.SignOut(false); return(new SignOutRequestMessage(new Uri(federationAuthenticationModule.Issuer), federationAuthenticationModule.Realm)); }
public ActionResult ProcessWSFedResponse() { var fam = new WSFederationAuthenticationModule(); fam.FederationConfiguration = new FederationConfiguration(); if (ConfigurationRepository.Keys.DecryptionCertificate != null) { var idConfig = new IdentityConfiguration(); idConfig.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(new SecurityToken[] { new X509SecurityToken(ConfigurationRepository.Keys.DecryptionCertificate) }), false); fam.FederationConfiguration.IdentityConfiguration = idConfig; } if (fam.CanReadSignInResponse(Request)) { var token = fam.GetSecurityToken(Request); return ProcessWSFedSignInResponse(fam.GetSignInResponseMessage(Request), token); } return View("Error"); }
/// <summary> /// Initializes a new instance of the <see cref="SignOffService"/> class. /// </summary> /// <param name="federatedAuthenticationProvider"> /// The federated authentication provider. /// </param> public SignOffService(IFederatedAuthenticationProvider federatedAuthenticationProvider) { _federationAuthenticationModule = federatedAuthenticationProvider.GetFederationAuthenticationModule(); }
/// <summary> /// Executed when the authentication should be done. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private void context_AuthenticateRequest(object sender, EventArgs e) { // Get the request. var request = ((HttpApplication)sender).Request; // The redirect back from the security token service is done using a POST method. Hence // abort processing of the current request, if it was not sent using POST. if (request.HttpMethod != "POST") { return; } // Check whether the request contains sign in data. if (request.Form["wa"] != WSFederationConstants.Actions.SignIn || request.Form["wresult"].IsNullOrEmpty()) { return; } // Otherwise, get the security token which is attached to the request, process it and // convert it to a principal. First, set up the federatec authentication module. var fam = new WSFederationAuthenticationModule { ServiceConfiguration = new ServiceConfiguration { AudienceRestriction = { AudienceMode = AudienceUriMode.Never }, CertificateValidationMode = X509CertificateValidationMode.Custom, CertificateValidator = new CertificateValidator(c => true), IssuerNameRegistry = new X509CertificateIssuerNameRegistry() } }; // Prepare the decryption by injecting the certificate to the service token resolver. var certificates = new List<SecurityToken> { new X509SecurityToken( this.Container.Resolve<ICertificateManager>().GetEncryptingCertificate()) }; var encryptedSecurityTokenHandler = (from handler in fam.ServiceConfiguration.SecurityTokenHandlers where handler is EncryptedSecurityTokenHandler select handler).First() as EncryptedSecurityTokenHandler; encryptedSecurityTokenHandler.Configuration.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(certificates.AsReadOnly(), false); // Get the security token from the request. var securityToken = fam.GetSecurityToken(request); // Validate the token and convert it to a collection of claims. var claims = fam.ServiceConfiguration.SecurityTokenHandlers.ValidateToken(securityToken); // Create a principal from the claims. IClaimsPrincipal principal = new ClaimsPrincipal(claims); // Set the current principal. HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; }
public void GivenNoClaimsIdentityExists_WhenIAuthenticate_ThenNoUserEntityIsSet() { AuthorizationContext authorizationContext = CreateAuthorizationContext(true, "whatever"); authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf"); WSFederationAuthenticationModule module = new WSFederationAuthenticationModule { Issuer = "http://blah.com", HomeRealm = "http://blah.com", Realm = "http://site.com" }; IAuthenticationModuleProvider provider = MockRepository.GenerateMock<IAuthenticationModuleProvider>(); provider.Expect(m => m.GetModule()).Return(module); AuthenticationUtility.SetModuleProvider(provider); Target.OnAuthorization(authorizationContext); Assert.IsNull(Target.UserEntity); }
/// <summary> /// Initializes a new instance of the <see cref="SignOffService"/> class. /// </summary> /// <param name="federatedAuthenticationProvider"> /// The federated authentication provider. /// </param> public SignOffService( IFederatedAuthenticationProvider federatedAuthenticationProvider ) { _federationAuthenticationModule = federatedAuthenticationProvider.GetFederationAuthenticationModule (); }
public void GivenAnAuthenticatedUserWasAlreadyAuthorized_AndNoClaimsIdentityExists_WhenIAuthenticate_ThenNoUserEntityIsSet() { string userKey = "whatever"; AuthorizationContext authorizationContext = CreateAuthorizationContext(false, userKey); authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf"); MockAccountManager.Expect(m => m.EnsureUserEntity(authorizationContext.HttpContext.User.Identity as System.Security.Claims.ClaimsIdentity)).Return(new User()); Target.OnAuthorization(authorizationContext); authorizationContext = CreateAuthorizationContext(true, userKey); authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf"); WSFederationAuthenticationModule module = new WSFederationAuthenticationModule { Issuer = "http://blah.com", HomeRealm = "http://blah.com", Realm = "http://site.com" }; IAuthenticationModuleProvider provider = MockRepository.GenerateMock<IAuthenticationModuleProvider>(); provider.Expect(m => m.GetModule()).Return(module); AuthenticationUtility.SetModuleProvider(provider); Target.OnAuthorization(authorizationContext); Assert.IsNull(Target.UserEntity); }
public void GivenNoClaimsIdentityExists_WhenIAuthenticate_ThenCorrectRedirectResponseIssued() { AuthorizationContext authorizationContext = CreateAuthorizationContext(true, "whatever"); authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf"); WSFederationAuthenticationModule module = new WSFederationAuthenticationModule { Issuer = "http://blah.com", HomeRealm = "http://blah.com", Realm = "http://site.com" }; IAuthenticationModuleProvider provider = MockRepository.GenerateMock<IAuthenticationModuleProvider>(); provider.Expect(m => m.GetModule()).Return(module); AuthenticationUtility.SetModuleProvider(provider); Target.OnAuthorization(authorizationContext); Assert.IsInstanceOfType(authorizationContext.Result, typeof(RedirectToRouteResult)); ((RedirectToRouteResult)authorizationContext.Result).AssertActionRedirection("Login", "Account"); }
public ActionResult IssueResponse() { if (Request.Form.HasKeys()) { if (Request.Form["SAMLResponse"] != null) { var samlResponse = Request.Form["SAMLResponse"]; var responseDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(HttpUtility.HtmlDecode(samlResponse))); Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken token; using (var sr = new StringReader(responseDecoded)) { using (var reader = XmlReader.Create(sr)) { reader.ReadToFollowing("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion"); var coll = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); token = (Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken)coll.ReadToken(reader.ReadSubtree()); } } var realm = token.Assertion.Conditions.AudienceRestrictions[0].Audiences[0].ToString(); var issuer = token.Assertion.Issuer.Value; var rstr = new RequestSecurityTokenResponse { TokenType = Constants.TokenKeys.TokenType, RequestType = Constants.TokenKeys.RequestType, KeyType = Constants.TokenKeys.KeyType, Lifetime = new Lifetime(token.Assertion.IssueInstant, token.Assertion.Conditions.NotOnOrAfter), AppliesTo = new System.ServiceModel.EndpointAddress(new Uri(realm)), RequestedSecurityToken = new RequestedSecurityToken(GetElement(responseDecoded)) }; var principal = GetClaimsIdentity(rstr); if (principal != null) { var claimsPrinciple = Microsoft.IdentityModel.Claims.ClaimsPrincipal.CreateFromPrincipal(principal); var requestMessage = new Microsoft.IdentityModel.Protocols.WSFederation.SignInRequestMessage(new Uri("http://foo"), realm); var ipc = new SamlTokenServiceConfiguration(issuer); SecurityTokenService identityProvider = new SamlTokenService(ipc); var responseMessage = Microsoft.IdentityModel.Web.FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, claimsPrinciple, identityProvider); new SignInSessionsManager(HttpContext, _cookieName, ConfigurationRepository.Global.MaximumTokenLifetime).AddEndpoint(responseMessage.BaseUri.AbsoluteUri); Microsoft.IdentityModel.Web.FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, System.Web.HttpContext.Current.Response); } //return new EmptyResult(); } var fam = new WSFederationAuthenticationModule { FederationConfiguration = new FederationConfiguration() }; if (fam.CanReadSignInResponse(Request)) { var responseMessage = fam.GetSignInResponseMessage(Request); return ProcessSignInResponse(responseMessage, fam.GetSecurityToken(Request)); } } return View("Error"); }
private ClaimsPrincipal ValidateToken(SignInResponseMessage signInResponse) { var serviceConfig = new FederationConfiguration(); var fam = new WSFederationAuthenticationModule { FederationConfiguration = serviceConfig }; var tokenFromAcs = fam.GetSecurityToken(signInResponse); var icp = ValidateToken(tokenFromAcs); return icp; }
protected string GetSessionTokenContext() { return("(" + typeof(WSFederationAuthenticationModule).Name + ")" + WSFederationAuthenticationModule.GetFederationPassiveSignOutUrl(this.Issuer, string.Empty, string.Empty)); }
public ActionResult IssueResponse() { if (Request.Form.HasKeys()) { if (Request.Form["SAMLResponse"] != null) { var samlResponse = Request.Form["SAMLResponse"]; var responseDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(HttpUtility.HtmlDecode(samlResponse))); Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken token; using (var sr = new StringReader(responseDecoded)) { using (var reader = XmlReader.Create(sr)) { reader.ReadToFollowing("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion"); var coll = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); token = (Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken)coll.ReadToken(reader.ReadSubtree()); } } var realm = token.Assertion.Conditions.AudienceRestrictions[0].Audiences[0].ToString(); var issuer = token.Assertion.Issuer.Value; var rstr = new RequestSecurityTokenResponse { TokenType = Constants.TokenKeys.TokenType, RequestType = Constants.TokenKeys.RequestType, KeyType = Constants.TokenKeys.KeyType, Lifetime = new Lifetime(token.Assertion.IssueInstant, token.Assertion.Conditions.NotOnOrAfter), AppliesTo = new System.ServiceModel.EndpointAddress(new Uri(realm)), RequestedSecurityToken = new RequestedSecurityToken(GetElement(responseDecoded)) }; var principal = GetClaimsIdentity(rstr); if (principal != null) { var claimsPrinciple = Microsoft.IdentityModel.Claims.ClaimsPrincipal.CreateFromPrincipal(principal); var requestMessage = new Microsoft.IdentityModel.Protocols.WSFederation.SignInRequestMessage(new Uri("http://foo"), realm); var ipc = new SamlTokenServiceConfiguration(issuer); SecurityTokenService identityProvider = new SamlTokenService(ipc); var responseMessage = Microsoft.IdentityModel.Web.FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, claimsPrinciple, identityProvider); new SignInSessionsManager(HttpContext, _cookieName, ConfigurationRepository.Global.MaximumTokenLifetime).AddEndpoint(responseMessage.BaseUri.AbsoluteUri); Microsoft.IdentityModel.Web.FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, System.Web.HttpContext.Current.Response); } //return new EmptyResult(); } var fam = new WSFederationAuthenticationModule { FederationConfiguration = new FederationConfiguration() }; if (fam.CanReadSignInResponse(Request)) { var responseMessage = fam.GetSignInResponseMessage(Request); return(ProcessSignInResponse(responseMessage, fam.GetSecurityToken(Request))); } } return(View("Error")); }
/// <summary> /// Executed when the authentication should be done. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private void context_AuthenticateRequest(object sender, EventArgs e) { // Get the request. var request = ((HttpApplication)sender).Request; // The redirect back from the security token service is done using a POST method. Hence // abort processing of the current request, if it was not sent using POST. if (request.HttpMethod != "POST") { return; } // Check whether the request contains sign in data. if (request.Form["wa"] != WSFederationConstants.Actions.SignIn || request.Form["wresult"].IsNullOrEmpty()) { return; } // Otherwise, get the security token which is attached to the request, process it and // convert it to a principal. First, set up the federatec authentication module. var fam = new WSFederationAuthenticationModule { ServiceConfiguration = new ServiceConfiguration { AudienceRestriction = { AudienceMode = AudienceUriMode.Never }, CertificateValidationMode = X509CertificateValidationMode.Custom, CertificateValidator = new CertificateValidator(c => true), IssuerNameRegistry = new X509CertificateIssuerNameRegistry() } }; // Prepare the decryption by injecting the certificate to the service token resolver. var certificates = new List <SecurityToken> { new X509SecurityToken( this.Container.Resolve <ICertificateManager>().GetEncryptingCertificate()) }; var encryptedSecurityTokenHandler = (from handler in fam.ServiceConfiguration.SecurityTokenHandlers where handler is EncryptedSecurityTokenHandler select handler).First() as EncryptedSecurityTokenHandler; encryptedSecurityTokenHandler.Configuration.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(certificates.AsReadOnly(), false); // Get the security token from the request. var securityToken = fam.GetSecurityToken(request); // Validate the token and convert it to a collection of claims. var claims = fam.ServiceConfiguration.SecurityTokenHandlers.ValidateToken(securityToken); // Create a principal from the claims. IClaimsPrincipal principal = new ClaimsPrincipal(claims); // Set the current principal. HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; }