public void GetSecurityToken_AllOkay_SecurityTokenReturned() { // Act SecurityToken actAsToken = AdfsHelper.GetSecurityToken("https://devtest-idp.vfltest.dk/adfs/services/trust/13/usernamemixed", "https://dev.dcf.ws.dlbr.dk/DCFServices/", "DCFIntegrationstest", "dcftest"); // Assert actAsToken.Should().NotBeNull(); }
private void context_ExecutingWebRequestADFS(object sender, WebRequestEventArgs e) { var wtrealm = _configuration.AdfsRealm; var wctx = string.Format("{0}/_layouts/Authenticate.aspx?Source=%2F", _configuration.SiteUrl); var wreply = string.Format("{0}/_trust/", _configuration.SiteUrl); var stsUrl = string.Format("https://{0}/adfs/services/trust/2005/usernamemixed", _configuration.AdfsSTSUrl); try { e.WebRequestExecutor.WebRequest.CookieContainer = AdfsHelper.AttachCookie(_configuration.SiteUrl, wctx, wtrealm, wreply, stsUrl, _configuration.Username, _configuration.Password); } catch { AdfsHelper.InValidateCookie(); throw; } }
public async Task <ClaimsPrincipal> ValidateJWT(AdfsEndpoint endpoint, string token, string[] audiences) { if (_securityKey == null) { _securityKey = await AdfsHelper.GetAdfsSigningKeys(endpoint.Uri); } TokenValidationParameters validationParameters = new TokenValidationParameters { ValidateIssuer = false, //ValidIssuer = $"{endpoint.Uri}adfs/services/trust" , //ValidIssuers = new[] { $"{endpoint.Uri}adfs/services/trust" }, ValidAudiences = audiences, IssuerSigningKeys = _securityKey }; SecurityToken validatedToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); try { var claims = handler.ValidateToken(token, validationParameters, out validatedToken); return(claims); } catch (Exception ex) { var fragment = new TextFragment() { Code = TextCodes.JWTExpire, DefaultFormatting = $"JWT字符串{token}已经过期,请重新登录!", ReplaceParameters = new List <object>() { token , HashEntityNames.CommonLog } }; throw new UtilityException((int)Errors.EntityAttributeMetadataValueTypeNotMatchEntityAttributeValueKeyConvertService, fragment); } }
public void GetActAsToken_AllOkay_SecurityTokenReturned() { // Arrange SecurityToken bootstrap = AdfsHelper.GetSecurityToken("https://devtest-idp.vfltest.dk/adfs/services/trust/13/usernamemixed", "https://dev.dcf.ws.dlbr.dk/DCFServices/", "DCFIntegrationstest", "dcftest"); ClaimsIdentity identity = new ClaimsIdentity(); identity.BootstrapContext = bootstrap; ClaimsPrincipal principal = new ClaimsPrincipal(identity); Thread.CurrentPrincipal = principal; // Act SecurityToken actAsToken = AdfsHelper.GetActAsToken("https://devtest-idp.vfltest.dk/adfs/services/trust/13/usernamemixed", "https://dev.dcf.ws.dlbr.dk/DCFServices/", "DCFKVKService", "dcfkvk898"); // Assert actAsToken.Should().NotBeNull(); }
public async Task <ClaimsPrincipal> ValidateJWT(AdfsEndpoint endpoint, string token, string[] audiences) { if (_securityKey == null) { _securityKey = await AdfsHelper.GetAdfsSigningKeys(endpoint.Uri); } TokenValidationParameters validationParameters = new TokenValidationParameters { ValidateIssuer = false, //ValidIssuer = $"{endpoint.Uri}adfs/services/trust" , //ValidIssuers = new[] { $"{endpoint.Uri}adfs/services/trust" }, ValidAudiences = audiences, IssuerSigningKeys = _securityKey }; SecurityToken validatedToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); var claims = handler.ValidateToken(token, validationParameters, out validatedToken); return(claims); }
/// <summary> /// This method tries to login the provided user on the specified ADFS IDP. If successful the current principal will be attached to the Thread and it will return the security token. /// /// If login is not successful it will throw an AdfsSecurityException specifying the reason. /// /// </summary> /// <param name="adfs">Options indicating which IDP to use and a few other options.</param> /// <param name="userName">The username to login</param> /// <param name="password">The users password</param> /// <returns>The obtained security token</returns> /// /// <throws>If login is not successful it will throw AdfsSecurityException with one of the reason codes (UserNameOrPasswordIncorrect, PasswordHasExpired, AccountDisabled, AccountLockedOut, PasswordMustChange)</throws> public static SecurityToken Login(AdfsOptions adfs, string userName, string password) { if (string.IsNullOrEmpty(adfs.Realm)) { adfs.Realm = GetAudienceUri(); } Thread.CurrentPrincipal = null; if (!string.IsNullOrEmpty(adfs.UserValidationServiceUri)) { ValidateUser(adfs.UserValidationServiceUri, userName, password); } GenericXmlSecurityToken securityToken = (GenericXmlSecurityToken)AdfsHelper.GetSecurityToken(adfs.IdpEndpoint, adfs.Realm, userName, password); SamlSecurityToken token = (SamlSecurityToken)FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers.ReadToken(new XmlTextReader(new StringReader(securityToken.TokenXml.OuterXml))); ClaimsIdentity identity = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers.ValidateToken(token).First(); // Get the IClaimsPrincipal and attach it to the current thread ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); Thread.CurrentPrincipal = claimsPrincipal; return(securityToken); }
private async Task GetAdfsAuth(string adfsUrl, string clientId, string clientSecret, string crmUrl, string userName, string password, Func <AdfsAuth, Task> action) { var strKey = GenerateKeyString(adfsUrl, clientId, clientSecret, crmUrl, userName, password); if (!_adfsAuthContexts.TryGetValue(strKey, out AdfsAuthWrapperContainer wrapperContainer)) { SharePool <AdfsAuthWrapper> wrapperPool = new SharePool <AdfsAuthWrapper>("Adfs", () => { return(null); }, (wrapper) => { return(true); } , (wrapper) => { }, async() => { var auth = await AdfsHelper.GetAdfsAuthDirect(adfsUrl, $"{crmUrl}/api/data", clientId, clientSecret, userName, password); AdfsAuthWrapper wrapper = new AdfsAuthWrapper() { AdfsAuth = auth, AdfsParameter = new AdfsParameter() { AdfsUrl = adfsUrl, ClientId = clientId, CrmUrl = crmUrl, ClientSecret = clientSecret, UserName = userName, Password = password }, CreateTime = DateTime.UtcNow, TokenCreateTime = DateTime.UtcNow }; return(wrapper); } , async(wrapper) => { if ((DateTime.UtcNow - wrapper.CreateTime).TotalSeconds > _refreashTokenTimeout - 100) { return(await Task.FromResult(false)); } return(await Task.FromResult(true)); } , async(wrapper) => { await Task.FromResult(0); }, _poolLimit ); wrapperContainer = new AdfsAuthWrapperContainer() { ContextPool = wrapperPool, LastTime = DateTime.UtcNow }; lock (_adfsAuthContexts) { if (_adfsAuthContexts.Count > _limit) { var deleteItem = (from item in _adfsAuthContexts orderby item.Value.LastTime select item ).FirstOrDefault(); if (deleteItem.Key != null) { _adfsAuthContexts.Remove(deleteItem.Key); } } _adfsAuthContexts[strKey] = wrapperContainer; } } AdfsAuthWrapper adfsAuthWrapper = null; AdfsAuth adfsAuth = null; adfsAuthWrapper = await wrapperContainer.ContextPool.GetAsync(); if ((DateTime.UtcNow - adfsAuthWrapper.TokenCreateTime).TotalSeconds > adfsAuthWrapper.AdfsAuth.Expires - 20) { adfsAuth = await AdfsHelper.RefreshToken(adfsAuthWrapper.AdfsParameter.AdfsUrl, clientId, clientSecret, adfsAuthWrapper.AdfsAuth.RefreshToken); adfsAuthWrapper.AdfsAuth = adfsAuth; adfsAuthWrapper.TokenCreateTime = DateTime.UtcNow; } else { adfsAuth = adfsAuthWrapper.AdfsAuth; } await action(adfsAuth); }