public static StoredGrant CreateRefreshTokenHandle(
            string subject,
            Client client,
            Application application,
            IEnumerable<Claim> claims,
            IEnumerable<Scope> scopes,
            DateTime expiration,
            bool createRefreshToken = false)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (application == null) throw new ArgumentNullException("application");
            if (claims == null) throw new ArgumentNullException("claims");
            if (scopes == null) throw new ArgumentNullException("scopes");

            return new StoredGrant
            {
                Type = StoredGrantType.RefreshTokenIdentifier,
                Subject = subject,
                Client = client,
                Application = application,
                ResourceOwner = claims.ToStoredGrantClaims().ToList(),
                Scopes = scopes.ToList(),
                Created = DateTime.UtcNow,
                Expiration = expiration,
                CreateRefreshToken = createRefreshToken
            };
        }
        public static StoredGrant CreateAuthorizationCode(
            Client client, 
            Application application, 
            string redirectUri, 
            IEnumerable<Claim> claims, 
            IEnumerable<Scope> scopes, 
            bool createRefreshToken,
            DateTime? refreshTokenExpiration = null,
            DateTime? expiration = null)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (application == null) throw new ArgumentNullException("application");
            if (claims == null) throw new ArgumentNullException("claims");
            if (scopes == null) throw new ArgumentNullException("scopes");

            return new StoredGrant
            {
                Type = StoredGrantType.AuthorizationCode,
                Client = client,
                Application = application,
                RedirectUri = redirectUri,
                ResourceOwner = claims.ToStoredGrantClaims().ToList(),
                Scopes = scopes.ToList(),
                Created = DateTime.UtcNow,
                Expiration = DateTime.UtcNow.AddHours(1),
                CreateRefreshToken = createRefreshToken,
                RefreshTokenExpiration = createRefreshToken ? refreshTokenExpiration : null
            };
        }
        public StoredGrant Find(string subject, Client client, Application application, IEnumerable<Scope> scopes, StoredGrantType type)
        {
            var grants = db.StoredGrants.Where(h => h.Subject == subject &&
                                                             h.Client.ClientId == client.ClientId &&
                                                             h.Application.ID == application.ID &&
                                                             h.Type == type).ToList();

            return grants.FirstOrDefault(grant => grant.Scopes.ScopeEquals(scopes));
        }
        public static TokenHandle CreateConsentDecisionHandle(string subject, Client client, Application application, IEnumerable<Scope> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (application == null) throw new ArgumentNullException("application");
            if (scopes == null) throw new ArgumentNullException("scopes");

            return new TokenHandle
            {
                Type = TokenHandleType.ConsentDecision,
                Subject = subject,
                Client = client,
                Application = application, 
                Scopes = scopes.ToList(),
                Created = DateTime.UtcNow
            };
        }
        public static StoredGrant CreateConsentDecision(string subject, Client client, Application application, IEnumerable<Scope> scopes)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (application == null) throw new ArgumentNullException("application");
            if (scopes == null) throw new ArgumentNullException("scopes");

            return new StoredGrant
            {
                Type = StoredGrantType.ConsentDecision,
                Subject = subject,
                Client = client,
                Application = application, 
                Scopes = scopes.ToList(),
                Created = DateTime.UtcNow,
                Expiration = DateTime.UtcNow.AddYears(5)
            };
        }
        public static void PopulateDefaultData(Application app, IAuthorizationServerAdministration config)
        {
            var currentRememberOptions = app.RememberOptions;

            if (currentRememberOptions.Count > 0)
            {
                foreach (var remb in currentRememberOptions.ToArray())
                {
                    config.RememberOptions.Remove(remb);
                }
                config.SaveChanges();
            }

            var rememberOptions = CreateRememberOptions();

            foreach (var r in rememberOptions)
            {
                app.RememberOptions.Add(r);
            }

            config.SaveChanges();
        }
        public static void Populate()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AuthorizationServerContext>());

            try
            {
                var db = DependencyResolver.Current.GetService<AuthorizationServerContext>();

                var resourceOwnerClient = db.Clients.Find("roclient");
                var CodeClient = db.Clients.Find("codeclient");
                var ImplicitClient = db.Clients.Find("implicitclient");
                var client = db.Clients.Find("client");
                var assertionClient = db.Clients.Find("assertionclient");

                if (client == null)
                {
                    client = new Client
                    {
                        Enabled = true,
                        Name = "Client",
                        ClientId = "client",
                        Flow = OAuthFlow.Client
                    };
                    client.SetSharedSecret("secret");
                    db.Clients.Add(client);
                    db.SaveChanges();
                }

                if (assertionClient == null)
                {
                    assertionClient = new Client
                    {
                        Enabled = true,
                        Name = "Assertion Client",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                        ClientId = "assertionclient",
                        Flow = OAuthFlow.Assertion
                    };
                    assertionClient.SetSharedSecret("secret");
                    db.Clients.Add(assertionClient);
                    db.SaveChanges();
                }

                if (resourceOwnerClient == null)
                {
                    resourceOwnerClient = new Client
                    {
                        Enabled = true,
                        Name = "Resource Owner Flow Client",
                        ClientId = "roclient",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                        Flow = OAuthFlow.ResourceOwner,
                        AllowRefreshToken = true
                    };
                    resourceOwnerClient.SetSharedSecret("secret");
                    db.Clients.Add(resourceOwnerClient);
                    db.SaveChanges();
                }
                if (CodeClient == null)
                {
                    CodeClient = new Client
                    {
                        Enabled = true,
                        Name = "Code Flow Client",
                        ClientId = "codeclient",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                        AllowRefreshToken = true,
                        Flow = OAuthFlow.Code,

                        RedirectUris = new List<ClientRedirectUri> 
                        {
                            new ClientRedirectUri
                            {
                                Uri = "https://prod.local",
                                Description = "Production"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://test.local",
                                Description = "Test"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://localhost:44303/callback",
                                Description = "Local Test"
                            }
                        }
                    };
                    CodeClient.SetSharedSecret("secret");
                    db.Clients.Add(CodeClient);
                    db.SaveChanges();
                }
                if (ImplicitClient == null)
                {
                    ImplicitClient = new Client
                    {
                        Enabled = true,
                        Name = "Implicit Flow Client",
                        ClientId = "implicitclient",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                        AllowRefreshToken = false,
                        Flow = OAuthFlow.Implicit,

                        RedirectUris = new List<ClientRedirectUri>
                        {
                            new ClientRedirectUri
                            {
                                Uri = "https://test2.local",
                                Description = "Test"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://localhost:44300/callback.cshtml",
                                Description = "JavaScript Callback Page"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "ms-app://s-1-15-2-4224567138-2162094511-1976135278-3909242924-69295690-1380993013-1329561029/",
                                Description = "Win Store App"
                            }
                        }
                    };
                    ImplicitClient.SetSharedSecret("secret");
                    db.Clients.Add(ImplicitClient);
                    db.SaveChanges();
                }

                //if (!db.SigningKeys.Any())
                //{
                //    db.SigningKeys.Add(new X509CertificateReference
                //    {
                //        Name = "Default X509 Cert",
                //        Location = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                //        FindValue = "CN=idsrv.local",
                //        FindType = System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectDistinguishedName,
                //        StoreName = System.Security.Cryptography.X509Certificates.StoreName.My
                //    });
                //    db.SaveChanges();
                //}

                if (!db.Applications.Any())
                {
                    var readScope = new Scope
                    {
                        AllowedClients = new List<Client> { CodeClient, ImplicitClient, resourceOwnerClient, client, assertionClient },
                        Name = "read",
                        DisplayName = "Read data",
                        Description = "Allows to read data",
                        Emphasize = false
                    };

                    var searchScope = new Scope
                    {
                        AllowedClients = new List<Client> { CodeClient, resourceOwnerClient },
                        Name = "search",
                        DisplayName = "Search data",
                        Description = "Allows to search for data",
                        Emphasize = false
                    };

                    var writeScope = new Scope
                    {
                        AllowedClients = new List<Client> { resourceOwnerClient },
                        Name = "write",
                        DisplayName = "Write data",
                        Description = "Allows to write data",
                        Emphasize = true
                    };

                    var key = new SymmetricKey { Name = "Demo signing key" };
                    key.SetValue(Convert.FromBase64String("1fTiS2clmPTUlNcpwYzd5i4AEFJ2DEsd8TcUsllmaKQ="));

                    var application = new Application
                    {
                        Enabled = true,
                        Name = "User management",
                        Namespace = "users",
                        Audience = "users",
                        Description = "This app manages your users",
                        LogoUrl = "http://en.opensuse.org/images/0/0b/Icon-user.png",
                        Scopes = new List<Scope> { readScope, searchScope, writeScope },
                        RequireConsent = true,
                        TokenLifetime = 60,
                        AllowRefreshToken = true,
                        AllowRememberConsentDecision = true,
                        SigningKey = key
                    };
                    
                    db.Applications.Add(application);
                    db.SaveChanges();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
 public StoredGrant Find(string subject, Client client, Application application, System.Collections.Generic.IEnumerable<Scope> scopes, StoredGrantType type)
 {
     throw new System.NotImplementedException();
 }
        static void Main(string[] args)
        {
            using (var db = new EFAuthorizationServerConfigurationContext())
            {
                db.Database.Delete();
            }

            using (var db = new EFAuthorizationServerConfigurationContext())
            {
                Console.WriteLine(db.Database.Connection.ConnectionString);

                if (!db.SigningKeys.Any())
                {
                    db.SigningKeys.Add(new X509CertificateReference
                    {
                        Location = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                        FindType = System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectDistinguishedName,
                        StoreName = System.Security.Cryptography.X509Certificates.StoreName.My,
                        FindValue = "CN=sts"
                    });
                    db.SigningKeys.Add(new SymmetricKey { Value = new byte[] { 1, 2, 3, 4 } });
                    db.SaveChanges();
                }

                if (!db.Clients.Any())
                {
                    var client1 = new Client
                    {
                        ClientId = "client1",
                        Name = "Test Client1",
                        RedirectUris = new List<ClientRedirectUri>()
                        {
                            new ClientRedirectUri{ Description = "Test1", Uri = "http://test1"}
                        }
                    };
                    var client2 = new Client
                    {
                        ClientId = "client2",
                        Name = "Test Client2",
                        RedirectUris = new List<ClientRedirectUri>()
                        {
                            new ClientRedirectUri{ Description = "Test2", Uri = "http://test2"}
                        }
                    };
                    db.Clients.Add(client1);
                    db.Clients.Add(client2);
                    db.SaveChanges();
                }

                //var c1 = db.Clients.Find("client1");
                //if (c1 != null)
                //{
                //    db.Clients.Remove(c1);
                //    db.SaveChanges();
                //}

                if (!db.Applications.Any())
                {
                    var c1 = db.Clients.OrderBy(x => x.ClientId).Skip(0).Take(1).First();
                    var c2 = db.Clients.OrderBy(x => x.ClientId).Skip(1).Take(1).First();
                    var key = db.SigningKeys.First();

                    var app = new Application
                    {
                        Name = "Test App",
                        Scopes = new List<Scope>()
                        {
                            new Scope{ Name = "edit", 
                                AllowedClients = new List<Client>{c1} },
                            new Scope{ Name = "view", 
                                AllowedClients = new List<Client>{c2} },
                        },
                        SigningKey = key
                       
                    };
                    db.Applications.Add(app);
                    db.SaveChanges();
                }

                var a1 = db.Applications.First();
                if (a1 != null)
                {
                    foreach (var c in a1.Clients)
                    {
                        Console.WriteLine(c.Name);
                    }
                    if (a1.SigningKey != null)
                    {
                        var creds = a1.SigningKey.GetSigningCredentials();
                    }

                    //db.Applications.Remove(a1);
                    //db.SaveChanges();
                }

                //var client = db.Clients.First();
                //if (client != null)
                //{
                //    db.Clients.Remove(client);
                //    db.SaveChanges();
                //}
            }
        }
 private static List<RememberOption> GetRememberOptions(Application application)
 {
     return (from r in application.RememberOptions
         orderby (r.Value == -1 ? int.MaxValue : r.Value)
         select r).ToList();
 }
        public HttpResponseMessage Post(ApplicationModel model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            if (this.config.Applications.All.Any(x => x.Namespace == model.Namespace))
            {
                ModelState.AddModelError("", "That Namespace is already in use.");
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }
            if (this.config.Applications.All.Any(x => x.Audience == model.Audience))
            {
                ModelState.AddModelError("", "That Audience is already in use.");
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
            }

            var app = new Application();
            app.Name = model.Name;
            app.Description = model.Description;
            app.LogoUrl = model.LogoUrl;
            app.Namespace = model.Namespace;
            app.Audience = model.Audience;
            app.TokenLifetime = model.TokenLifetime;
            app.AllowRefreshToken = model.AllowRefreshToken;
            app.RequireConsent = model.RequireConsent;
            app.AllowRememberConsentDecision = model.RememberConsentDecision;
            app.SigningKey = config.Keys.All.Single(x => x.ID == model.SigningKeyID);
            app.Enabled = model.Enabled;

            config.Applications.Add(app);
            config.SaveChanges();

            return Request.CreateResponse(HttpStatusCode.OK, new { ID = app.ID });
        }
        public ValidatedRequest Validate(Application application, TokenRequest request, ClaimsPrincipal clientPrincipal)
        {
            var validatedRequest = new ValidatedRequest();

            // validate request model binding
            if (request == null)
            {
                throw new TokenRequestValidationException(
                    "Invalid request parameters.",
                    OAuthConstants.Errors.InvalidRequest);
            }

            validatedRequest.Application = application;
            Tracing.InformationFormat("OAuth2 application: {0} ({1})",
                validatedRequest.Application.Name,
                validatedRequest.Application.Namespace);

            // grant type is required
            if (string.IsNullOrWhiteSpace(request.Grant_Type))
            {
                throw new TokenRequestValidationException(
                    "Missing grant_type",
                    OAuthConstants.Errors.UnsupportedGrantType);
            }

            validatedRequest.GrantType = request.Grant_Type;
            Tracing.Information("Grant type: " + validatedRequest.GrantType);

            // validate client credentials
            var client = ValidateClient(clientPrincipal, validatedRequest.Application);
            if (client == null)
            {
                throw new TokenRequestValidationException(
                    "Invalid client: " + ClaimsPrincipal.Current.Identity.Name,
                    OAuthConstants.Errors.InvalidClient);
            }

            validatedRequest.Client = client;
            Tracing.InformationFormat("Client: {0} ({1})",
                validatedRequest.Client.Name,
                validatedRequest.Client.ClientId);

            switch (request.Grant_Type)
            {
                case OAuthConstants.GrantTypes.AuthorizationCode:
                    ValidateCodeGrant(validatedRequest, request);
                    break;
                case OAuthConstants.GrantTypes.Password:
                    ValidatePasswordGrant(validatedRequest, request);
                    break;
                case OAuthConstants.GrantTypes.RefreshToken:
                    ValidateRefreshTokenGrant(validatedRequest, request);
                    break;
                case OAuthConstants.GrantTypes.ClientCredentials:
                    ValidateClientCredentialsGrant(validatedRequest, request);
                    break;
                default:
                    throw new TokenRequestValidationException(
                        "Invalid grant_type: " + request.Grant_Type,
                        OAuthConstants.Errors.UnsupportedGrantType);
            }

            Tracing.Information("Token request validation successful.");
            return validatedRequest;
        }
        private Client ValidateClient(ClaimsPrincipal clientPrincipal, Application application)
        {
            if (clientPrincipal == null || !clientPrincipal.Identity.IsAuthenticated)
            {
                Tracing.Error("Anonymous client.");
                return null;
            }

            var passwordClaim = clientPrincipal.FindFirst("password");
            if (passwordClaim == null)
            {
                Tracing.Error("No client secret provided.");
                return null;
            }

            return application.Clients.ValidateClient(
                clientPrincipal.Identity.Name,
                passwordClaim.Value);
        }
 public TokenHandle Find(string subject, Client client, Application application, System.Collections.Generic.IEnumerable<Scope> scopes, TokenHandleType type)
 {
     throw new System.NotImplementedException();
 }
        private Client ValidateClient(ClaimsPrincipal clientPrincipal, Application application)
        {
            if (clientPrincipal == null || !clientPrincipal.Identity.IsAuthenticated)
            {
                Tracing.Error("Anonymous client.");
                return null;
            }

            var clientIdClaim = clientPrincipal.FindFirst("client_id");
            if (clientIdClaim == null)
            {
                Tracing.Error("No client_id provided.");
                return null;
            }

            var passwordClaim = clientPrincipal.FindFirst("secret");
            if (passwordClaim == null)
            {
                Tracing.Error("No client secret provided.");
                return null;
            }

            var client = _clientManager.Get(clientIdClaim.Value);
            if (client == null)
            {
                Tracing.Error("Unable to find client in repository.");
                return null;
            }

            if (!client.ValidateSharedSecret(passwordClaim.Value))
            {
                Tracing.Error("Invalid client secret.");
                return null;
            }

            return client;
        }
        public void Init()
        {
            DataProtectection.Instance = new NoProtection();
            globalConfiguration = new GlobalConfiguration() { Issuer = "Test Issuer" };

            rocv = new Mock<IResourceOwnerCredentialValidation>();
            config = new Mock<IAuthorizationServerConfiguration>();
            handleManager = new Mock<IStoredGrantManager>();
            assertionGrantValidator = new Mock<IAssertionGrantValidation>();
            clientManager = new Mock<IClientManager>();

            tokenService = new TokenService(globalConfiguration);


            #region Setup Test Client
            string secret = "12345678";
            byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(secret);
            string base64EncodedSecret = Convert.ToBase64String(encodedByte);
            _Client = new Client()
            {
                ClientId = "MobileAppShop",
                ClientSecret = base64EncodedSecret,
                Flow = OAuthFlow.ResourceOwner,
                AllowRefreshToken = true
            };
            #endregion

            #region Setup Test Application
            var scope = new Scope();
            scope.Name = "read";
            scope.AllowedClients = new List<Client>();
            scope.AllowedClients.Add(_Client);
            _Scopes = new List<Scope>();
            _Scopes.Add(scope);

            string symmetricKey = "C33333333333333333333333335=";
            byte[] keybytes = Convert.FromBase64String(symmetricKey);
            SecurityKey securityKey = new InMemorySymmetricSecurityKey(keybytes);
            _Application = new Application()
            {
                Name = "Test Application 1",
                Scopes = _Scopes,
                Audience = "Test Audience",
                TokenLifetime = 1,
                AllowRefreshToken = true,
            };
            #endregion

            #region Setup Example StoredGrant
            Claim[] resourceOwnerClaims = { new Claim("Username", "JohnSmith"), new Claim("sub", "JohnSmith") };
            _StoredGrant = new StoredGrant() 
            { 
                GrantId = "MyFavouriteRefrehToken1234",
                CreateRefreshToken = true,
                Client = _Client,
                ResourceOwner = resourceOwnerClaims.ToStoredGrantClaims().ToList(),
                Expiration = DateTime.Now.AddDays(1),
                RefreshTokenExpiration = DateTime.Now.AddMonths(1),
                Type = StoredGrantType.RefreshTokenIdentifier,
                Scopes = _Scopes,
                Application = _Application
            };
            #endregion

            #region Setup Mocking Objects
            // IAuthorizationServerConfiguration
            config.Setup(x => x.FindApplication(It.IsNotNull<string>()))
                .Returns((string name) =>
                {
                    return _Application;
                });
            config.Setup(x => x.GlobalConfiguration).Returns(() => globalConfiguration);

            // IClientManager
            clientManager.Setup(x => x.Get(It.IsNotNull<string>()))
                .Returns((string clientId) =>
                {
                    return _Client;
                });

            // IResourceOwnerCredentialValidation
            rocv.Setup(x => x.Validate(It.IsNotNull<string>(), It.IsNotNull<string>()))
                .Returns((string username, string password) =>
                {
                    return Principal.Create("Test", resourceOwnerClaims);
                });

            // IStoredGrantManager
            handleManager.Setup(x => x.Get(It.IsNotNull<string>()))
                .Returns((string grantIdentifier) => 
                {
                    return _StoredGrant;
                });

            #endregion

            _TokenController = new TokenController(
                rocv.Object,
                config.Object,
                handleManager.Object,
                assertionGrantValidator.Object,
                tokenService,
                clientManager.Object);
            _TokenController.Request = new HttpRequestMessage();
            _TokenController.Request.SetConfiguration(new HttpConfiguration());
        }
        public ValidatedRequest Validate(Application application, AuthorizeRequest request)
        {
            // If the request fails due to a missing, invalid, or mismatching
            // redirection URI, or if the client identifier is missing or invalid,
            // the authorization server SHOULD inform the resource owner of the
            // error and MUST NOT automatically redirect the user-agent to the
            // invalid redirection URI.

            var validatedRequest = new ValidatedRequest();

            // validate request model binding
            if (request == null)
            {
                throw new AuthorizeRequestResourceOwnerException("Invalid request parameters.");
            }

            validatedRequest.Application = application;
            Tracing.InformationFormat("OAuth2 application: {0} ({1})",
                validatedRequest.Application.Name,
                validatedRequest.Application.Namespace);

            validatedRequest.ShowRememberConsent = application.AllowRememberConsentDecision;

            // make sure redirect uri is present
            if (string.IsNullOrWhiteSpace(request.redirect_uri))
            {
                throw new AuthorizeRequestResourceOwnerException("Missing redirect URI");
            }

            // validate client
            if (string.IsNullOrWhiteSpace(request.client_id))
            {
                throw new AuthorizeRequestResourceOwnerException("Missing client identifier");
            }


            var client = _clientManager.Get(request.client_id);
            if (client == null)
            {
                throw new AuthorizeRequestResourceOwnerException("Invalid client: " + request.client_id);
            }

            validatedRequest.Client = client;
            Tracing.InformationFormat("Client: {0} ({1})",
                validatedRequest.Client.Name,
                validatedRequest.Client.ClientId);

            // make sure redirect_uri is a valid uri, and in case of http is over ssl
            Uri redirectUri;
            if (Uri.TryCreate(request.redirect_uri, UriKind.Absolute, out redirectUri))
            {
                if (redirectUri.Scheme == Uri.UriSchemeHttp)
                {
                    throw new AuthorizeRequestClientException(
                        "Redirect URI not over SSL : " + request.redirect_uri,
                        new Uri(request.redirect_uri),
                        OAuthConstants.Errors.InvalidRequest,
                        string.Empty,
                        validatedRequest.State);
                }

                // make sure redirect uri is registered with client
                var validUri = validatedRequest.Client.RedirectUris.Get(request.redirect_uri);

                if (validUri == null)
                {
                    throw new AuthorizeRequestResourceOwnerException("Invalid redirect URI: " + request.redirect_uri);
                }

                validatedRequest.RedirectUri = validUri;
                Tracing.InformationFormat("Redirect URI: {0} ({1})",
                    validatedRequest.RedirectUri.Uri,
                    validatedRequest.RedirectUri.Description);
            }
            else
            {
                var message = "Invalid redirect URI: " + request.redirect_uri;
                Tracing.Error(message);

                throw new AuthorizeRequestResourceOwnerException("Invalid redirect URI: " + request.redirect_uri);
            }

            // check state
            if (!string.IsNullOrWhiteSpace(request.state))
            {
                validatedRequest.State = request.state;
                Tracing.Information("State: " + validatedRequest.State);
            }
            else
            {
                Tracing.Information("No state supplied.");
            }

            // validate response type
            if (String.IsNullOrWhiteSpace(request.response_type))
            {
                throw new AuthorizeRequestClientException(
                    "response_type is null or empty",
                    new Uri(validatedRequest.RedirectUri.Uri),
                    OAuthConstants.Errors.InvalidRequest,
                    string.Empty,
                    validatedRequest.State);
            }

            // check response type (only code and token are supported)
            if (!request.response_type.Equals(OAuthConstants.ResponseTypes.Token, StringComparison.Ordinal) &&
                !request.response_type.Equals(OAuthConstants.ResponseTypes.Code, StringComparison.Ordinal))
            {
                throw new AuthorizeRequestClientException(
                    "response_type is not token or code: " + request.response_type,
                    new Uri(validatedRequest.RedirectUri.Uri),
                    OAuthConstants.Errors.UnsupportedResponseType,
                    string.Empty,
                    validatedRequest.State);
            }

            validatedRequest.ResponseType = request.response_type;
            Tracing.Information("Response type: " + validatedRequest.ResponseType);

            if (request.response_type == OAuthConstants.ResponseTypes.Code)
            {
                ValidateCodeResponseType(validatedRequest, request);
            }
            else if (request.response_type == OAuthConstants.ResponseTypes.Token)
            {
                ValidateTokenResponseType(validatedRequest, request);
            }
            else
            {
                throw new AuthorizeRequestClientException(
                    "Invalid response_type: " + request.response_type,
                    new Uri(validatedRequest.RedirectUri.Uri),
                    OAuthConstants.Errors.UnsupportedResponseType,
                    request.response_type,
                    validatedRequest.State);
            }

            ValidateScopes(request, validatedRequest);

            // TODO: fix based upon past "remember me" settings
            validatedRequest.ShowConsent = client.RequireConsent || application.RequireConsent;

            Tracing.Information("Authorize request validation successful.");
            return validatedRequest;
        }
        private void PopulateData()
        {
            var resourceOwnerClient = new Client
            {
                Name = "Resource Owner Flow Client",
                ClientId = "roclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                Flow = OAuthFlow.ResourceOwner,
                AllowRefreshToken = true
            };

            var CodeClient = new Client
            {
                Name = "Code Flow Client",
                ClientId = "codeclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = true,
                Flow = OAuthFlow.Code,

                RedirectUris = new RedirectUris 
                    {
                        new RedirectUri
                        {
                            Uri = "https://prod.local",
                            Description = "Production"
                        },
                        new RedirectUri
                        {
                            Uri = "https://test.local",
                            Description = "Test"
                        }
                    }
            };

            var ImplicitClient = new Client
            {
                Name = "Implicit Flow Client",
                ClientId = "implicitclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = false,
                Flow = OAuthFlow.Implicit,

                RedirectUris = new RedirectUris 
                    {
                        new RedirectUri
                        {
                            Uri = "https://test2.local",
                            Description = "Test"
                        }
                    }
            };

            var readScope = new Scope
            {
                AllowedClients = new Clients { CodeClient, ImplicitClient, resourceOwnerClient },
                Name = "read",
                Description = "Read data",
                Emphasize = false
            };

            var searchScope = new Scope
            {
                AllowedClients = new Clients { CodeClient, resourceOwnerClient },
                Name = "search",
                Description = "Search data",
                Emphasize = false
            };

            var writeScope = new Scope
            {
                AllowedClients = new Clients { resourceOwnerClient },
                Name = "write",
                Description = "write data",
                Emphasize = true
            };

            var application = new Application
            {
                Name = "User management",
                Namespace = "users",
                Scopes = new Scopes { readScope, searchScope, writeScope },
                Clients = new Clients { CodeClient, ImplicitClient, resourceOwnerClient },
                ShowConsent = true,
                TokenLifetime = 60
            };

            _applications.Add(application);
        }
        private void PopulateData()
        {
            var resourceOwnerClient = new Client
            {
                Name = "Resource Owner Flow Client",
                ClientId = "roclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                Flow = OAuthFlow.ResourceOwner,
                AllowRefreshToken = true
            };

            var codeClient = new Client
            {
                Name = "Code Flow Client",
                ClientId = "codeclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = true,
                Flow = OAuthFlow.Code,

                RedirectUris = new List<ClientRedirectUri>
                    {
                        new ClientRedirectUri
                        {
                            Uri = "https://prod.local",
                            Description = "Production"
                        },
                        new ClientRedirectUri
                        {
                            Uri = "https://test.local",
                            Description = "Test"
                        }
                    }
            };

            var implicitClient = new Client
            {
                Name = "Implicit Flow Client",
                ClientId = "implicitclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = false,
                Flow = OAuthFlow.Implicit,

                RedirectUris = new List<ClientRedirectUri> 
                    {
                        new ClientRedirectUri
                        {
                            Uri = "https://test2.local",
                            Description = "Test"
                        }
                    }
            };

            var trustedClient = new Client
            {
                Name = "Trusted Client",
                ClientId = "trustedclient",
                ClientSecret = "secret",
                AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                AllowRefreshToken = false,
                Flow = OAuthFlow.ResourceOwner,
            };

            var readScope = new Scope
            {
                AllowedClients = new List<Client> { codeClient, implicitClient, resourceOwnerClient },
                Name = "read",
                Description = "Read data",
                Emphasize = false
            };

            var browseScope = new Scope
            {
                AllowedClients = new List<Client> { codeClient, implicitClient, resourceOwnerClient },
                Name = "browse",
                Description = "Browse data",
                Emphasize = false
            };

            var searchScope = new Scope
            {
                AllowedClients = new List<Client> { codeClient, resourceOwnerClient },
                Name = "search",
                Description = "Search data",
                Emphasize = false
            };

            var writeScope = new Scope
            {
                AllowedClients = new List<Client> { resourceOwnerClient },
                Name = "write",
                Description = "write data",
                Emphasize = true
            };

            var deleteScope = new Scope
            {
                AllowedClients = new List<Client> { trustedClient },
                Name = "delete",
                Description = "delete data",
                Emphasize = true
            };

            var application = new Application
            {
                Name = "Test Application",
                Namespace = "test",
                Scopes = new List<Scope> { readScope, browseScope, searchScope, writeScope, deleteScope },
                RequireConsent = true,
                TokenLifetime = 60
            };
            
            _applications.Add(application);
        }
        public static void Populate()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AuthorizationServerContext>());

            try
            {
                var db = DependencyResolver.Current.GetService<Thinktecture.AuthorizationServer.EF.AuthorizationServerContext>();
                if (!db.GlobalConfiguration.Any())
                {
                    var config = new GlobalConfiguration
                    {
                        AuthorizationServerName = "Thinktecture AuthorizationServer",
                        Issuer = "ThinktectureAuthorizationServer",
                        Administrators = new List<AuthorizationServerAdministrator>
                            {
                                new AuthorizationServerAdministrator{NameID="dominick"},
                                new AuthorizationServerAdministrator{NameID="brock"},
                            }
                    };
                    db.GlobalConfiguration.Add(config);
                    db.SaveChanges();
                }

                var resourceOwnerClient = db.Clients.Find("roclient");
                var CodeClient = db.Clients.Find("codeclient");
                var ImplicitClient = db.Clients.Find("implicitclient");
                var client = db.Clients.Find("client");

                if (client == null)
                {
                    client = new Client
                    {
                        Enabled = true,
                        Name = "Client",
                        ClientId = "client",
                        ClientSecret = "secret",
                        Flow = OAuthFlow.Client
                    };
                    db.Clients.Add(client);
                    db.SaveChanges();
                }

                if (resourceOwnerClient == null)
                {
                    resourceOwnerClient = new Client
                    {
                        Enabled = true,
                        Name = "Resource Owner Flow Client",
                        ClientId = "roclient",
                        ClientSecret = "secret",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,
                        Flow = OAuthFlow.ResourceOwner,
                        AllowRefreshToken = true
                    };
                    db.Clients.Add(resourceOwnerClient);
                    db.SaveChanges();
                }
                if (CodeClient == null)
                {
                    CodeClient = new Client
                    {
                        Enabled = true,
                        Name = "Code Flow Client",
                        ClientId = "codeclient",
                        ClientSecret = "secret",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                        AllowRefreshToken = true,
                        Flow = OAuthFlow.Code,

                        RedirectUris = new List<ClientRedirectUri> 
                        {
                            new ClientRedirectUri
                            {
                                Uri = "https://prod.local",
                                Description = "Production"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://test.local",
                                Description = "Test"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "https://localhost:44303/callback",
                                Description = "Local Test"
                            }
                        }
                    };
                    db.Clients.Add(CodeClient);
                    db.SaveChanges();
                }
                if (ImplicitClient == null)
                {
                    ImplicitClient = new Client
                    {
                        Enabled = true,
                        Name = "Implicit Flow Client",
                        ClientId = "implicitclient",
                        ClientSecret = "secret",
                        AuthenticationMethod = ClientAuthenticationMethod.SharedSecret,

                        AllowRefreshToken = false,
                        Flow = OAuthFlow.Implicit,

                        RedirectUris = new List<ClientRedirectUri>
                        {
                            new ClientRedirectUri
                            {
                                Uri = "https://test2.local",
                                Description = "Test"
                            },
                            new ClientRedirectUri
                            {
                                Uri = "ms-app://s-1-15-2-4224567138-2162094511-1976135278-3909242924-69295690-1380993013-1329561029/",
                                Description = "Win Store App"
                            }
                        }
                    };
                    db.Clients.Add(ImplicitClient);
                    db.SaveChanges();
                }

                if (!db.SigningKeys.Any())
                {
                    db.SigningKeys.Add(new X509CertificateReference
                    {
                        Name = "Default X509 Cert",
                        Location = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                        FindValue = "CN=idsrv.local",
                        FindType = System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectDistinguishedName,
                        StoreName = System.Security.Cryptography.X509Certificates.StoreName.My
                    });
                    db.SaveChanges();
                }

                if (!db.Applications.Any())
                {
                    var readScope = new Scope
                    {
                        AllowedClients = new List<Client> { CodeClient, ImplicitClient, resourceOwnerClient, client },
                        Name = "read",
                        Description = "Read data",
                        Emphasize = false
                    };

                    var searchScope = new Scope
                    {
                        AllowedClients = new List<Client> { CodeClient, resourceOwnerClient },
                        Name = "search",
                        Description = "Search data",
                        Emphasize = false
                    };

                    var writeScope = new Scope
                    {
                        AllowedClients = new List<Client> { resourceOwnerClient },
                        Name = "write",
                        Description = "write data",
                        Emphasize = true
                    };

                    var application = new Application
                    {
                        Enabled = true,
                        Name = "User management",
                        Namespace = "users",
                        Audience = "users",
                        Description = "This app manages your users",
                        LogoUrl = "http://en.opensuse.org/images/0/0b/Icon-user.png",
                        Scopes = new List<Scope> { readScope, searchScope, writeScope },
                        RequireConsent = true,
                        TokenLifetime = 60,
                        AllowRefreshToken = true,
                        SigningKey = new SymmetricKey { Name="main signing key", Value = Convert.FromBase64String("1fTiS2clmPTUlNcpwYzd5i4AEFJ2DEsd8TcUsllmaKQ=") }
                    };
                    db.Applications.Add(application);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }