简体   繁体   中英

ASP.NET WEB API External Login

I have used Visual Studio 2013 project wizard to create WEB API project in ASP.NET. 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:

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
X-SourceFiles: =?UTF-8?B?RTpcUHJvamVjdFxEYXRpbmdcRGF0aW5nLlNlcnZlclxhcGlcQWNjb3VudFxFeHRlcm5hbExvZ2lu?= Cache-Control: no-cache Date: Tue, 08 Nov 2016 15:12:33 GMT
Server: Microsoft-IIS/8.0 X-Powered-By: ASP.NET Content-Length: 24 Content-Type: text/plain; charset=UTF-8 Expires: -1 }

Same error appears when I try to navigate respective link in web browser. 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.

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.

Since you're using one of the templates, I'm assuming your project uses a derived OAuthAuthorizationServerProvider with several overridden methods. Drop some breakpoints in those, because that's probably where it's failing.

By default , the OAuthServerOptions have the following :

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

Just get rid of that line, and your ExternalLOgin end point will work as it should to.

File: Startup.Auth.cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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