如果asp.net mvc5应用程序中的hangfire授权失败,则重定向到错误页面

时间:2017-04-05 18:20:24

标签: c# asp.net-mvc hangfire

我们是否可以将尝试浏览hangfire网址的用户重定向到某些未经授权的网页。 我正在使用ASP.net mvc 5。 我在startup.cs文件中有以下页面。

 public void Configuration(IAppBuilder app)
        {
            String conn = System.Configuration.ConfigurationManager.
    ConnectionStrings["conn"].ConnectionString;
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            GlobalConfiguration.Configuration
               .UseSqlServerStorage(conn,
               new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) });

            //BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!"));

            //app.UseHangfireDashboard();

            app.UseHangfireDashboard("/Admin/hangfire", new DashboardOptions
            {
                Authorization =new[] { new DashboardAuthorizationFilter() }
            });
            //app.MapHangfireDashboard("/hangfire", new[] { new AuthorizationFilter() });
            app.UseHangfireServer();
            //start hangfire recurring jobs
            HangFireServices service = new HangFireServices();
            //service.StartArchive();
            service.StartDelete();
        }

HangFireServices有工作:

public void StartDelete()
        {
            List<KeyValuePair<string, int>> c = _service.GetServiceRetention();

            foreach (var obj in c)
            {
                  RecurringJob.AddOrUpdate(DELETE_SERVICE + obj.Key, () =>
                  Delete(obj.Key), //this is my function that does the actual process
               Cron.DayInterval(Convert.ToInt32(obj.Value)));
            }
        }

授权码是:

public class DashboardAuthorizationFilter : IDashboardAuthorizationFilter
    {
        public bool Authorize(DashboardContext context)
        {
            //TODO:Implement

                return false;
        }
    }

默认页面是主页,其上设置了不同的授权类。用户根据db失败了授权规则,并被重定向到UnAuthorizedController索引页面。如果用户手动更改url指向/ hangfire,因为返回的授权是false,它会看到一个空白页面,但我想重定向到UnAuthorizedController索引页面。

1 个答案:

答案 0 :(得分:0)

如果您想重定向到控制器上的特定页面,那么这可能会有所帮助。

我使用登录方法创建了一个帐户控制器,如下所示:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl = "jobs")
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

            var user = await UserManager.FindByNameAsync(model.UserName);

            await SignInManager.SignInAsync(user, false, false);        

            var virtualDirectory = Request.ApplicationPath.Equals("/") ? "/" : Request.ApplicationPath + "/";       

            return Redirect(virtualDirectory + returnUrl);
        }

        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
    }

在我的Startup.Auth.cs中,我做了以下更改:

        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>
             (ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>
              (ApplicationSignInManager.Create);


            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieName = "TestService",
                LoginPath = new PathString("/Account/Login"),
                SlidingExpiration = true,
                ExpireTimeSpan = TimeSpan.FromMinutes(20000),
                Provider = new CookieAuthenticationProvider()
            });
        }

最后,在startup.cs类中:

public partial class Startup
    {    
        public void Configuration(IAppBuilder app)
        {

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });


            LogProvider.SetCurrentLogProvider(new HangfireLogProvider());

            GlobalConfiguration.Configuration.UseSqlServerStorage("HangfirePersistence");

            app.UseHangfireDashboard("/jobs", new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthFilter() }
            });

            app.UseHangfireServer();

            ConfigureAuth(app);
        }
    }

public class HangfireAuthFilter : IDashboardAuthorizationFilter
{
    public bool Authorize(DashboardContext context)
    {
        var user = HttpContext.Current.User;

        return user != null && user.IsInRole("Admin") && user.Identity.IsAuthenticated;
    }
}

如果您未经过身份验证,您将被重定向到帐户控制器上的登录操作。