【发布时间】:2021-09-15 14:05:42
【问题描述】:
我在 asp.net 核心 Web 应用程序中实现了自定义身份验证路由,以创建和验证自定义令牌。虽然我能够创建自定义令牌,但我不确定如何在 Firestore 中使用该令牌,我的所有尝试都会导致 Firestore 的权限不正确。
如果我在 Firestore 中使用 rules playground 和解码的 JWT 违反我的规则,我可以成功读取包含自定义声明的文档,如果我在规则游乐场中修改自定义声明,我将无法阅读文档。
通过 firestore api playground 我也可以拨打电话,但在这种情况下我的规则完全被忽略了。
Firebase 身份验证
public class FirebaseAuthenticationMiddleware
{
private readonly RequestDelegate _next;
public FirebaseAuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, FirebaseSettings settings)
{
if (FirebaseAuth.DefaultInstance == null)
{
_ = FirebaseApp.Create(new AppOptions
{
Credential = GoogleCredential.FromJson(settings.ServicePrinciaplJson),
ServiceAccountId = settings.ServiceAccountId,
ProjectId = setting.ProjectId
});
}
await _next(context);
}
}
[HttpGet("{id}")]
public async Task<IActionResult> CreateToken(string id)
{
var token = await FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(id,
new Dictionary<string, object> {{"documentId", id}});
var response = await VerifyAccessTokenWithAuthority(token);
return Ok(response);
}
private async Task<CustomTokenResponse> VerifyAccessTokenWithAuthority(string accessCode)
{
CustomTokenRequest requestBody = new() {Token = accessCode};
using HttpClient client = new();
HttpRequestMessage requestMessage = new(HttpMethod.Post, _settings.Authority)
{
Content = new StringContent(
JsonSerializer.Serialize(requestBody,
new JsonSerializerOptions {PropertyNamingPolicy = JsonNamingPolicy.CamelCase}), Encoding.UTF8,
"application/json")
};
var response = await client.SendAsync(requestMessage);
var token = await response.Content.ReadAs<CustomTokenResponse>(new JsonSerializerOptions
{PropertyNamingPolicy = JsonNamingPolicy.CamelCase});
return token;
}
Firestore 请求(不同的 asp.net 核心客户端应用程序)
[HttpGet]
public async Task<IActionResult> GetPassenger(string passengerId)
{
var token = await _authorizationClient.AuthorizePassenger(passengerId);
using HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get,
$"https://firestore.googleapis.com/v1/projects/{_firebaseAuthSettings.ProjectId}/databases/(default)/documents/myCollection/{id}/?key={_firebaseAuthSettings.ApiKey}");
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.IdToken);
var response = await client.SendAsync(message);
if (!response.IsSuccessStatusCode)
{
return new StatusCodeResult((int) response.StatusCode);
}
var docs = await response.Content.ReadAsStringAsync();
return Ok(docs);
}
Firestore 规则
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /myCollection/{documentId} {
allow read: if request.auth.documentId == documentId
allow write: if request.auth.documentId == documentId
}
}
}
【问题讨论】:
标签: firebase google-cloud-firestore