我按照ASP.NET核心文档中的步骤将Facebook / Google登录添加到我的应用程序中:
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/
它完美无缺。
问题是我希望有一个Ionic 2客户端应用程序(使用Angular 2)和一个ASP.NET Core API作为后端。
在文档中,在配置社交媒体中间件后,他们的登录按钮会在MVC应用程序中神奇地显示。
由于ASP.NET Core MVC应用程序和WebAPI本质上是相同的,我想我可以使用这个例子,只需更改前端。
我阅读了很多关于身份验证,身份服务器4,JWT,OpenID等的内容,但这是一个非常广泛的主题,我迷失在专注于研究的内容上......
到目前为止,根据我的理解,我需要Ionic应用程序与社交提供商进行身份验证。这将生成一个令牌,我应该将其传递给API,然后API将使用社交提供程序验证此令牌以授予对其内容的访问权限。这个流程是否正确?我如何验证API中收到的令牌?
答案 0 :(得分:2)
这是我使用的解决方案:
1)有2个身份验证级别 - 离子应用程序 - API
2)当用户登录应用程序时,我使用Firebase身份验证,如果一切正常,则会向我返回一个令牌。此时,用户在应用程序上进行了身份验证,并保存了对API调用的令牌。
3)当用户需要访问任何资源时,将会调用API。此调用也需要某种身份验证,因为API不公开。
4)我得到了保存在(2)上的令牌,我把它放在我的http请求的标题中:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authentication', `${my-saved-token}`);
let options = new RequestOptions({ headers: headers });
return this.http.get(url, options)
.toPromise()
.then( .... )
5)在服务器端(我使用ASP.NET Core),我创建了一个自定义中间件,它读取每个请求的标题并查找“身份验证”。键。如果不存在,则只返回401错误,否则验证令牌,如果有效,则将请求发送到管道中的下一个中间件。此处未显示验证服务,但我使用了此答案的代码:Firebase authentication asp.net core
public class AuthenticationValidatorMiddleware
{
private readonly RequestDelegate _next;
private ITokenValidation TokenValidator { get; set; }
public AuthenticationValidatorMiddleware(RequestDelegate next, ITokenValidation tokenValidator)
{
_next = next;
TokenValidator = tokenValidator;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Headers.Keys.Contains("Authentication"))
{
context.Response.StatusCode = 400; //Bad Request
await context.Response.WriteAsync("Authentication is missing");
return;
}
else
{
var token = context.Request.Headers["authentication"];
if (!TokenValidator.Validate(token))
{
context.Response.StatusCode = 401; //UnAuthorized
await context.Response.WriteAsync("Invalid authentication");
return;
}
}
await _next.Invoke(context);
}
}
在客户端应用程序上,我使用AngularFire2进行身份验证,但请记住,在使用Firebase + AngularFire2时,Ionic 2不支持他们提供的登录方法。
要解决此问题,您必须使用cordova-plugin-inappbrowser
和cordova-plugin-facebook4
。然后,您将通过Facebook插件登录应用程序,获取Facebook身份验证令牌,然后使用此令牌登录Firebase。这是我的登录方法:
public signInWithFacebook(): firebase.Promise<any>
{
if (this.platformService.is('cordova'))
{
return Facebook.login(['email', 'public_profile']).then(res =>
{
const facebookCredential = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
return firebase.auth().signInWithCredential(facebookCredential);
});
}
else
{
return this.firebaseAuthenticationService.login(
{
provider: AuthProviders.Facebook,
method: AuthMethods.Popup
});
}
}
正如您在上面的代码中看到的,如果我检测到我在浏览器上运行,我使用原生的AngularFire2身份验证,如果我在设备上运行,那么我通过Facebook登录cordova插件,凭据然后将其传递给Firebase。
答案很大,但我希望我能说清楚......如果你有任何进一步的问题,请问......