public void TryParseInvalidStringReturnsFalse(string invalidString) { SimpleWebToken dummy; bool actual = SimpleWebToken.TryParse(invalidString, out dummy); Assert.False(actual); }
public void TryParseInvalidStringReturnsFalse(string invalidString) { SimpleWebToken dummy; var isValid = SimpleWebToken.TryParse(invalidString, out dummy); Assert.False(isValid); }
/// <summary> /// Reads the headers to determine client location & identity /// </summary> /// <returns>Service execution context</returns> private SvcContext InflateContext() { var ctx = new SvcContext(); var latLon = new LatLon(); if (latLon.Inflate()) { ctx.ClientGeolocation = latLon; } //else { ctx.Invalid = true; ctx.ContextMessage = Forbidden("Operation not allowed"); return ctx; } SimpleWebToken swttoken = null; if (!IsAuthenticated(HttpContext.Current, out swttoken)) { ctx.Invalid = true; if (swttoken == null) { ctx.ContextMessage = Unauthorized("Token required"); } else if (swttoken.IsExpired) { ctx.ContextMessage = Unauthorized("Token expired"); } else { ctx.ContextMessage = Unauthorized("Token invalid"); } } return(ctx); }
public void NewTokenWithArgs() { var args = new Dictionary<string, string> { {"alfa", "beta"}, {"http://unittest-ip.com/alfa", "fisk & fugl"} }; const string issuer = "http://unittest-ip.com/"; const string audience = "http://unittest-rt.com/"; var expiresOn = new DateTime(2034, 4, 7, 23, 12, 34, DateTimeKind.Utc); const string signingKey = "nh0BPopBTc7MAzviohoUbWNhO6NlV+LYm+sXOTPULxk="; var swt = new SimpleWebToken(issuer, audience, expiresOn, signingKey, args); Assert.AreEqual(expiresOn, swt.ExpiresOn); Assert.AreEqual(issuer, swt.Issuer); Assert.AreEqual(audience, swt.Audience); Assert.IsNotNull(swt.RawToken); Assert.IsNotNull(swt.Signature); Assert.IsTrue(swt.ValidateSignature(signingKey)); foreach (var item in args) Assert.AreEqual(item.Value, swt[item.Key]); Assert.AreEqual(2, swt.Keys.Count()); Assert.IsTrue(swt.Keys.Contains("alfa")); Assert.IsTrue(swt.Keys.Contains("http://unittest-ip.com/alfa")); }
public void RoundTrip() { var args = new Dictionary <string, string> { { "alfa", "beta" }, { "http://unittest-ip.com/alfa", "fisk & fugl" } }; const string issuer = "http://unittest-ip.com/"; const string audience = "http://unittest-rt.com/"; var expiresOn = new DateTime(2034, 4, 7, 23, 12, 34, DateTimeKind.Utc); const string signingKey = "nh0BPopBTc7MAzviohoUbWNhO6NlV+LYm+sXOTPULxk="; var swt0 = new SimpleWebToken().CreateToken(issuer, audience, expiresOn, signingKey, args); var swt = new SimpleWebToken().CreateTokenFromRaw(swt0.RawToken); Assert.IsTrue(swt.ValidateSignature(signingKey)); Assert.AreEqual(expiresOn, swt.ExpiresOn); Assert.AreEqual(issuer, swt.Issuer); Assert.AreEqual(audience, swt.Audience); Assert.IsNotNull(swt.RawToken); Assert.IsNotNull(swt.Signature); foreach (var item in args) { Assert.AreEqual(item.Value, swt[item.Key]); } Assert.AreEqual(2, swt.Keys.Count()); Assert.IsTrue(swt.Keys.Contains("alfa")); Assert.IsTrue(swt.Keys.Contains("http://unittest-ip.com/alfa")); }
// POST api/issue public HttpResponseMessage Post(TokenRequest rst) { Uri scope = rst.Scope; if (scope == null) { return(Request.CreateResponse <TokenResponse>(HttpStatusCode.BadRequest, new TokenResponse() { Error = OAuthError.INVALID_REQUEST })); } string key = OAuthConfiguration.Configuration.StsSettings.SymmetricKey; TimeSpan lifeTime = new TimeSpan(0, 0, OAuthConfiguration.Configuration.StsSettings.TokenLifeTimeInSec); var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Name, this.User.Identity.Name)); claims.Add(new Claim(ClaimTypes.Role, "AssetsServiceUser")); claims.Add(new Claim(ClaimTypes.Role, "Developer")); claims.Add(new Claim(ClaimTypes.Role, "Administrator")); SimpleWebToken token = new SimpleWebToken(scope, OAuthConfiguration.Configuration.StsSettings.IssuerUri.ToString(), DateTime.UtcNow + lifeTime, claims, key); var tokenResponse = new TokenResponse() { AccessToken = token.ToString(), TokenType = "bearer", ExpiresIn = 600 }; return(Request.CreateResponse <TokenResponse>(HttpStatusCode.OK, tokenResponse)); }
public void WhenMultipleClaimValues_ThenExposesClaims() { var token = new SimpleWebToken("Role=Admin,User"); var values = token.Claims.GetValues("Role"); Assert.Equal(2, values.Length); }
public void ToStringReturnsCorrectResult(string[] keysAndValues, string expected) { var claims = keysAndValues.Select(k => k.Split('|')) .Select(k => new Claim(k[0], k[1])) .ToArray(); var sut = new SimpleWebToken(claims); var actual = sut.ToString(); Assert.Equal(expected, actual); }
public void WhenParsing_ThenCalculatesIsExpired() { var expiration = DateTime.UtcNow.Subtract(TimeSpan.FromHours(1)).ToEpochTime(); var token = new SimpleWebToken(new TokenData { ExpiresOn = expiration, }.ToString()); Assert.True(token.IsExpired); }
public void ToStringReturnsCorrectResult(string[] keysAndValues, string expected) { var claims = keysAndValues .Select(s => s.Split('|')) .Select(s => new Claim(s[0], s[1])) .ToArray(); var sut = new SimpleWebToken(claims); var actual = sut.ToString(); Assert.Equal(expected, actual); }
public void TryParseInvalidStringReturnsFalse(string invalidString) { // Fixture setup // Exercise system SimpleWebToken dummy; bool actual = SimpleWebToken.TryParse(invalidString, out dummy); // Verify outcome Assert.False(actual); // Teardown }
/// <summary> /// Issues the token. /// </summary> /// <param name="scope">The scope.</param> /// <param name="claims">The claims.</param> /// <returns>System.String.</returns> private string IssueToken(Uri scope, params Claim[] claims) { var tokenIssuer = SecurityConfiguration.Instance.TokenIssuer; if (tokenIssuer != null) { return(SimpleWebToken.Create(tokenIssuer.Uri, scope, DateTime.UtcNow + tokenIssuer.Lifetime, tokenIssuer.SignatureKey, claims)); } return(""); }
public void ToStringShouldBeRight(string[] action, string expected) { //var expected = new[] // { // new Claim("foo", "bar") // }; var claims = action.Select(s => s.Split('|')).Select(a => new Claim(a[0], a[1])).ToArray(); var sut = new SimpleWebToken(claims); Assert.Equal(expected, sut.ToString()); }
public void ToStringShouldBeRight(string[] action, string expected) { //var expected = new[] // { // new Claim("foo", "bar") // }; var claims = action.Select(s => s.Split('|')).Select(a => new Claim(a[0], a[1])).ToArray(); var sut = new SimpleWebToken(claims); Assert.Equal(expected, sut.ToString()); }
//[InlineData(new[] { "foo|bar", "baz|qux" }, "foo=bar&baz=qux")] public void TryParseValidStringReturnsTrue(string[] keysAndValues) { var expected = keysAndValues.Select(k => k.Split('|')) .Select(k => new Claim(k[0], k[1])) .ToArray(); var tokenString = new SimpleWebToken(expected).ToString(); SimpleWebToken actual; var isValid = SimpleWebToken.TryParse(tokenString, out actual); Assert.True(isValid); Assert.True(expected.SequenceEqual(actual, new ClaimComparer())); }
//[HttpPost, CfAuthorize] //public ActionResult SaveClimbImages(Guid id, string guidlist) //{ // var items = new List<TempImageUploadJsonItem>(); // var medSvc = new MediaService(); // var climb = geoSvc.GetClimbByID(id); // //you can use the MvcUploader.GetUploadedFile in any where // using (CuteWebUI.MvcUploader uploader = new CuteWebUI.MvcUploader(System.Web.HttpContext.Current)) // { // foreach (string strguid in guidlist.Split('/')) // { // var item = new TempImageUploadJsonItem(); // item.FileGuid = strguid; // CuteWebUI.MvcUploadFile file = uploader.GetUploadedFile(new Guid(strguid)); // if (file == null) // { // item.Exists = false; // item.Error = "File not exists"; // continue; // } // item.FileName = file.FileName; // item.FileSize = file.FileSize; // //process this item.. // using (var stream = file.OpenStream()) // { // //you should validate it here: // var media = new cf.Entities.Media() { Title = item.FileName }; // if (climb.HasAvatar) // { // medSvc.CreateImageMedia(media, climb.ID, stream); // } // else // { // geoSvc.SaveClimbAvatar(climb, stream, null); // } // } // items.Add(item); // } // } // return new JsonResult() { Data = items }; //} protected static bool IsAuthenticated(HttpContextBase context) { //-- If the WIF pipeline has already authenticated the user just return if (context.User.Identity.IsAuthenticated) { return(true); } //-- Otherwise try to authenticate by swt token in header SimpleWebToken swttoken = null; return(SwtAuthenticate(context, out swttoken).Identity.IsAuthenticated); }
public void SutYieldsInjectedClaims() { var expected = new[] { new Claim("foo", "bar"), new Claim("bax", "qux"), new Claim("quux", "corge") }; var sut = new SimpleWebToken(expected); Assert.True(expected.SequenceEqual(sut)); Assert.True(expected.Cast <object>().SequenceEqual(((System.Collections.IEnumerable)sut).OfType <object>())); }
private static SimpleWebToken CreateSimpleWebToken(string issuer, string scope, TimeSpan validity, NameValueCollection additionalInfo) { var swt = new SimpleWebToken(issuer) { Audience = scope, TokenValidity = validity }; if (additionalInfo != null) { foreach (string key in additionalInfo.AllKeys) { swt.Parameters.Add(key, additionalInfo[key]); } } return swt; }
public void YieldEnumeratorOfClaims() { var expected = new[] { new Claim("foo", "bar"), new Claim("queue", "qux"), new Claim("Rafael", "Ricardo") }; var sut = new SimpleWebToken(expected); Assert.True(expected.SequenceEqual(sut)); Assert.True(expected.Cast <object>().SequenceEqual(sut.OfType <object>())); }
public void TryParsevalidStringReturnsCorrectResult(string[] keysAndValues) { var expected = keysAndValues .Select(s => s.Split('|')) .Select(s => new Claim(s[0], s[1])) .ToArray(); var tokenString = new SimpleWebToken(expected).ToString(); SimpleWebToken actual; var isValid = SimpleWebToken.TryParse(tokenString, out actual); Assert.True(isValid, "Token string was not valid"); Assert.True(expected.SequenceEqual(actual, new ClaimComparer())); }
public void YieldEnumeratorOfClaims() { var expected = new[] { new Claim("foo", "bar"), new Claim("queue", "qux"), new Claim("Rafael", "Ricardo") }; var sut = new SimpleWebToken(expected); Assert.True(expected.SequenceEqual(sut)); Assert.True(expected.Cast<object>().SequenceEqual(sut.OfType<object>())); }
public void SutYieldInjectedClaims() { var expected = new[] { new Claim("foo", "bar"), new Claim("baz", "qux"), new Claim("quux", "corge") }; var sut = new SimpleWebToken(expected); Assert.True(expected.SequenceEqual(sut)); Assert.True(expected.Cast<object>().SequenceEqual(((IEnumerable)sut).OfType<object>())); }
private void WrapSWT(NameValueCollection collection, SimpleWebToken token, bool deflate) { var rawToken = token.RawToken; if (deflate) { var zipped = ZipStr(rawToken); rawToken = Convert.ToBase64String(zipped); collection["wrap_deflated"] = "true"; } collection["wrap_access_token"] = _httpUtility.UrlEncode(rawToken); var seconds = Convert.ToInt32((token.ValidTo - token.ValidFrom).TotalSeconds); collection["wrap_access_token_expires_in"] = seconds.ToString(); }
protected static IClaimsPrincipal SwtAuthenticate(HttpContextBase context, out SimpleWebToken swttoken) { IClaimsIdentity currentIdentiy = context.User.Identity as IClaimsIdentity; IClaimsPrincipal incomingPrincipal = context.User as IClaimsPrincipal; //if (!incomingPrincipal.Identity.IsAuthenticated) //{ if (new cf.Identity.CfIdentityInflater().TryGetSwtClaimsIdentity(out currentIdentiy, out swttoken)) { incomingPrincipal.Identities[0] = currentIdentiy; } //} return(incomingPrincipal); }
public void SutYieldsInjectedClaims() { var expected = new[] { new Claim("foo", "bar"), new Claim("baz", "qux"), new Claim("quux", "corge"), }; var sut = new SimpleWebToken(expected); Assert.True(expected.SequenceEqual(sut)); Assert.True( expected.SequenceEqual( sut.OfType <object>())); }
private static string CreateSwtToken() { var signingKey = "wAVkldQiFypTQ+kdNdGWCYCHRcee8XmXxOvgmak8vSY="; var audience = "http://websample"; var issuer = "http://self"; var token = new SimpleWebToken(issuer, audience, Convert.FromBase64String(signingKey)); token.AddClaim(ClaimTypes.Name, "dominick"); token.AddClaim(ClaimTypes.Email, "*****@*****.**"); token.AddClaim(ClaimTypes.Role, "Users"); token.AddClaim(ClaimTypes.Role, "Administrators"); token.AddClaim("simple", "test"); return token.ToString(); }
public void TestSimpleWebToken() { var payload = new { i = "", n = "", e = DateTime.Now.ToString() }; var token = string.Empty; Stopwatch stopwatch = new Stopwatch(); stopwatch.Reset(); stopwatch.Start(); for (int i = 0; i < 10; i++) { token = SimpleWebToken.Encode(payload, "MD5"); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(SimpleWebToken.Decode(token))); } stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedTicks); }
public void NewToken() { const string issuer = "http://unittest-ip.com/"; const string audience = "http://unittest-rt.com/"; var expiresOn = new DateTime(2034, 4, 7, 23, 12, 34, DateTimeKind.Utc); const string signingKey = "nh0BPopBTc7MAzviohoUbWNhO6NlV+LYm+sXOTPULxk="; var swt = new SimpleWebToken(issuer, audience, expiresOn, signingKey); Assert.AreEqual(expiresOn, swt.ExpiresOn); Assert.AreEqual(issuer, swt.Issuer); Assert.AreEqual(audience, swt.Audience); Assert.IsNotNull(swt.RawToken); Assert.IsNotNull(swt.Signature); Assert.IsTrue(swt.ValidateSignature(signingKey)); Assert.AreEqual(0, swt.Keys.Count()); }
private static string CreateSwtToken() { var signingKey = "wAVkldQiFypTQ+kdNdGWCYCHRcee8XmXxOvgmak8vSY="; var audience = "http://websample"; var issuer = "http://self"; var token = new SimpleWebToken(issuer, audience, Convert.FromBase64String(signingKey)); token.AddClaim(ClaimTypes.Name, "dominick"); token.AddClaim(ClaimTypes.Email, "*****@*****.**"); token.AddClaim(ClaimTypes.Role, "Users"); token.AddClaim(ClaimTypes.Role, "Administrators"); token.AddClaim("simple", "test"); return(token.ToString()); }
public void ToStringReturnsCorrectResult( string[] keysAndValues, string expected) { // Fixture setup var claims = keysAndValues .Select(s => s.Split('|')) .Select(a => new Claim(a[0], a[1])) .ToArray(); var sut = new SimpleWebToken(claims); // Exercise system var actual = sut.ToString(); // Verify outcome Assert.Equal(expected, actual); }
public string AuthenticateUser(string userName, string password, Uri scope) { string token = null; string role = userName == "Administrator" ? "adminis" : "everyone"; if (_validUsers.Any(u => string.Equals(u, userName, StringComparison.OrdinalIgnoreCase))) { token = SimpleWebToken.Create(_tokenIssuer, scope, DateTime.UtcNow.AddHours(1), _tokenSignatureKey, new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.NameIdentifier, "ID"), new Claim(ClaimTypes.Role, role) ); } return(token); }
public void TryParseCorrectStringReturnsCorrectResult( string[] keysAndValues) { var expected = keysAndValues .Select(s => s.Split('|')) .Select(a => new Claim(a[0], a[1])) .ToArray(); var tokenString = new SimpleWebToken(expected).ToString(); SimpleWebToken actual; var isValid = SimpleWebToken.TryParse(tokenString, out actual); Assert.True(isValid, "Token string was not considered valid"); Assert.True(expected.SequenceEqual(actual, new ClaimComparer())); }
/// <summary> /// Tries to retrieve the clients ClaimsIdentity from the current request context. /// </summary> /// <param name="identity">The identity.</param> /// <returns>True when a valid identity was found - otherwise false.</returns> public virtual bool TryGetSwtClaimsIdentity(out IClaimsIdentity identity, out SimpleWebToken swttoken) { identity = null; // check header first - authorization and x-authorization var authZheader = HttpContext.Current.Request.Headers["cf-Authorization"]; if (!string.IsNullOrEmpty(authZheader)) { try { if (authZheader.StartsWith("cfST=")) { var encryptedBase64TokenString = authZheader.Substring("cfST=".Length); var encryptedTokenBytes = Convert.FromBase64String(encryptedBase64TokenString); var encryptedTokenString = enc.GetString(encryptedTokenBytes); var tokenString = cf.Identity.DHDRSA.DecryptWithSymmetricAid((RSACryptoServiceProvider)cert.PrivateKey, encryptedTokenString); tokenString = tokenString.Replace("_ws", "http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2f"). Replace("_ms", "http%3a%2f%2fschemas.microsoft.com%2fws%2f2008%2f06%2fidentity%2fclaims%2f"). Replace("_ma", "http%3a%2f%2fschemas.microsoft.com%2fws%2f2008%2f06%2fidentity%2fauthenticationmethod%2f"). Replace("_cf", "http%3a%2f%2fclimbfind.com%2fclaims%2f"). Replace("_ct", "http%3a%2f%2faccounts.climbfind.com%2ftrust"); swttoken = new SimpleWebToken(HttpUtility.UrlDecode(tokenString)); identity = swttoken.ToClaimsIdentity(); } else { throw new AccessViolationException("Client usage of cf-Auth is invalid. This request has been logged & legal action will be taken if the client illegally access Climbfinds systems"); } return(true); } catch { swttoken = null; return(false); } } else { swttoken = null; } return(false); }
public void NewToken() { const string issuer = "http://unittest-ip.com/"; const string audience = "http://unittest-rt.com/"; var expiresOn = new DateTime(2034, 4, 7, 23, 12, 34, DateTimeKind.Utc); const string signingKey = "nh0BPopBTc7MAzviohoUbWNhO6NlV+LYm+sXOTPULxk="; var swt = new SimpleWebToken().CreateToken(issuer, audience, expiresOn, signingKey); Assert.AreEqual(expiresOn, swt.ExpiresOn); Assert.AreEqual(issuer, swt.Issuer); Assert.AreEqual(audience, swt.Audience); Assert.IsNotNull(swt.RawToken); Assert.IsNotNull(swt.Signature); Assert.IsTrue(swt.ValidateSignature(signingKey)); Assert.AreEqual(0, swt.Keys.Count()); }
private static SimpleWebToken CreateSimpleWebToken(string issuer, string scope, TimeSpan validity, NameValueCollection additionalInfo) { var swt = new SimpleWebToken(issuer) { Audience = scope, TokenValidity = validity }; if (additionalInfo != null) { foreach (string key in additionalInfo.AllKeys) { swt.Parameters.Add(key, additionalInfo[key]); } } return(swt); }
public void FromValidEncoded() { const string tokenString = "http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=upwJyUGTUPWMEiU3ds61jcsJUeUFjRza6sNEcdyNYnw%3d&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=uri%3aWindowsLiveID&Audience=http%3a%2f%2fnoisesentinel-dev-adminapi.azurewebsites.net%2f&ExpiresOn=1356650451&Issuer=https%3a%2f%2fbruelandkjaer.accesscontrol.windows.net%2f&HMACSHA256=npM6PtfuNUtG6EJ1gpS0s9rVvEx%2buP4UIXe3GB1t4CM%3d"; var swt = new SimpleWebToken(tokenString); Assert.AreEqual(tokenString, swt.RawToken); Assert.AreEqual(new DateTime(2012, 12, 27, 23, 20, 51, DateTimeKind.Utc), swt.ExpiresOn); Assert.AreEqual("https://bruelandkjaer.accesscontrol.windows.net/", swt.Issuer); Assert.AreEqual("http://noisesentinel-dev-adminapi.azurewebsites.net/", swt.Audience); Assert.AreEqual("uri:WindowsLiveID", swt["http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider"]); Assert.AreEqual("upwJyUGTUPWMEiU3ds61jcsJUeUFjRza6sNEcdyNYnw=", swt["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"]); Assert.AreEqual("npM6PtfuNUtG6EJ1gpS0s9rVvEx+uP4UIXe3GB1t4CM=", swt.Signature); Assert.IsTrue(swt.ValidateSignature("eP+VgZq3YVUXSDt71lKnCRoxdoGngCT9WR4vTprH9TY=")); Assert.IsFalse(swt.ValidateSignature("nh0BPopBTc7MAzviohoUbWNhO6NlV+LYm+sXOTPULxk=")); Assert.IsNotNull(swt); Assert.AreEqual(2, swt.Keys.Count()); Assert.IsTrue(swt.Keys.Contains("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider")); Assert.IsTrue(swt.Keys.Contains("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")); }
public void WhenParsing_ThenExposesClaimsButNotIntrinsicProperties() { var expiration = DateTime.UtcNow.ToEpochTime(); var token = new SimpleWebToken(new TokenData { IdClaim = "23", NameClaim = "kzu", Audience = "http://netfx.codeplex.com", Issuer = "clarius", ExpiresOn = expiration, }.ToString()); Assert.Equal(2, token.Claims.Count); Assert.Equal("23", token.Claims["IdClaim"]); Assert.Equal("kzu", token.Claims["NameClaim"]); Assert.Equal("http://netfx.codeplex.com", token.Audience); Assert.Equal("clarius", token.Issuer); Assert.Equal(expiration, token.ExpiresOn.ToEpochTime()); }
public void FromValidEncoded() { const string tokenString = "http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=upwJyUGTUPWMEiU3ds61jcsJUeUFjRza6sNEcdyNYnw%3d&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=uri%3aWindowsLiveID&Audience=http%3a%2f%2fnoisesentinel-dev-adminapi.azurewebsites.net%2f&ExpiresOn=1356650451&Issuer=https%3a%2f%2fbruelandkjaer.accesscontrol.windows.net%2f&HMACSHA256=npM6PtfuNUtG6EJ1gpS0s9rVvEx%2buP4UIXe3GB1t4CM%3d"; var swt = new SimpleWebToken().CreateTokenFromRaw(tokenString); Assert.AreEqual(tokenString, swt.RawToken); Assert.AreEqual(new DateTime(2012, 12, 27, 23, 20, 51, DateTimeKind.Utc), swt.ExpiresOn); Assert.AreEqual("https://bruelandkjaer.accesscontrol.windows.net/", swt.Issuer); Assert.AreEqual("http://noisesentinel-dev-adminapi.azurewebsites.net/", swt.Audience); Assert.AreEqual("uri:WindowsLiveID", swt["http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider"]); Assert.AreEqual("upwJyUGTUPWMEiU3ds61jcsJUeUFjRza6sNEcdyNYnw=", swt["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"]); Assert.AreEqual("npM6PtfuNUtG6EJ1gpS0s9rVvEx+uP4UIXe3GB1t4CM=", swt.Signature); Assert.IsTrue(swt.ValidateSignature("eP+VgZq3YVUXSDt71lKnCRoxdoGngCT9WR4vTprH9TY=")); Assert.IsFalse(swt.ValidateSignature("nh0BPopBTc7MAzviohoUbWNhO6NlV+LYm+sXOTPULxk=")); Assert.IsNotNull(swt); Assert.AreEqual(2, swt.Keys.Count()); Assert.IsTrue(swt.Keys.Contains("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider")); Assert.IsTrue(swt.Keys.Contains("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")); }
private static string SerializeToken(SimpleWebToken accessToken, SecurityTokenHandlerCollection handlers) { if (handlers.CanWriteToken(accessToken)) { string token = String.Empty; using (var sw = new StringWriter()) { var writer = new XmlTextWriter(sw); handlers.WriteToken(writer, accessToken); // remove the envelope <stringToken> var envelope = sw.ToString(); token = XElement.Parse(envelope).Value; } return(token); } return(null); }
public override string GetIssuerName(SecurityToken securityToken) { if (securityToken == null) { throw new ArgumentNullException("securityToken"); } SimpleWebToken token = securityToken as SimpleWebToken; if (token != null) { string issuer = token.Issuer.ToLowerInvariant(); if (this.configuredTrustedIssuers.ContainsKey(issuer)) { return(this.configuredTrustedIssuers[issuer]); } } return(null); }
private static string SerializeToken(SimpleWebToken accessToken, SecurityTokenHandlerCollection handlers) { if (handlers.CanWriteToken(accessToken)) { string token = String.Empty; using (var sw = new StringWriter()) { var writer = new XmlTextWriter(sw); handlers.WriteToken(writer, accessToken); // remove the envelope <stringToken> var envelope = sw.ToString(); token = XElement.Parse(envelope).Value; } return token; } return null; }
private static void CheckToken(SimpleWebToken swt, string testKey, string trustedIssuer, string expectedAudience) { SimpleWebTokenValidationResult validationResult = SimpleWebToken.Validate(swt, testKey, trustedIssuer, expectedAudience); Assert.IsTrue(validationResult == SimpleWebTokenValidationResult.Valid, string.Format("Invalid Token: {0}", validationResult.ToString())); }
private static void CheckPrinciple(SimpleWebToken swt) { IClaimsPrincipal principle = swt.ToPrinciple(nameClaimType: ClaimTypes.NameIdentifier); Assert.IsNotNull(principle); IClaimsIdentity identity = principle.Identity as IClaimsIdentity; Assert.IsNotNull(identity); if (identity != null) { foreach (var claim in identity.Claims) { System.Console.WriteLine(string.Format("Claim Type: {0}, Claim Value: {1}", claim.ClaimType, claim.Value)); } } }
public void TestTokenConstructor() { string testKey = "ZncEZCBioztYEE3iC6dSnv+lJC4NmFX7Ns5pDgPKCwU="; string trustedIssuer = "https://clazure.accesscontrol.windows.net/"; string expectedAudience = "http://www.robblackwell.org.uk/"; NameValueCollection claims = new NameValueCollection(); claims.Add("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "robblackwell"); claims.Add("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "https://clazure.accesscontrol.windows.net/"); SimpleWebToken swt = new SimpleWebToken("https://clazure.accesscontrol.windows.net/", "http://www.robblackwell.org.uk/", DateTime.UtcNow.AddHours(1), claims); swt.Sign(testKey); CheckToken(swt, testKey, trustedIssuer, expectedAudience); CheckPrinciple(swt); }
public void Test3() { string testKey = "ZncEZCBioztYEE3iC6dSnv+lJC4NmFX7Ns5pDgPKCwU="; NameValueCollection claims = new NameValueCollection(); claims.Add("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "robblackwell"); claims.Add("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "https://clazure.accesscontrol.windows.net/"); SimpleWebToken swt = new SimpleWebToken("https://clazure.accesscontrol.windows.net/", "http://www.robblackwell.org.uk/", 1331740071, claims); swt.Sign(testKey); Assert.IsTrue(swt.CheckSignature(testKey)); }
public override SecurityToken GetTokenFromString(string token) { // TODO: validate var items = HttpUtility.ParseQueryString(token); var issuer = items[IssuerLabel]; items.Remove(IssuerLabel); var audience = items[AudienceLabel]; items.Remove(AudienceLabel); var expiresOn = items[ExpiresOnLabel]; items.Remove(ExpiresOnLabel); var id = items[IdLabel]; items.Remove(IdLabel); var algorithm = items[SignatureAlgorithmLabel]; items.Remove(SignatureAlgorithmLabel); // Treat signature differently to avoid loosing characters like '+' in the decoding var signature = ExtractSignature(HttpUtility.UrlDecode(token)); items.Remove(SignatureLabel); byte[] signatureBytes = Convert.FromBase64String(signature); DateTime validTo = this.GetDateTimeFromExpiresOn((ulong)Convert.ToInt64(expiresOn)); var swt = new SimpleWebToken(issuer) { Audience = audience, Signature = signatureBytes, TokenValidity = validTo - DateTime.UtcNow }; if (id != null) { swt.SetId(id); } if (string.IsNullOrEmpty(algorithm)) { swt.SignatureAlgorithm = algorithm; } foreach (string key in items.AllKeys) { swt.AddClaim(key, items[key]); } swt.RawToken = token; return swt; }
private bool IsIssuerTrusted(SimpleWebToken accessToken, out string issuerName) { issuerName = null; if (!string.IsNullOrEmpty(accessToken.Issuer)) { if (this.IssuerNameRegistry != null) { issuerName = this.IssuerNameRegistry.GetIssuerName(accessToken); if (!string.IsNullOrEmpty(issuerName)) { return true; } } } return false; }
protected bool IsAudienceTrusted(SimpleWebToken accessToken) { if (this.AudienceRestriction.AudienceMode == AudienceUriMode.Never) { return true; } if (!string.IsNullOrEmpty(accessToken.Audience)) { return this.AudienceRestriction.AllowedAudienceUris.Contains(new Uri(accessToken.Audience)); } return false; }
private void WrapSWT(NameValueCollection collection, SimpleWebToken token, bool deflate) { var rawToken = token.RawToken; if (deflate) { var zipped = this.ZipStr(rawToken); rawToken = Convert.ToBase64String(zipped); collection["wrap_deflated"] = "true"; } collection["wrap_access_token"] = HttpUtility.UrlEncode(rawToken); var seconds = Convert.ToInt32((token.ValidTo - token.ValidFrom).TotalSeconds); collection["wrap_access_token_expires_in"] = seconds.ToString(); }
protected bool IsExpired(SimpleWebToken accessToken) { if (accessToken.ValidTo > DateTime.UtcNow) { return false; } return true; }
protected bool IsValidSignature(SimpleWebToken token, byte[] signingKey) { var unsignedToken = this.GetUnsignedToken(token.RawToken); if (string.IsNullOrEmpty(unsignedToken)) { return false; } var localSignature = GenerateSignature(unsignedToken, signingKey); var incomingSignature = HttpUtility.UrlEncode(Convert.ToBase64String(token.Signature)); return localSignature.Equals(incomingSignature, StringComparison.Ordinal); }
private static IDictionary<string, string> ToDictionary(SimpleWebToken token) { var dictionary = new Dictionary<string, string> { { "Issuer", token.Issuer }, { "Audience", token.Audience } }; return dictionary; }
/// <summary> /// Check if the user is authenticated with a valid token /// </summary> /// <param name="context"></param> /// <returns></returns> protected static bool IsAuthenticated(HttpContext context, out SimpleWebToken swttoken) { IClaimsIdentity currentIdentiy = context.User.Identity as IClaimsIdentity; IClaimsPrincipal incomingPrincipal = context.User as IClaimsPrincipal; //if (!incomingPrincipal.Identity.IsAuthenticated) //{ if (new cf.Identity.CfIdentityInflater().TryGetSwtClaimsIdentity(out currentIdentiy, out swttoken)) { incomingPrincipal.Identities[0] = currentIdentiy; } //} return incomingPrincipal.Identity.IsAuthenticated; }
protected static string SerializeToken(SimpleWebToken swt, SecurityTokenResolver tokenResolver) { StringBuilder builder = new StringBuilder(64); builder.Append("Id="); builder.Append(swt.Id); builder.Append('&'); builder.Append(IssuerLabel); builder.Append('='); builder.Append(swt.Issuer); if (swt.Parameters.Count > 0) { builder.Append('&'); foreach (string key in swt.Parameters.AllKeys) { builder.Append(key); builder.Append('='); builder.Append(swt.Parameters[key]); builder.Append('&'); } } else { builder.Append('&'); } builder.Append(ExpiresOnLabel); builder.Append('='); builder.Append(GetExpiresOn(swt.TokenValidity)); if (!string.IsNullOrEmpty(swt.Audience)) { builder.Append('&'); builder.Append(AudienceLabel); builder.Append('='); builder.Append(swt.Audience); } builder.Append('&'); builder.Append(SignatureAlgorithmLabel); builder.Append('='); builder.Append(SignatureAlgorithm); var keyIdentifierClause = new DictionaryBasedKeyIdentifierClause(ToDictionary(swt)); InMemorySymmetricSecurityKey securityKey; try { securityKey = (InMemorySymmetricSecurityKey)tokenResolver.ResolveSecurityKey(keyIdentifierClause); } catch (InvalidOperationException) { throw new SecurityTokenValidationException(string.Format(CultureInfo.InvariantCulture, "Simmetryc key was not found for the key identifier clause: Keys='{0}', Values='{1}'", string.Join(",", keyIdentifierClause.Dictionary.Keys.ToArray()), string.Join(",", keyIdentifierClause.Dictionary.Values.ToArray()))); } string signature = GenerateSignature(builder.ToString(), securityKey.GetSymmetricKey()); builder.Append("&" + SignatureLabel + "="); builder.Append(signature); return builder.ToString(); }
public void SutIsIteratorOfClaims() { var sut = new SimpleWebToken(); Assert.IsAssignableFrom<IEnumerable<Claim>>(sut); }