简体   繁体   English

ASP.NET WEB API外部登录

[英]ASP.NET WEB API External Login

I have used Visual Studio 2013 project wizard to create WEB API project in ASP.NET. 我已使用Visual Studio 2013项目向导在ASP.NET中创建WEB API项目。 It created this function for social login: 它为社交登录创建了此功能:

// GET api/Account/ExternalLogin
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
[Route("ExternalLogin", Name = "ExternalLogin")]
public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{
    if (error != null)
    {
        return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
    }

    if (!User.Identity.IsAuthenticated)
    {
        return new ChallengeResult(provider, this);
    }

    ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

    if (externalLogin == null)
    {
        return InternalServerError();
    }

    if (externalLogin.LoginProvider != provider)
    {
        Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        return new ChallengeResult(provider, this);
    }

    ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
        externalLogin.ProviderKey));

    bool hasRegistered = user != null;

    if (hasRegistered)
    {
        Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

         ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
            OAuthDefaults.AuthenticationType);
        ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
            CookieAuthenticationDefaults.AuthenticationType);

        AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
        Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
    }
    else
    {
        IEnumerable<Claim> claims = externalLogin.GetClaims();
        ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
        Authentication.SignIn(identity);
    }

    return Ok();
}

Then I wrote a client side code in C# to call this function: 然后,我用C#编写了一个客户端代码来调用此函数:

public async Task LogInAsync(string url, string provider)
{
    using (HttpClient client = new HttpClient())
    {
      string request = url + "/api/Account/ExternalLogin";
      var query = HttpUtility.ParseQueryString(string.Empty);
      query["provider"] = provider;
      query["error"] = "";
      request += "?" + query.ToString();

      HttpResponseMessage responseMessage = await client.GetAsync(request);
      if (responseMessage.IsSuccessStatusCode)
      {
        string responseContent = await responseMessage.Content.ReadAsStringAsync();
      }
    }
}

Strangely enough, I receive this error response from server: 奇怪的是,我从服务器收到以下错误响应:

StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache StatusCode:400,ReasonPhrase:“ Bad Request”,版本:1.1,内容:System.Net.Http.StreamContent,标头:{Pragma:no-cache
X-SourceFiles: =?UTF-8?B?RTpcUHJvamVjdFxEYXRpbmdcRGF0aW5nLlNlcnZlclxhcGlcQWNjb3VudFxFeHRlcm5hbExvZ2lu?= Cache-Control: no-cache Date: Tue, 08 Nov 2016 15:12:33 GMT X-SourceFiles:=?UTF-8?B?RTpcUHJvamVjdFxEYXRpbmdcRGF0aW5nLlNlcnZlclxhcGlcQWNjb3VudFxFeHRlcm5hbExvZ2lu?= Cache-Control:no-cache Date:Tue,08 Nov 2016 15:12:
Server: Microsoft-IIS/8.0 X-Powered-By: ASP.NET Content-Length: 24 Content-Type: text/plain; 服务器:Microsoft-IIS / 8.0 X-Powered:ASP.NET内容长度:24内容类型:文本/纯文本; charset=UTF-8 Expires: -1 } charset = UTF-8过期:-1}

Same error appears when I try to navigate respective link in web browser. 当我尝试在Web浏览器中导航各个链接时,会出现相同的错误。 On server debugging, the respective entry point for this function is not hit. 在服务器调试中,未单击该功能的相应入口点。 What I m doing wrong? 我做错了什么? It is GET verb, so I should be able to access it in either way successfully. 它是GET动词,所以我应该能够成功地以任何一种方式访问​​它。

What puzzles me most, this function is included by default in every WEB API project around and yet, I cannot find any references or mentioning how people use it in practice. 最让我感到困惑的是,此功能默认包含在每个WEB API项目中,但是,我找不到任何引用或提及人们在实践中如何使用它。

Since you're using one of the templates, I'm assuming your project uses a derived OAuthAuthorizationServerProvider with several overridden methods. 由于您使用的是模板之一,因此我假设您的项目使用具有多个重写方法的派生OAuthAuthorizationServerProvider Drop some breakpoints in those, because that's probably where it's failing. 在其中删除一些断点,因为这可能是失败的地方。

By default , the OAuthServerOptions have the following : 默认情况下,OAuthServerOptions具有以下内容:

AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin")

Just get rid of that line, and your ExternalLOgin end point will work as it should to. 只需摆脱那条线,您的ExternalLOgin端点将可以正常工作。

File: Startup.Auth.cs 文件:Startup.Auth.cs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM