Asp.net web api 具有外部JWT身份验证微服务的.NET核心授权属性?

Asp.net web api 具有外部JWT身份验证微服务的.NET核心授权属性?,asp.net-web-api,authorization,asp.net-core,jwt,microservices,Asp.net Web Api,Authorization,Asp.net Core,Jwt,Microservices,因此,我只是有点难以理解.NET核心[Authorize]属性 我有一个正在运行的身份验证服务(比如authapi.com),当提供有效的身份验证详细信息时,它将返回一个JWT。当这个JWT被返回给它时,它将验证JWT并返回一条消息,指示这样做 因此,我现在正在构建另一个WebAPI(比如说genericapi.com),它需要对某些操作/控制器进行授权。这个想法是,JWT将在请求的头中传递给genericapi,然后需要将它们传递给authapi.com,以验证它们 我尝试添加一个策略,但它很

因此,我只是有点难以理解.NET核心[Authorize]属性

我有一个正在运行的身份验证服务(比如
authapi.com
),当提供有效的身份验证详细信息时,它将返回一个JWT。当这个JWT被返回给它时,它将验证JWT并返回一条消息,指示这样做

因此,我现在正在构建另一个WebAPI(比如说
genericapi.com
),它需要对某些操作/控制器进行授权。这个想法是,JWT将在请求的头中传递给
genericapi
,然后需要将它们传递给
authapi.com
,以验证它们

我尝试添加一个策略,但它很快就变得复杂起来,我不得不在所有内容上编写
[Authorize(Policy=“TokenValid”)]
,而我宁愿只使用默认的
[Authorize]
,因为所有授权都必须点击
authapi

我如何从标题中获取JWT并将其作为
[Authorize]
的标准行为传递给
authapi


请记住:我不想在
genericapi
上对JWTs做任何事情,所有身份验证都将由
authapi

处理,您可以尝试自定义默认的
JWTBeareAuthenticationMiddleware
为其提供一个自定义的
ISecurityTokenValidator
。您的用户身份将由中间件自动设置,您可以继续在MVC中使用
Authorize
属性:

class MyTokenValidator : ISecurityTokenValidator
{
    public string AuthenticationScheme { get; }

    public MyTokenValidator(string authenticationScheme)
    {
        AuthenticationScheme = authenticationScheme;
    }

    public bool CanValidateToken => true;

    public int MaximumTokenSizeInBytes
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }

    public bool CanReadToken(string securityToken) => true;

    public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
    {
        validatedToken = null;

        //your logic here
        var response = GetResponseFromMyAuthServer(securityToken);
        //assuming response will contain info about the user

        if(response == null || response.IsError)
            throw new SecurityTokenException("invalid");

        //create your identity by generating its claims
        var claims = new[]
        {
            new Claim(ClaimTypes.NameIdentifier, response.UserId),
            new Claim(ClaimTypes.Email, response.Email),
            new Claim(ClaimsIdentity.DefaultNameClaimType, response.UserName),
        };

        return new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationScheme));
    }
}
在你的创业课上:

var options = new JwtBearerOptions();
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new MyTokenValidator(options.AuthenticationScheme));

app.UseJwtBearerAuthentication(options);

//the rest of your code here
app.UseMvc();

您可能需要进一步完善此方法,但通过这种方式,您可以通过将所有验证委托给远程端点来实现所需的功能。

据我所知,您不希望在
genericapi
中使用
JWTBeareAuthentication
。在这种情况下,您可以为
genericapi
编写自定义身份验证中间件(将jwt发送到
authapi
并进行验证,然后设置当前用户)。然后只需使用
[Authorize]
属性

要编写自定义身份验证中间件,请查看

但是如果可能的话,我不会按照你的方式去做。我将使用
JwtBearerAuthentication
进行
genericapi
。然后我将使用
OnTokenValidated
事件来处理其他验证

        app.UseJwtBearerAuthentication(new JwtBearerOptions()
        {
            Events = new JwtBearerEvents()
            {
                OnTokenValidated = (context) =>
                {
                    // send jwt to auth api
                    // validate it
                    if (!valid)
                    {
                        context.SkipToNextMiddleware();
                    }
                    return Task.FromResult(0);
                }
            }
        });

事实上,你已经基本确定了我的目标,我想我误解了JWTBeareAuthentication的作用。我现在再检查一遍,看看。