这是我使用的解决方案:
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。
答案很大,但我希望我能说清楚...如果您还有其他问题,请询问...