Beispiel #1
0
        public bool Authorize(DashboardContext context)
        {
            return(true);

            //todo
            var isLocal = context.GetHttpContext().Request.IsLocal();

            if (isLocal)
            {
                return(true);
            }

            var httpContext = context.GetHttpContext();

            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return(false);
            }

            if (!httpContext.User.HasClaim("Role", "Admin"))
            {
                return(false);
            }

            return(true);
        }
Beispiel #2
0
        public bool Authorize([NotNull] DashboardContext context)
        {
            var http = context.GetHttpContext();
            var jwt  = http.Request.Cookies["JWT_TOKEN"];

            if (jwt == "null")
            {
                return(false);
            }

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadToken(jwt) as JwtSecurityToken;

            if (token == null)
            {
                return(false);
            }

            var userID      = Int32.Parse(token.Claims.First(c => c.Type == "unique_name").Value);
            var userService = context.GetHttpContext().RequestServices.GetRequiredService <IUserService>();
            var user        = userService.GetById(userID);

            if (user != null)
            {
                return(true);
            }
            return(false);
        }
 public bool Authorize(DashboardContext context)
 {
     if (context.GetHttpContext().User.Identity.IsAuthenticated &&
         context.GetHttpContext().User.IsInRole("admin"))
     {
         return(true);
     }
     return(false);
 }
Beispiel #4
0
        public bool Authorize(DashboardContext context)
        {
            var httpcontext = context.GetHttpContext();

            if (httpcontext.User.Identity.IsAuthenticated /*.IsInRole("Admin")*/)
            {
                return(true);
            }
            var httpContext = context.GetHttpContext();

            httpContext.Response.Redirect("/Identity/Account/Login");
            // httpContext.Response.Redirect("/hangfire");
            return(true); //always return true
        }
        public bool Authorize([NotNull] DashboardContext context)
        {
            if (!context.GetHttpContext().User.Identity.IsAuthenticated)
            {
                return(false);
            }

            var userSub = context.GetHttpContext().User.FindFirst("sub").Value;

            return(new JoinableTaskFactory(new JoinableTaskContext()).Run(async delegate
            {
                return await _membershipService.ReadUserInGroupsAsync(userSub, new[] { _authorizationSettings.HangfireAuthorizationGroup });
            }));
        }
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            // if unknown, assume not local
            if (String.IsNullOrEmpty(context.Request.RemoteIpAddress))
            {
                return(false);
            }

            // check if localhost
            if (context.Request.RemoteIpAddress == "127.0.0.1" || context.Request.RemoteIpAddress == "::1")
            {
                return(true);
            }

            // compare with local address
            if (context.Request.RemoteIpAddress == context.Request.LocalIpAddress)
            {
                return(true);
            }

            return(httpContext.User.Identity.IsAuthenticated &&
                   httpContext.User.IsInRole(Constants.Roles.Admin));
        }
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            // Allow all authenticated users to see the Dashboard (potentially dangerous).
            return(httpContext.User.IsInRole(GlobalConstants.AdminRoleName));
        }
        public bool Authorize(DashboardContext context)
        {
            var http  = context.GetHttpContext();
            var token = _configuration.GetValue <string>("Hangfire:DashboardToken");

            var cookie = http.Request.Cookies.FirstOrDefault(w => w.Key == "hangfire:token");

            if (!string.IsNullOrEmpty(cookie.Value))
            {
                return(cookie.Value == token);
            }

            var key = http.Request.Query["token"].FirstOrDefault();

            if (key == null)
            {
                return(false);
            }

            if (key != token)
            {
                return(false);
            }

            http.Response.Cookies.Append("hangfire:token", token);

            return(true);
        }
Beispiel #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool Authorize([NotNull] DashboardContext context)
        {
            var httpcontext = context.GetHttpContext();
            var auth        = httpcontext.Request.Cookies?["Auth"];

            return(auth == AuthCode);
        }
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            // Allow all authenticated users to see the Dashboard (potentially dangerous).
            return(httpContext.User.Identity.IsAuthenticated); //allow access to any user
        }
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            // FIXME: This should be limited to admins
            return(httpContext.User.Identity.IsAuthenticated);
        }
        public bool Authorize([NotNull] DashboardContext dashboardContext)
        {
            var    context = dashboardContext.GetHttpContext();
            string header  = context.Request.Headers["Authorization"];

            if (String.IsNullOrWhiteSpace(header) == false)
            {
                AuthenticationHeaderValue authValues = AuthenticationHeaderValue.Parse(header);

                if ("Basic".Equals(authValues.Scheme, StringComparison.OrdinalIgnoreCase))
                {
                    string parameter = Encoding.UTF8.GetString(Convert.FromBase64String(authValues.Parameter));
                    var    parts     = parameter.Split(':');

                    if (parts.Length > 1)
                    {
                        string login    = parts[0];
                        string password = parts[1];

                        if ((String.IsNullOrWhiteSpace(login) == false) && (String.IsNullOrWhiteSpace(password) == false))
                        {
                            return(Username == login && Password == password);
                        }
                    }
                }
            }

            return(Challenge(context));
        }
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            // Allow only admins
            return(httpContext.User.IsInRole("Administrator"));
        }
        public bool Authorize([NotNull] DashboardContext context)
        {
            var httpContext = context.GetHttpContext();
            var authService = httpContext.RequestServices.GetRequiredService <IAuthorizationService>();

            return(authService.AuthorizeAsync(httpContext.User, this.policyName).ConfigureAwait(false).GetAwaiter().GetResult().Succeeded);
        }
Beispiel #15
0
        public bool Authorize([NotNull] DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            if (httpContext.Request.Query.TryGetValue("token", out var token) && token.Count == 1)
            {
                try
                {
                    var json = new JwtBuilder()
                               .DoNotVerifySignature()
                               .Decode <IDictionary <string, object> >(token.ToString());
                    var permission = json["permissions"] as JArray;
                    var iss        = json["iss"] as string;
                    return(iss == issuer && permission != null && permission.Contains(""));
                }
                catch (TokenExpiredException ex)
                {
                    Log.Error(ex, "Hangfire dashboard access denied because given token is expired.");
                }
                catch (SignatureVerificationException ex)
                {
                    Log.Error(ex, "Hangfire dashboard access denied because the given token is invalid (invalid signature).");
                }
            }

            return(false);
        }
            public bool Authorize(DashboardContext context)
            {
                var httpContext = context.GetHttpContext();

                string authHeader = httpContext.Request.Headers["Authorization"];

                if (authHeader != null && authHeader.StartsWith("Basic "))
                {
                    // Get the encoded username and password
                    var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1]?.Trim();

                    // Decode from Base64 to string
                    var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));

                    // Split username and password
                    var username = decodedUsernamePassword.Split(':', 2)[0];
                    var password = decodedUsernamePassword.Split(':', 2)[1];

                    // Check if login is correct
                    if (username == configuration["Hangfire:DashboardUsername"] && password == configuration["Hangfire:DashboardPassword"])
                    {
                        return(true);
                    }
                }

                // Return authentication type (causes browser to show login dialog)
                httpContext.Response.Headers["WWW-Authenticate"] = "Basic";

                // Return unauthorized
                httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;

                return(false);
            }
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            // Allow all authenticated users to see the Dashboard (potentially dangerous).
            return(true);
        }
Beispiel #18
0
        public bool Authorize([NotNull] DashboardContext context)
        {
            var httpContext = context.GetHttpContext();
            var useRole     = "HangfireOpenUser";// httpContext.User.FindFirst(ClaimTypes.Role)?.Value;

            return(useRole == AppRoles.RoleEnums.HangfireOpenUser.ToString());
        }
        public bool Authorize(DashboardContext context)
        {
            var    httpContext = context.GetHttpContext();
            Uri    baseUrl     = new Uri(configuration["WebAppUrl:Url"]);
            string url         = new Uri(baseUrl, "/pages/refreshhangfire").ToString();

            try
            {
                var access_token = String.Empty;
                var setCookie    = false;

                //Try to get token from query string
                if (httpContext.Request.Query.ContainsKey("access_token"))
                {
                    access_token = httpContext.Request.Query["access_token"].FirstOrDefault();
                    setCookie    = true;
                }
                else if (httpContext.Request.Cookies.ContainsKey(HangFireCookieName))
                {
                    access_token = httpContext.Request.Cookies[HangFireCookieName];
                }

                if (String.IsNullOrEmpty(access_token))
                {
                    httpContext.Response.Redirect(url, false);
                    return(true);
                }

                SecurityToken           validatedToken = null;
                JwtSecurityTokenHandler hand           = new JwtSecurityTokenHandler();
                var claims = hand.ValidateToken(access_token, this.tokenValidationParameters, out validatedToken);

                if (setCookie && claims?.Identity?.IsAuthenticated == true)
                {
                    if (httpContext.Request.Cookies.ContainsKey(HangFireCookieName))
                    {
                        httpContext.Response.Cookies.Delete(HangFireCookieName);
                    }

                    httpContext.Response.Cookies.Append(HangFireCookieName,
                                                        access_token,
                                                        new CookieOptions()
                    {
                        Expires = DateTime.Now.AddMinutes(CookieExpirationMinutes)
                    });
                }

                if (claims?.Identity?.IsAuthenticated == false)
                {
                    httpContext.Response.Redirect(url, false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                httpContext.Response.Redirect(url, false);
                return(true);
            }
        }
Beispiel #20
0
        public bool Authorize(DashboardContext context)
        {
            var httpContext  = context.GetHttpContext();
            var userIdentity = httpContext.User.Identity;

            if (userIdentity.IsAuthenticated)
            {
                var provider          = httpContext.RequestServices.GetRequiredService <ISharedXafApplicationProvider>();
                var blazorApplication = provider.Application;
                var security          = provider.Security;
                if (security.IsSecurityStrategyComplex())
                {
                    if (!security.IsActionPermissionGranted(nameof(JobSchedulerService.JobDashboard)) &&
                        !security.IsAdminPermissionGranted())
                    {
                        using var objectSpace = blazorApplication.CreateObjectSpace(security?.UserType);
                        var user = (ISecurityUserWithRoles)objectSpace.FindObject(security?.UserType, CriteriaOperator.Parse($"{nameof(ISecurityUser.UserName)}=?", userIdentity.Name));
                        return(user.Roles.Cast <IPermissionPolicyRole>().Any(role => role.IsAdministrative));
                    }
                    return(true);
                }
                return(true);
            }
            return(false);
        }
        public bool Authorize([NotNull] DashboardContext context)
        {
            var httpcontext = context.GetHttpContext();


            return(true);
        }
Beispiel #22
0
            public bool Authorize(DashboardContext context)
            {
                var httpContext = context.GetHttpContext();

                // Allow only the specified Characters to access
                return(httpContext.User.Identity.IsAuthenticated && httpContext.User.HasClaim("Admin", "true"));
            }
Beispiel #23
0
 string GetRequestBody(DashboardContext context)
 {
     using (var reader = new StreamReader(context.GetHttpContext().Request.Body))
     {
         return(reader.ReadToEnd());
     }
 }
Beispiel #24
0
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            // Allow all authenticated users to see the Dashboard (potentially dangerous).
            return(httpContext.User.Identity.IsAuthenticated); /*true;*/ // Never publish 'true' in production (use it for debug only) !!!!!!!!
        }
Beispiel #25
0
        public Task <bool> AuthorizeAsync(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();
            var authService = httpContext.RequestServices.GetRequiredService <IAuthManager>();

            return(authService.IsUserAdmin());
        }
Beispiel #26
0
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            //return httpContext.User.Identity.IsAuthenticated;
            return(true);
        }
Beispiel #27
0
        public bool Authorize(DashboardContext context)
        {
            var http = context.GetHttpContext();

            if (http.Request.Headers.ContainsKey("Authorization"))
            {
                var authObj = _processAuthHeader(http.Request.Headers["Authorization"].ToString());
                if (http.Request.QueryString.ToString().Contains("logout"))
                {
                    _redis.KeyDelete(CacheKey.HangfireDashboardAuthPrefix + authObj["opaque"]);
                    _redirect(http);
                    return(true);
                }
                if (authObj["username"] == _config["Hangfire:User"])
                {
                    var a1        = _md5(string.Format("{0}:Need Login:{1}", authObj["username"], _config["Hangfire:Pass"]));
                    var a2        = _md5(string.Format("{0}:{1}", http.Request.Method, authObj["uri"]));
                    var nonce     = _redis.StringGet(CacheKey.HangfireDashboardAuthPrefix + authObj["opaque"]);
                    var validCode = _md5(string.Format("{0}:{1}:{2}:{3}:{4}:{5}", a1, nonce, authObj["nc"], authObj["cnonce"], authObj["qop"], a2));
                    if (authObj["response"] == validCode)
                    {
                        _redis.StringSet(CacheKey.HangfireDashboardAuthPrefix + authObj["opaque"], nonce, new TimeSpan(0, 5, 0));
                        return(true);
                    }
                }
            }
            _challenge(http);
            return(false);
        }
Beispiel #28
0
        public bool Authorize(DashboardContext context)
        {
            //#if DEBUG
            //            // If we are in debug, always allow Hangfire access.
            //            return true;
            //#else
            //            var httpContext = context.GetHttpContext();
            //            var accessTokenHangfire = httpContext.Request.Cookies["accessTokenHangfire"];
            //            if (!string.IsNullOrEmpty(accessTokenHangfire))
            //            {
            //                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            //                JwtSecurityToken securityToken = handler.ReadToken(accessTokenHangfire) as JwtSecurityToken;
            //                bool result = securityToken.Claims.Where(claim => claim.Type == "roles").Select(x=>x.Value).Contains(_role);
            //                return result;
            //            }
            //            return false;
            //#endif


            var httpContext         = context.GetHttpContext();
            var accessTokenHangfire = httpContext.Request.Cookies["accessTokenHangfire"];

            if (!string.IsNullOrEmpty(accessTokenHangfire))
            {
                JwtSecurityTokenHandler handler       = new JwtSecurityTokenHandler();
                JwtSecurityToken        securityToken = handler.ReadToken(accessTokenHangfire) as JwtSecurityToken;
                bool result = securityToken.Claims.Where(claim => claim.Type == "roles").Select(x => x.Value).Contains(_role);
                return(result);
            }
            return(false);
        }
        public bool Authorize(DashboardContext context)
        {
            var httpContext = context.GetHttpContext();

            // Allow all authenticated users to see the Dashboard (potentially dangerous).
            return(httpContext.User.Identity.IsAuthenticated && httpContext.User.IsInRole("CEO"));
        }
        public bool Authorize([NotNull] DashboardContext context)
        {
            var httpContext = context.GetHttpContext();
            var result      = httpContext.Request.Cookies.TryGetValue("hangfire-key", out string value);

            return(result == true && value == "123");
        }