public async Task GetAllGrantsAsync_should_return_all_grants() { await _userConsent.StoreUserConsentAsync(new Consent() { ClientId = "client1", SubjectId = "123", Scopes = new string[] { "foo1", "foo2" } }); await _userConsent.StoreUserConsentAsync(new Consent() { ClientId = "client2", SubjectId = "123", Scopes = new string[] { "foo3" } }); await _userConsent.StoreUserConsentAsync(new Consent() { ClientId = "client1", SubjectId = "456", Scopes = new string[] { "foo3" } }); var handle1 = await _referenceTokens.StoreReferenceTokenAsync(new Token() { ClientId = "client1", Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Type = "type", Claims = new List <Claim> { new Claim("sub", "123"), new Claim("scope", "bar1"), new Claim("scope", "bar2"), }, }); var handle2 = await _referenceTokens.StoreReferenceTokenAsync(new Token() { ClientId = "client2", Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Type = "type", Claims = new List <Claim> { new Claim("sub", "123"), new Claim("scope", "bar3"), }, }); var handle3 = await _referenceTokens.StoreReferenceTokenAsync(new Token() { ClientId = "client1", Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Type = "type", Claims = new List <Claim> { new Claim("sub", "456"), new Claim("scope", "bar3"), }, }); var handle4 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { CreationTime = DateTime.UtcNow, Lifetime = 10, AccessToken = new Token { ClientId = "client1", Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Type = "type", Claims = new List <Claim> { new Claim("sub", "123"), new Claim("scope", "baz1"), new Claim("scope", "baz2") } }, Version = 1 }); var handle5 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { CreationTime = DateTime.UtcNow, Lifetime = 10, AccessToken = new Token { ClientId = "client1", Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Type = "type", Claims = new List <Claim> { new Claim("sub", "456"), new Claim("scope", "baz3"), } }, Version = 1 }); var handle6 = await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken() { CreationTime = DateTime.UtcNow, Lifetime = 10, AccessToken = new Token { ClientId = "client2", Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Type = "type", Claims = new List <Claim> { new Claim("sub", "123"), new Claim("scope", "baz3"), } }, Version = 1 }); var handle7 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { ClientId = "client1", CreationTime = DateTime.UtcNow, Lifetime = 10, Subject = _user, CodeChallenge = "challenge", RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux1", "quux2" } }); var handle8 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { ClientId = "client2", CreationTime = DateTime.UtcNow, Lifetime = 10, Subject = _user, CodeChallenge = "challenge", RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux3" } }); var handle9 = await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode() { ClientId = "client1", CreationTime = DateTime.UtcNow, Lifetime = 10, Subject = IdentityServerPrincipal.Create("456", "alice"), CodeChallenge = "challenge", RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux3" } }); var grants = await _subject.GetAllGrantsAsync("123"); grants.Count().Should().Be(2); var grant1 = grants.First(x => x.ClientId == "client1"); grant1.SubjectId.Should().Be("123"); grant1.ClientId.Should().Be("client1"); grant1.Scopes.ShouldBeEquivalentTo(new string[] { "foo1", "foo2", "bar1", "bar2", "baz1", "baz2", "quux1", "quux2" }); var grant2 = grants.First(x => x.ClientId == "client2"); grant2.SubjectId.Should().Be("123"); grant2.ClientId.Should().Be("client2"); grant2.Scopes.ShouldBeEquivalentTo(new string[] { "foo3", "bar3", "baz3", "quux3" }); }
/// <summary> /// Issues the login cookie for IdentityServer. /// </summary> /// <param name="env">The OWIN environment.</param> /// <param name="login">The login information.</param> /// <exception cref="System.ArgumentNullException"> /// env /// or /// login /// </exception> public static void IssueLoginCookie(this IDictionary <string, object> env, AuthenticatedLogin login) { if (env == null) { throw new ArgumentNullException("env"); } if (login == null) { throw new ArgumentNullException("login"); } var options = env.ResolveDependency <IdentityServerOptions>(); var sessionCookie = env.ResolveDependency <SessionCookie>(); var context = new OwinContext(env); var props = new AuthenticationProperties(); // if false, then they're explicit in preventing a persistent cookie if (login.PersistentLogin != false) { if (login.PersistentLogin == true || options.AuthenticationOptions.CookieOptions.IsPersistent) { props.IsPersistent = true; if (login.PersistentLogin == true) { var expires = login.PersistentLoginExpiration ?? DateTimeHelper.UtcNow.Add(options.AuthenticationOptions.CookieOptions.RememberMeDuration); props.ExpiresUtc = expires; } } } var authenticationMethod = login.AuthenticationMethod; var identityProvider = login.IdentityProvider ?? Constants.BuiltInIdentityProvider; if (String.IsNullOrWhiteSpace(authenticationMethod)) { if (identityProvider == Constants.BuiltInIdentityProvider) { authenticationMethod = Constants.AuthenticationMethods.Password; } else { authenticationMethod = Constants.AuthenticationMethods.External; } } var user = IdentityServerPrincipal.Create(login.Subject, login.Name, authenticationMethod, identityProvider, Constants.PrimaryAuthenticationType); var identity = user.Identities.First(); var claims = login.Claims; if (claims != null && claims.Any()) { claims = claims.Where(x => !Constants.OidcProtocolClaimTypes.Contains(x.Type)); claims = claims.Where(x => x.Type != Constants.ClaimTypes.Name); identity.AddClaims(claims); } context.Authentication.SignIn(props, identity); sessionCookie.IssueSessionId(login.PersistentLogin, login.PersistentLoginExpiration); }
private IHttpActionResult SignInAndRedirect( AuthenticateResult authResult, string authenticationMethod, string identityProvider, long authTime = 0) { Logger.Debug("[AuthenticationController.SignInAndRedirect] called"); if (authResult == null) { throw new ArgumentNullException("authResult"); } if (String.IsNullOrWhiteSpace(authenticationMethod)) { throw new ArgumentNullException("authenticationMethod"); } if (String.IsNullOrWhiteSpace(identityProvider)) { throw new ArgumentNullException("identityProvider"); } var signInMessage = LoadLoginRequestMessage(); var issuer = authResult.IsPartialSignIn ? Constants.PartialSignInAuthenticationType : Constants.PrimaryAuthenticationType; var principal = IdentityServerPrincipal.Create( authResult.Subject, authResult.Name, authenticationMethod, identityProvider, issuer, authTime); var id = principal.Identities.First(); if (authResult.IsPartialSignIn) { // TODO: put original return URL into cookie with a GUID ID // and put the ID as route param for the resume URL. then // we can always call ClearLoginRequestMessage() id.AddClaim(new Claim(Constants.ClaimTypes.PartialLoginReturnUrl, Url.Route(Constants.RouteNames.ResumeLoginFromRedirect, null))); // allow redircting code to add claims for target page id.AddClaims(authResult.RedirectClaims); } var ctx = Request.GetOwinContext(); ctx.Authentication.SignOut( Constants.PrimaryAuthenticationType, Constants.ExternalAuthenticationType, Constants.PartialSignInAuthenticationType); ctx.Authentication.SignIn(id); if (authResult.IsPartialSignIn) { Logger.Info("[AuthenticationController.SignInAndRedirect] partial login requested, redirecting to requested url"); var uri = new Uri(ctx.Request.Uri, authResult.PartialSignInRedirectPath.Value); return(Redirect(uri)); } Logger.Info("[AuthenticationController.SignInAndRedirect] normal login requested, redirecting back to authorization"); // TODO -- manage this state better if we're doing redirect to custom page // would rather the redirect URL from request message put into cookie // and named with a nonce, then the resume url + nonce set as claim // in principal above so page being redirected to can know what url to return to ClearLoginRequestMessage(); return(Redirect(signInMessage.ReturnUrl)); }
public async Task RemoveAllGrantsAsync_should_remove_all_grants() { await _userConsent.StoreUserConsentAsync(new Consent() { ClientId = "client1", SubjectId = "123", Scopes = new string[] { "foo1", "foo2" } }); await _userConsent.StoreUserConsentAsync(new Consent() { ClientId = "client2", SubjectId = "123", Scopes = new string[] { "foo3" } }); await _userConsent.StoreUserConsentAsync(new Consent() { ClientId = "client1", SubjectId = "456", Scopes = new string[] { "foo3" } }); await _referenceTokens.StoreReferenceTokenAsync("key1", new Token() { ClientId = "client1", Audience = "aud", CreationTime = DateTime.Now, Type = "type", Claims = new List <Claim> { new Claim("sub", "123"), new Claim("scope", "bar1"), new Claim("scope", "bar2"), }, }); await _referenceTokens.StoreReferenceTokenAsync("key2", new Token() { ClientId = "client2", Audience = "aud", CreationTime = DateTime.Now, Type = "type", Claims = new List <Claim> { new Claim("sub", "123"), new Claim("scope", "bar3"), }, }); await _referenceTokens.StoreReferenceTokenAsync("key3", new Token() { ClientId = "client1", Audience = "aud", CreationTime = DateTime.Now, Type = "type", Claims = new List <Claim> { new Claim("sub", "456"), new Claim("scope", "bar3"), }, }); await _refreshTokens.StoreRefreshTokenAsync("key4", new RefreshToken() { CreationTime = DateTime.Now, Lifetime = 10, AccessToken = new Token { ClientId = "client1", Audience = "aud", CreationTime = DateTime.Now, Type = "type", Claims = new List <Claim> { new Claim("sub", "123"), new Claim("scope", "baz1"), new Claim("scope", "baz2") } }, Version = 1 }); await _refreshTokens.StoreRefreshTokenAsync("key5", new RefreshToken() { CreationTime = DateTime.Now, Lifetime = 10, AccessToken = new Token { ClientId = "client1", Audience = "aud", CreationTime = DateTime.Now, Type = "type", Claims = new List <Claim> { new Claim("sub", "456"), new Claim("scope", "baz3"), } }, Version = 1 }); await _refreshTokens.StoreRefreshTokenAsync("key6", new RefreshToken() { CreationTime = DateTime.Now, Lifetime = 10, AccessToken = new Token { ClientId = "client2", Audience = "aud", CreationTime = DateTime.Now, Type = "type", Claims = new List <Claim> { new Claim("sub", "123"), new Claim("scope", "baz3"), } }, Version = 1 }); await _codes.StoreAuthorizationCodeAsync("key7", new AuthorizationCode() { ClientId = "client1", CreationTime = DateTime.Now, Lifetime = 10, Subject = _user, CodeChallenge = "challenge", RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux1", "quux2" } }); await _codes.StoreAuthorizationCodeAsync("key8", new AuthorizationCode() { ClientId = "client2", CreationTime = DateTime.Now, Lifetime = 10, Subject = _user, CodeChallenge = "challenge", RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux3" } }); await _codes.StoreAuthorizationCodeAsync("key9", new AuthorizationCode() { ClientId = "client1", CreationTime = DateTime.Now, Lifetime = 10, Subject = IdentityServerPrincipal.Create("456", "alice"), CodeChallenge = "challenge", RedirectUri = "http://client/cb", Nonce = "nonce", RequestedScopes = new string[] { "quux3" } }); await _subject.RemoveAllGrantsAsync("123", "client1"); (await _referenceTokens.GetReferenceTokenAsync("key1")).Should().BeNull(); (await _referenceTokens.GetReferenceTokenAsync("key2")).Should().NotBeNull(); (await _referenceTokens.GetReferenceTokenAsync("key3")).Should().NotBeNull(); (await _refreshTokens.GetRefreshTokenAsync("key4")).Should().BeNull(); (await _refreshTokens.GetRefreshTokenAsync("key5")).Should().NotBeNull(); (await _refreshTokens.GetRefreshTokenAsync("key6")).Should().NotBeNull(); (await _codes.GetAuthorizationCodeAsync("key7")).Should().BeNull(); (await _codes.GetAuthorizationCodeAsync("key8")).Should().NotBeNull(); (await _codes.GetAuthorizationCodeAsync("key9")).Should().NotBeNull(); }
public DefaultRefreshTokenServiceTests() { originalNowFunc = DateTimeOffsetHelper.UtcNowFunc; DateTimeOffsetHelper.UtcNowFunc = () => UtcNow; roclient_absolute_refresh_expiration_one_time_only = new Client { ClientName = "Resource Owner Client", Enabled = true, ClientId = "roclient_absolute_refresh_expiration_one_time_only", ClientSecrets = new List <Secret> { new Secret("secret".Sha256()) }, Flow = Flows.ResourceOwner, RefreshTokenExpiration = TokenExpiration.Absolute, RefreshTokenUsage = TokenUsage.OneTimeOnly, AbsoluteRefreshTokenLifetime = 200 }; roclient_sliding_refresh_expiration_one_time_only = new Client { ClientName = "Resource Owner Client", Enabled = true, ClientId = "roclient_sliding_refresh_expiration_one_time_only", ClientSecrets = new List <Secret> { new Secret("secret".Sha256()) }, Flow = Flows.ResourceOwner, RefreshTokenExpiration = TokenExpiration.Sliding, RefreshTokenUsage = TokenUsage.OneTimeOnly, AbsoluteRefreshTokenLifetime = 10, SlidingRefreshTokenLifetime = 4 }; roclient_absolute_refresh_expiration_reuse = new Client { ClientName = "Resource Owner Client", Enabled = true, ClientId = "roclient_absolute_refresh_expiration_reuse", ClientSecrets = new List <Secret> { new Secret("secret".Sha256()) }, Flow = Flows.ResourceOwner, RefreshTokenExpiration = TokenExpiration.Absolute, RefreshTokenUsage = TokenUsage.ReUse, AbsoluteRefreshTokenLifetime = 200 }; refreshTokenStore = new InMemoryRefreshTokenStore(); service = new DefaultRefreshTokenService(refreshTokenStore, new DefaultEventService()); user = IdentityServerPrincipal.Create("bob", "Bob Loblaw"); }
public DefaultUserSessionTests() { _user = IdentityServerPrincipal.Create("123", "bob"); _subject = new DefaultUserSession(_mockHttpContext, _options, TestLogger.Create <DefaultUserSession>()); }
/// <summary> /// Initializes a new instance of the <see cref="ClaimsPrincipal"/> class with Claims from the Membership User /// </summary> /// <param name="user">Membership User</param> /// <param name="identityProvider">Identity Provider Name</param> /// <param name="claims">List of additional claims</param> /// <returns>Claims Principal</returns> public static ClaimsPrincipal Create(this MembershipUser user, string identityProvider, params Claim[] claims) { return(IdentityServerPrincipal.Create(user.GetSubjectId(), user.UserName, identityProvider, DateTime.Now, claims)); }
private async Task <string> GetToken(string userName, string audience) { var Request = new TokenCreationRequest(); var User = await _userManager.FindByNameAsync(userName); var IdentityPricipal = await _principalFactory.CreateAsync(User); var IdServerPrincipal = IdentityServerPrincipal.Create(User.Id.ToString(), User.UserName, IdentityPricipal.Claims.ToArray()); var lstScope = new List <Scope> { new Scope { Name = "api.main", Emphasize = true, UserClaims = new List <string> { "role", "name" } }, new Scope { Name = "api.blockchain", Emphasize = true, UserClaims = new List <string> { "role", "name" } } }; var c1 = new IdentityServer4.Models.Client { ClientId = "generatedTokenClient", ClientName = "generatedTokenClient", Enabled = true, AccessTokenType = AccessTokenType.Jwt, ClientSecrets = new List <IdentityServer4.Models.Secret> { new IdentityServer4.Models.Secret("21B5F798-BE55-42BC-8AA8-0025B903DC3B".Sha256()) } }; Request.Subject = IdServerPrincipal; Request.IncludeAllIdentityClaims = true; Request.ValidatedRequest = new ValidatedRequest(); Request.ValidatedRequest.Subject = Request.Subject; Request.ValidatedRequest.SetClient(c1); Request.Resources = new Resources(Config.GetIdentityResources(), Config.GetApiResources()); Request.ValidatedRequest.Options = _option; Request.ValidatedRequest.ClientClaims = IdentityPricipal.Claims.ToArray(); var Token = await _ts.CreateAccessTokenAsync(Request); Token.Issuer = "https://" + HttpContext.Request.Host.Value; Token.Audiences = new List <string> { audience }; if (Token.Claims == null) { Token.Claims = new List <Claim>(); } var rolesClaim = IdentityPricipal.FindAll("role"); if (rolesClaim != null && rolesClaim.Count() > 0) { foreach (var r1 in rolesClaim) { Token.Claims.Add(r1); } } var nameClaim = IdentityPricipal.FindFirst("name"); if (nameClaim != null) { Token.Claims.Add(nameClaim); } var custIdClaim = IdentityPricipal.FindFirst("customerid"); if (custIdClaim != null) { Token.Claims.Add(custIdClaim); } var TokenValue = await _ts.CreateSecurityTokenAsync(Token); return(TokenValue); }
/// <summary> /// Issues the login cookie for IdentityServer. /// </summary> /// <param name="env">The OWIN environment.</param> /// <param name="login">The login information.</param> /// <exception cref="System.ArgumentNullException"> /// env /// or /// login /// </exception> public static void IssueLoginCookie(this IDictionary <string, object> env, AuthenticatedLogin login, string partialSignInUrl = null, string loginId = null) { if (env == null) { throw new ArgumentNullException("env"); } if (login == null) { throw new ArgumentNullException("login"); } bool isPartial = !string.IsNullOrEmpty(partialSignInUrl); var options = env.ResolveDependency <IdentityServerOptions>(); var sessionCookie = env.ResolveDependency <SessionCookie>(); var context = new OwinContext(env); var props = new AuthenticationProperties(); //If the login id is empty, populate it from the request query. if (string.IsNullOrEmpty(loginId)) { var id = context.Request.Query.Get(Constants.Authentication.SigninQueryParamName); if (String.IsNullOrWhiteSpace(id)) { return; //We don't have a login id... Abort. } loginId = id; } // if false, then they're explicit in preventing a persistent cookie if (login.PersistentLogin != false) { if (login.PersistentLogin == true || options.AuthenticationOptions.CookieOptions.IsPersistent) { props.IsPersistent = true; if (login.PersistentLogin == true) { var expires = login.PersistentLoginExpiration ?? DateTimeHelper.UtcNow.Add(options.AuthenticationOptions.CookieOptions.RememberMeDuration); props.ExpiresUtc = expires; } } } //Populate the authentication metho and identity sources. var authenticationMethod = login.AuthenticationMethod; var identityProvider = login.IdentityProvider ?? Constants.BuiltInIdentityProvider; if (String.IsNullOrWhiteSpace(authenticationMethod)) { if (identityProvider == Constants.BuiltInIdentityProvider) { authenticationMethod = Constants.AuthenticationMethods.Password; } else { authenticationMethod = Constants.AuthenticationMethods.External; } } //Create the identity principal, setting the partial sign in if applicable. var user = IdentityServerPrincipal.Create(login.Subject, login.Name, authenticationMethod, identityProvider, isPartial ? Constants.PartialSignInAuthenticationType : Constants.PrimaryAuthenticationType); var identity = user.Identities.First(); var claims = login.Claims; if (claims != null && claims.Any()) { claims = claims.Where(x => !Constants.OidcProtocolClaimTypes.Contains(x.Type)); claims = claims.Where(x => x.Type != Constants.ClaimTypes.Name); identity.AddClaims(claims); } //Are we a partial sign in? if (isPartial) { // add claim so partial redirect can return here to continue login // we need a random ID to resume, and this will be the query string // to match a claim added. the claim added will be the original // signIn ID. var resumeId = IdentityModel.CryptoRandom.CreateUniqueId(); var resumeLoginUrl = context.GetPartialLoginResumeUrl(resumeId); var resumeLoginClaim = new Claim(Constants.ClaimTypes.PartialLoginReturnUrl, resumeLoginUrl); identity.AddClaim(resumeLoginClaim); identity.AddClaim(new Claim(String.Format(Constants.ClaimTypes.PartialLoginResumeId, resumeId), loginId)); // add url to start login process over again (which re-triggers preauthenticate) var restartUrl = context.GetPartialLoginRestartUrl(loginId); identity.AddClaim(new Claim(Constants.ClaimTypes.PartialLoginRestartUrl, restartUrl)); } else { //We are not - issue the session. sessionCookie.IssueSessionId(login.PersistentLogin, login.PersistentLoginExpiration); } context.Authentication.SignIn(props, identity); }