简体   繁体   中英

External authentication in ASP.NET core Web API and Angular Client

I have an angular application that uses asp.net core Web API. I need to add external authentication for google and facebook sign in so that my web and mobile application can use this web api to authenticate users. I have gone through the documents and tutorials provided for this like this one and also this but none of them are helping me because my web application is on Angular 5.

My actual problem is how to get URL that redirects me to Google or facebook sign in page.

Mostly all of them use scafolded Asp.net mvc application where there is a controller: AccountController with Methods ExternalLogins

GET /api/Account/ExternalLogins?returnUrl=%2F&generateState=true

and they say the response will be a json like this:

   [{"name":"Facebook",
  "url":"/api/Account/ExternalLogin?provider=Facebook&response_type=token&client_id=self&redirect_uri=http%3A%2F%2Flocalhost%3A15359%2F&state=QotufgXRptkAfJvcthIOWBnGZydgVkZWsx8YrQepeDk1",
  "state":"QotufgXRptkAfJvcthIOWBnGZydgVkZWsx8YrQepeDk1"}]

This JSON is exactly what I need because i need a URL like that to open facebook or google login page. The links above use scaffolded projects and every code written there already that works great for Asp.net web application. But in my case, I have started the web api from scratch and my web application is Angular 5. Also if I tried a scafolded web api project but I could not find any controller called AccountController, nor any Method called ExternalLogins to get the JSON that contains provider name and login page url. It looks like the way its done has been changed in .net core 2. The first link above has shown two ways to include GoogleAuthentication in startup class file for Asp.net core 1 and Asp.net Core 2. So there must be something I am missing.

I am using Asp.net core 2. I have already got Api keys and secrets and added to startup class file.

I hope I am clear enough.

Please tell me if I need to elaborate more.

Please help. Thanks.

You need to create Challenge for Google Authentication in one of your Controller in API and redirect from angular app to that API Controller.

Controller Method

    [HttpGet("ExternalLogin")]
    public IActionResult ExternalLogin(string provider)
    {
        if (provider == null)
        {
            return null;
        }

        var properties = new AuthenticationProperties { RedirectUri = "www.mydomain.com/api/auth/callback" };
        var response = Challenge(properties, provider);
        return response;
    }

component method called on click of google sign in button

externalLogin(provider:string){
this.document.location.href = this.baseAPIUrl + 'auth/externallogin?provider='+provider;
}

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