【发布时间】:2019-03-27 18:14:39
【问题描述】:
基本上我想做的事:
- 客户端(获取令牌,附加为元数据令牌并将其发送到不同的服务)--DONE
- 服务器端(获取令牌、验证发行者、日期和受众)--DONE
- 服务器端(验证令牌后,我想填充 AuthContext 的字段,以便我可以在我的 GrpcServices 中使用它们) -- 这里需要帮助
到目前为止,我设法从我的 tokenChallenge.GetClaimsPrincipal(token) 方法返回了 ClaimsPrinciple,但是我不确定如何填充 AuthContext。
我正在阅读documentation,我基本上需要一个服务器端的拦截器。
这是我目前的代码
public class AuthInterceptor: Interceptor
{
private readonly JwtTokenChallenger _tokenChallenger;
public AuthInterceptor(JwtTokenChallenger tokenChallenger)
{
_tokenChallenger = tokenChallenger;
}
public override Task<TResponse> UnaryServerHandler<TRequest, TResponse>(TRequest request, ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
Task<TResponse> response;
var isThisProtectedMethodAttribute = IsThisProtectedMethod(continuation.Target.GetType(), context);
if (isThisProtectedMethodAttribute == null) //only protected methods have attributes.
{
response = continuation(request, context);
return response;
}
//jwt token validation;
//populate auth context with claims principle?
var token = context.RequestHeaders.FirstOrDefault(h => h.Key == "authorization").Value.Split(" ").Last();
if (token == null)
{
context.Status = new Status(StatusCode.Unauthenticated, "Invalid token");
return default(Task<TResponse>);
}
if (ValidateToken(token))
{
PopulateAuthContext(token, context);
return continuation(request, context);
}
context.Status = new Status(StatusCode.Unauthenticated, "Invalid token");
return default(Task<TResponse>);
//test
}
private ProtectedMethod IsThisProtectedMethod(Type t, ServerCallContext context)
{
List<ProtectedMethod> returnAttributes = new List<ProtectedMethod>();
Attribute[] attrs = Attribute.GetCustomAttributes(t);
foreach (Attribute attr in attrs)
{
if (attr is ProtectedMethod a && (a.ProtectedResourceAcceessMethodName == context.Method.Split("/").Last()))
{
return a;
}
}
return null;
}
private bool ValidateToken(String tokenToValidate)
{
return _tokenChallenger.isValidToken(tokenToValidate);
}
private void PopulateAuthContext(String token, ServerCallContext context)
{
//help needed?
}
}
客户端我使用Java(Android),服务器端我使用C#
编辑:令牌有 2 个我想要的东西,名称标识符和角色
【问题讨论】:
标签: c# jwt interceptor grpc