asp.net-mvc - 使用 MVC 和 OAuthWebSecurity 登录 Twitter

标签 asp.net-mvc twitter asp.net-mvc-5

我有一个 MVC 5 Web 应用程序,在 Global.cs 中我有以下行:

OAuthWebSecurity.RegisterTwitterClient("123", "456");

我的 Controller 具有[Authorize]属性:

public class HomeController : Controller
{
    [Authorize]
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
}

当我加载页面时,我被带到 /Account/Login?ReturnUrl=%2f 这表明我的应用程序拒绝未经授权的请求并尝试重定向到默认值 Controller / Action 。

如何配置应用程序以重定向到 Twitter 应用程序登录页面?

最佳答案

我认为如果您更改了默认实现的 AccountController.Login 方法。

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
  ViewBag.ReturnUrl = returnUrl;
  return View();
}

对于这样的事情:

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
  return new ChallengeResult("Twitter",
                             Url.Action("ExternalLoginCallback", "Account",
                                        new { ReturnUrl = returnUrl }));
}

ChallengeResult 类由 MVC 模板生成,对我来说是这样的。

private class ChallengeResult : HttpUnauthorizedResult
{
  public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null)
  {
  }

  public ChallengeResult(string provider, string redirectUri, string userId)
  {
    LoginProvider = provider;
    RedirectUri = redirectUri;
    UserId = userId;
  }

  public string LoginProvider { get; set; }
  public string RedirectUri { get; set; }
  public string UserId { get; set; }

  public override void ExecuteResult(ControllerContext context)
  {
    var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
    if (UserId != null)
    {
      properties.Dictionary[XsrfKey] = UserId;
    }
    context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
  }
}

这样做的效果是当用户尝试登录时立即自动重定向到 Twitter,并且您将无法支持任何其他登录提供商。

您可能还需要对您的帐户页面进行一些更改,以删除为用户指定本地密码的功能(因为如果您不允许您的用户使用本地密码,则这样做没有任何意义)它)。

关于asp.net-mvc - 使用 MVC 和 OAuthWebSecurity 登录 Twitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27427902/

相关文章:

c# - 如何保持列表中数据的顺序

asp.net-mvc - 通过 .net MVC 调用 Go 命令

python - 如何获取特定时间范围内推文的twitter数据?

asp.net - 在mvc5中获取复选框值

c# - 参数类型不能分配给参数类型,尽管它继承

javascript - RequireJS - ASP.NET MVC 捆绑脚本

javascript - observablearray 中的对象 KnockoutJs

objective-c - 在 iOS 中使用 Twitter 登录用户...使用什么?

ios - 发送推文后应用卡住

c# - 使用异步 Controller 的强类型 RedirectToAction( future )