仅在prod中进行C#开放式身份验证

时间:2014-02-10 19:48:21

标签: c# .net openid google-openid

我正在使用带有VS2012的C#进行小型项目。我工作的项目是一个网站,要求用户通过开放ID(Facebook,谷歌等)登录。

在向网站添加身份验证后,我必须在测试和尝试之前登录。这是一种烦恼,对开发环境没有任何意义 有没有办法不进行身份验证或在开发中跳过它并仅在部署到生产的代码时添加它?

1 个答案:

答案 0 :(得分:1)

是的,有。但是,没有一个解决方案。根据您对用户进行身份验证的方式,解决方案可能会有所不同。一个想法是使用Preprocessor Directives。这样,您可以根据构建调试版本或发行版本来有条件地编译身份验证代码。

例如,在具有表单身份验证的MVC应用程序中,您可以使用:

//Define that we are debugging
#define DEBUG    

public ActionResult DoSomething()
{
    //Determine if this is a debug build
    //If it is, then we want to exclude the authentication verification
    //portion of the code

    //Include the code if DEBUG has not been defined
    #if !DEBUG
    if(!HttpContext.User.Identity.IsAuthenticated)
    {
       //Not authenticated
       return new HttpUnauthorizedResult();
    }
    #endif
    //Authenticated
    DoOtherStuff();
}

如您所见,HttpUnathorizedException仅在未定义DEBUG指令时抛出。即使用户可能未登录,也始终执行DoOtherStuff()

这种方法的问题在于,通常当您要求用户登录时,您需要他/她的帐户详细信息来执行某些操作。

例如:

public ActionResult Post(PostModel post)
{
    #if !DEBUG
    if(!HttpContext.User.Identity.IsAuthenticated)
    {
        return new HttpUnauthorizedResult();
    }
    #endif

    User user = GetLoggedInUser(); //Returns null because the user
                                   //is not authenticated

    Post createdPost = new Post
    {
       Title = post.Title,
       Content = post.Content,

       //Uh oh, the user is not logged in. This post will not have an author!
       Author = user,
       PostDate = DateTime.Now
    };

    DbContext.Posts.Add(createdPost);
    DbContext.SaveChanges();

    return View();
}

不同的解决方案将允许用户登录而无需实际登录。

例如:

public ActionResult LogIn(string username)
{
    #if !DEBUG
       //Require the user to actually login through OpenId
    #else
       //Don't require the user/dev to actually login, instead just give them access
       FormsAuthentication.SetAuthCookie(username, false);
    #endif
}

然后,当用户/ dev尝试访问某些内容时......

public ActionResult Post(PostModel post)
{
    // The user will be logged in because you just gave them the
    // authentication cookie
    if(!HttpContext.User.Identity.IsAuthenticated)
    {
        return new HttpUnauthorizedResponse();
    }
    else
    {
       User user = GetLoggedInUser(); //Returns user
       Post createdPost = new Post
       {
          //ect..
          User = user
       };

       // Save post

       return View();
    }
}

总的来回答你的问题:

  

有没有办法不进行身份验证或在开发中跳过它并仅在部署到生产的代码时添加它?

,但确切的解决方案取决于您的情况。