protected void gOAuthClients_RowSelected(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            ClientService clientService = new ClientService(OAuthContext);
            Client        client        = clientService.Get(e.RowKeyId);

            hfClientId.Value   = client.Id.ToString();
            tbClientName.Text  = client.ClientName;
            tbApiKey.Text      = client.ApiKey.ToString();
            tbApiSecret.Text   = client.ApiSecret.ToString();
            tbCallbackUrl.Text = client.CallbackUrl;
            cbActive.Checked   = client.Active;


            ClientScopeService clientScopeService = new ClientScopeService(OAuthContext);

            ScopeService scopeService = new ScopeService(OAuthContext);

            cblClientScopes.DataSource = scopeService.Queryable().Select(s => new { Id = s.Id, Value = s.Identifier + " - " + s.Description }).ToList();
            cblClientScopes.DataBind();

            clientScopeService.Queryable().Where(cs => cs.ClientId == client.Id).ToList().ForEach(cs =>
                                                                                                  cblClientScopes.Items.FindByValue(cs.ScopeId.ToString()).Selected = cs.Active
                                                                                                  );
            gOAuthClientEdit.Show();
        }
Exemple #2
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (OAuthSettings["OAuthRequireSsl"].AsBoolean() && Request.Url.Scheme.ToLower() != "https")
            {
                throw new Exception("OAuth requires SSL.");
            }

            CheckAcceptableDomain();

            // Log the user out
            if (!String.IsNullOrEmpty(PageParameter("OAuthLogout")))
            {
                var authentication = HttpContext.Current.GetOwinContext().Authentication;
                authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);
                Response.Redirect(OAuthSettings["OAuthLoginPath"] + "?logout=true&ReturnUrl=" + Server.UrlEncode(Request.RawUrl.Replace("&OAuthLogout=true", "")));
            }
            if (IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.Form.Get("__EVENTTARGET")) && Request.Form.Get("__EVENTTARGET") == btnGrant.UniqueID)
                {
                    if (CurrentUser != null)
                    {
                        OAuthContext  context       = new OAuthContext();
                        ClientService clientService = new ClientService(context);
                        Client        OAuthClient   = clientService.GetByApiKey(PageParameter(PageParameterKeys.ClientId).AsGuid());
                        if (OAuthClient != null && OAuthClient.Active == true)
                        {
                            ClientScopeService   clientScopeService   = new ClientScopeService(context);
                            AuthorizationService authorizationService = new AuthorizationService(context);

                            foreach (var clientScope in clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope))
                            {
                                var authorization = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLoginId == CurrentUser.Id && a.ScopeId == clientScope.Id).FirstOrDefault();
                                if (authorization == null)
                                {
                                    authorization = new org.secc.OAuth.Model.Authorization();
                                    authorizationService.Add(authorization);
                                }
                                authorization.Active      = true;
                                authorization.ClientId    = OAuthClient.Id;
                                authorization.UserLoginId = CurrentUser.Id;
                                authorization.ScopeId     = clientScope.Id;
                            }
                            context.SaveChanges();
                            Response.Redirect(Request.RawUrl);
                        }
                    }
                }
            }
        }
Exemple #3
0
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.File(@"c:\logs\CAIdentityServer.txt")
                         .CreateLogger();

            ClientScopeService clientscopeservice = new ClientScopeService();

            app.Map("/core", coreApp =>
            {
                var factory = new IdentityServerServiceFactory()
                              //.UseInMemoryClients(Clients.Get())
                              .UseInMemoryClients(clientscopeservice.GetCLients())
                              //.UseInMemoryScopes(Scopes.Get());
                              .UseInMemoryScopes(clientscopeservice.GetScopes());

                factory.UserService = new Registration <IUserService, MidasUserService>();



                factory.ConfigureClientStoreCache();
                factory.ConfigureScopeStoreCache();
                factory.ConfigureUserServiceCache();

                var options = new IdentityServerOptions
                {
                    SiteName = "IdentityServer3 - Custom Login Page",

                    SigningCertificate = Certificate.Get(),
                    Factory            = factory,

                    AuthenticationOptions = new AuthenticationOptions
                    {
                        EnableSignOutPrompt           = false,
                        RequireSignOutPrompt          = false,
                        EnablePostSignOutAutoRedirect = true
                    },

                    EventsOptions = new EventsOptions
                    {
                        RaiseSuccessEvents     = true,
                        RaiseErrorEvents       = true,
                        RaiseFailureEvents     = true,
                        RaiseInformationEvents = true
                    }
                };

                coreApp.UseIdentityServer(options);
            });
        }
        public TokenResponse GetToken(string clientid, string clientsecret, string username, string password)
        {
            string tokenEndPointUrl = Convert.ToString(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("TokenEndpointUrl"));

            TokenClient _tokenClient = new TokenClient(
                tokenEndPointUrl,
                clientid,
                clientsecret);

            ClientScopeService service = new ClientScopeService();
            string             scope   = service.GetClientScopes(clientid);
            var response = _tokenClient.RequestResourceOwnerPasswordAsync(username, password, scope).Result;

            return(response);
        }
Exemple #5
0
        private System.Threading.Tasks.Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (!string.IsNullOrEmpty(context.UserName) && !string.IsNullOrEmpty(context.Password))
            {
                var userLoginService = new UserLoginService(new RockContext());
                var userLogin        = userLoginService.GetByUserName(context.UserName);
                if (userLogin != null && userLogin.EntityType != null)
                {
                    var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name);
                    if (component != null && component.IsActive && !component.RequiresRemoteAuthentication)
                    {
                        if (component.Authenticate(userLogin, context.Password))
                        {
                            if ((userLogin.IsConfirmed ?? true) && !(userLogin.IsLockedOut ?? false))
                            {
                                OAuthContext         oAuthContext         = new OAuthContext();
                                ClientScopeService   clientScopeService   = new ClientScopeService(oAuthContext);
                                AuthorizationService authorizationService = new AuthorizationService(oAuthContext);
                                ClientService        clientService        = new ClientService(oAuthContext);

                                var scopes = (context.Scope.FirstOrDefault() ?? "").Split(',');

                                bool     scopesApproved   = false;
                                Client   OAuthClient      = clientService.GetByApiKey(context.ClientId.AsGuid());
                                string[] authorizedScopes = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLogin.UserName == context.UserName && a.Active == true).Select(a => a.Scope.Identifier).ToArray <string>();
                                if (!clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Any() ||
                                    (authorizedScopes != null && scopes.Where(s => !authorizedScopes.Select(a => a.ToLower()).Contains(s.ToLower())).Count() == 0))
                                {
                                    scopesApproved = true;
                                }

                                if (scopesApproved)
                                {
                                    var identity = new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType));

                                    //only allow claims that have been requested and the client has been authorized for
                                    foreach (var scope in scopes.Where(s => clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope.Identifier.ToLower()).Contains(s.ToLower())))
                                    {
                                        identity.AddClaim(new Claim("urn:oauth:scope", scope));
                                    }
                                    UserLoginService.UpdateLastLogin(context.UserName);
                                    context.Validated(identity);
                                    return(System.Threading.Tasks.Task.FromResult(0));
                                }
                                else
                                {
                                    context.SetError("Authentication Error", "All scopes are not authorized for this user.");
                                }
                            }
                            if (!userLogin.IsConfirmed ?? true)
                            {
                                context.SetError("Authentication Error", "Account email is unconfirmed.");
                            }
                            if (userLogin.IsLockedOut ?? false)
                            {
                                context.SetError("Authentication Error", "Account is locked.");
                            }
                        }
                        else
                        {
                            context.SetError("Authentication Error", "Invalid Username/Password.");
                        }
                    }
                    else
                    {
                        context.SetError("Authentication Error", "Invalid Authentication Configuration.");
                    }
                }
                else
                {
                    context.SetError("Authentication Error", "Invalid Username/Password.");
                }
            }
            else
            {
                context.SetError("Authentication Error", "Invalid Username/Password.");
            }

            context.Rejected();
            return(System.Threading.Tasks.Task.FromResult(0));
        }
        protected void gOAuthClientEdit_SaveClick(object sender, EventArgs e)
        {
            divErrors.Visible = false;
            if (String.IsNullOrEmpty(tbClientName.Text))
            {
                divErrors.InnerText = "A valid Client Name must be provided.";
                divErrors.Visible   = true;
                return;
            }
            if (tbApiKey.Text.AsGuidOrNull() == null)
            {
                divErrors.InnerText = "A valid GUID must be provided for the API Key.";
                divErrors.Visible   = true;
                return;
            }
            if (tbApiSecret.Text.AsGuidOrNull() == null)
            {
                divErrors.InnerText = "A valid GUID must be provided for the API Secret.";
                divErrors.Visible   = true;
                return;
            }
            if (string.IsNullOrEmpty(tbCallbackUrl.Text))
            {
                divErrors.InnerText = "A valid Callback URL must be provided.";
                divErrors.Visible   = true;
                return;
            }
            ClientScopeService clientScopeService = new ClientScopeService(OAuthContext);
            ClientService      clientService      = new ClientService(OAuthContext);
            Client             client             = null;

            if (hfClientId.Value.AsIntegerOrNull().HasValue)
            {
                client = clientService.Get(hfClientId.Value.AsInteger());
            }
            else
            {
                client = new Client();
                clientService.Add(client);
            }

            client.ClientName  = tbClientName.Text;
            client.ApiKey      = tbApiKey.Text.AsGuid();
            client.ApiSecret   = tbApiSecret.Text.AsGuid();
            client.CallbackUrl = tbCallbackUrl.Text;
            client.Active      = cbActive.Checked;

            foreach (System.Web.UI.WebControls.ListItem item in cblClientScopes.Items)
            {
                int         scopeId     = item.Value.AsInteger();
                ClientScope clientScope = clientScopeService.Queryable().Where(cs => cs.ClientId == client.Id && cs.ScopeId == scopeId).FirstOrDefault();
                if (clientScope != null)
                {
                    clientScope.Active = item.Selected;
                }
                else if (item.Selected)
                {
                    clientScope          = new ClientScope();
                    clientScope.ClientId = client.Id;
                    clientScope.ScopeId  = item.Value.AsInteger();
                    clientScope.Active   = item.Selected;
                    clientScopeService.Add(clientScope);
                }
            }
            OAuthContext.SaveChanges();
            OAuthContext = new OAuthContext();
            gOAuthClients_Bind(sender, e);
            gOAuthClientEdit.Hide();
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var    authentication = HttpContext.Current.GetOwinContext().Authentication;
            var    ticket         = authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie).Result;
            var    identity       = ticket != null ? ticket.Identity : null;
            string userName       = null;

            string[] authorizedScopes = null;
            var      scopes           = (Request.QueryString.Get("scope") ?? "").Split(' ');
            bool     scopesApproved   = false;

            if (identity == null)
            {
                authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);
                Response.Redirect(OAuthSettings["OAuthLoginPath"] + "?ReturnUrl=" + Server.UrlEncode(Request.RawUrl), true);
            }
            else if (CurrentUser == null)
            {
                // Kill the OAuth session
                authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);
                Response.Redirect(OAuthSettings["OAuthLoginPath"] + "?ReturnUrl=" + Server.UrlEncode(Request.RawUrl), true);
            }
            else
            {
                OAuthContext  context       = new OAuthContext();
                ClientService clientService = new ClientService(context);
                Client        OAuthClient   = clientService.GetByApiKey(PageParameter("client_id").AsGuid());
                if (OAuthClient != null)
                {
                    ClientScopeService clientScopeService = new ClientScopeService(context);

                    userName = identity.Name;
                    AuthorizationService authorizationService = new AuthorizationService(context);

                    authorizedScopes = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLogin.UserName == identity.Name && a.Active == true).Select(a => a.Scope.Identifier).ToArray <string>();
                    if (!clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Any() ||
                        (authorizedScopes != null && scopes.Where(s => !authorizedScopes.Select(a => a.ToLower()).Contains(s.ToLower())).Count() == 0))
                    {
                        scopesApproved = true;
                    }

                    if (scopesApproved)
                    {
                        identity = new ClaimsIdentity(identity.Claims, "Bearer", identity.NameClaimType, identity.RoleClaimType);

                        //only allow claims that have been requested and the client has been authorized for
                        foreach (var scope in scopes.Where(s => clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope.Identifier.ToLower()).Contains(s.ToLower())))
                        {
                            identity.AddClaim(new Claim("urn:oauth:scope", scope));
                        }
                        authentication.SignIn(identity);
                    }
                    else
                    {
                        rptScopes.DataSource = clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(s => s.Scope).ToList();
                        rptScopes.DataBind();
                    }

                    lClientName.Text     = OAuthClient.ClientName;
                    lClientName2.Text    = OAuthClient.ClientName;
                    lUsername.Text       = CurrentUser.Person.FullName + " (" + userName + ")";
                    hlLogout.NavigateUrl = Request.RawUrl + "&OAuthLogout=true";
                }
                else
                {
                    throw new Exception("Invalid Client ID for OAuth authentication.");
                }
            }
        }
Exemple #8
0
        private System.Threading.Tasks.Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            if (!string.IsNullOrEmpty(context.UserName) && !string.IsNullOrEmpty(context.Password))
            {
                var rockContext      = new RockContext();
                var userLoginService = new UserLoginService(rockContext);
                //Older Avalanche Clients use __PHONENUMBER__+1 prefix vs the newer SMS_ prefix
                //This makes sure we are using the new ROCK external sms authentication
                var userName = context.UserName.Replace("__PHONENUMBER__+1", "SMS_");

                //SMS login does not use the phone number as the username.
                //Instead we need to change it to use the person's id.
                if (userName.StartsWith("SMS_"))
                {
                    string error;
                    var    smsAuthentication = new SMSAuthentication();
                    var    person            = smsAuthentication.GetNumberOwner(userName.Split('_').Last(), rockContext, out error);
                    if (person != null)
                    {
                        userName = string.Format("SMS_{0}", person.Id);
                    }
                    //If we cannot find a person, do nothing and just pass through the existing username
                }
                var userLogin = userLoginService.GetByUserName(userName);
                if (userLogin != null && userLogin.EntityType != null)
                {
                    var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name);
                    if (component != null && component.IsActive &&
                        (!component.RequiresRemoteAuthentication || component.TypeName == "Rock.Security.ExternalAuthentication.SMSAuthentication"))
                    {
                        if (component.Authenticate(userLogin, context.Password))
                        {
                            if ((userLogin.IsConfirmed ?? true) && !(userLogin.IsLockedOut ?? false))
                            {
                                OAuthContext         oAuthContext         = new OAuthContext();
                                ClientScopeService   clientScopeService   = new ClientScopeService(oAuthContext);
                                AuthorizationService authorizationService = new AuthorizationService(oAuthContext);
                                ClientService        clientService        = new ClientService(oAuthContext);

                                var scopes = (context.Scope.FirstOrDefault() ?? "").Split(',');

                                bool     scopesApproved   = false;
                                Client   OAuthClient      = clientService.GetByApiKey(context.ClientId.AsGuid());
                                string[] authorizedScopes = authorizationService.Queryable().Where(a => a.Client.Id == OAuthClient.Id && a.UserLogin.UserName == userName && a.Active == true).Select(a => a.Scope.Identifier).ToArray <string>();
                                if (!clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Any() ||
                                    (authorizedScopes != null && scopes.Where(s => !authorizedScopes.Select(a => a.ToLower()).Contains(s.ToLower())).Count() == 0))
                                {
                                    scopesApproved = true;
                                }

                                if (scopesApproved)
                                {
                                    var identity = new ClaimsIdentity(new GenericIdentity(userName, OAuthDefaults.AuthenticationType));

                                    //only allow claims that have been requested and the client has been authorized for
                                    foreach (var scope in scopes.Where(s => clientScopeService.Queryable().Where(cs => cs.ClientId == OAuthClient.Id && cs.Active == true).Select(cs => cs.Scope.Identifier.ToLower()).Contains(s.ToLower())))
                                    {
                                        identity.AddClaim(new Claim("urn:oauth:scope", scope));
                                    }
                                    UserLoginService.UpdateLastLogin(userName);
                                    context.Validated(identity);
                                    return(System.Threading.Tasks.Task.FromResult(0));
                                }
                                else
                                {
                                    context.Rejected();
                                    context.SetError("Authentication Error", "All scopes are not authorized for this user.");
                                }
                            }
                            if (!userLogin.IsConfirmed ?? true)
                            {
                                context.Rejected();
                                context.SetError("Authentication Error", "Account email is unconfirmed.");
                            }
                            if (userLogin.IsLockedOut ?? false)
                            {
                                context.Rejected();
                                context.SetError("Authentication Error", "Account is locked.");
                            }
                        }
                        else
                        {
                            context.Rejected();
                            context.SetError("Authentication Error", "Invalid Username/Password.");
                        }
                    }
                    else
                    {
                        context.Rejected();
                        context.SetError("Authentication Error", "Invalid Authentication Configuration.");
                    }
                }
                else
                {
                    context.Rejected();
                    context.SetError("Authentication Error", "Invalid Username/Password.");
                }
            }
            else
            {
                context.Rejected();
                context.SetError("Authentication Error", "Invalid Username/Password.");
            }

            return(System.Threading.Tasks.Task.FromResult(0));
        }