【问题标题】:Validate an Access Token at the Resource Server and Respond Accordingly在资源服务器上验证访问令牌并做出相应响应
【发布时间】:2015-09-09 23:32:10
【问题描述】:

我们已经询问并收到了有关如何执行资源所有者密码凭据流程的答复。 Configure the authorization server endpoint我们能够从身份服务器接收访问令牌并将其存储在依赖方的数据存储中。

我们现在需要学习如何在资源服务器上验证访问令牌。

在我们的资源服务器的Startup 中,我们目前有这个:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication();
}

public void Configure(IApplicationBuilder app)
{
    // Add a new middleware validating access tokens issued by the server.
    app.UseOAuthBearerAuthentication(options =>
    {
        options.AutomaticAuthentication = true;
        options.Audience = "http://localhost:50000/";
        options.Authority = "http://localhost:50000/";
    });

    app.Run(async (context) =>
    {
        // this runs on each request not just per application startup
        await context.Response.WriteAsync(DateTime.Now.ToString() + 
            " Hello Resource Owner Password Flow...");
    });
}

我们需要在资源服务器中的控制器/操作中添加什么来检查访问令牌验证是否成功?例如。在伪代码中:

public string MyAction()
{
    if(AccessTokenIsValid())
    {
        return "one thing.";
    } 
    else
    {
        return "another.";
    }
}

【问题讨论】:

    标签: asp.net openid asp.net-core openid-connect


    【解决方案1】:

    应该超级简单:

    public string MyAction()
    {
        if (User.Identity.IsAuthenticated)
        {
            return "one thing.";
        } 
        else
        {
            return "another.";
        }
    }
    

    您还可以使用 ASP.NET 5 支持的新方法,它基本上是相同的 sn-p 迭代 ClaimsPrincipal 的不同身份来确定是否存在经过身份验证的身份。

    public string MyAction()
    {
        if (User.Identities.Any(identity => identity.IsAuthenticated))
        {
            return "one thing.";
        } 
        else
        {
            return "another.";
        }
    }
    

    【讨论】:

    • 当然,如果您只是需要阻止未经身份验证的请求(而不是返回不同的值),使用AuthorizeAttribute 会容易得多。
    • 酷。我们也看到了这个:context.User?.FindFirst("access_token") 我假设它也应该可以工作。那正确吗?这对我来说是新语法……例如,把 ?在点看起来很奇怪之前。是否喜欢,自动检查null 或其他东西,FindFirst 搜索是什么?是User,请求正文,查询字符串参数。我得再研究一下。
    • 它不会在 OTB 工作,因为不记名中间件不会将令牌存储为声明(您可以使用 SecurityTokenValidated 通知来做到这一点);因为通常,您不需要从资源服务器(也就是您的 API)检索访问令牌。它在客户端应用程序上更有用,因为您经常需要访问令牌来查询您的 API(您可以查看 github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/… 以获取示例)
    • 新的?. 语法基本上是当其中一个成员本身为空时返回空的另一种方式:context.User == null ? null : context.User.FindFirst("access_token")
    • 在资源服务器上,我们是不是经常要检查声明以找出用户的角色。如果授权是基于角色的,那似乎很重要,所以我很惊讶听到这是一个不常见的用例。如果不检查令牌的声明,在资源服务器上进行基于角色的授权的更常见方法是什么?也就是说,在资源服务器上,我们如何确定角色?还是只使用IsInRole() 工作?
    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 2016-02-03
    • 2019-07-12
    • 2012-08-28
    • 2023-02-22
    • 2013-07-12
    • 2012-08-31
    相关资源
    最近更新 更多