c# - 使用 open id connect server 在 asp.net core 中检索声明

标签 c# asp.net authentication asp.net-core aspnet-contrib

我即将在我的 asp.net 核心应用程序中实现基于承载的身份验证。来自 .NET Framework,核心内容对我来说仍然很新。从服务器获取 token 已经很有效了。但是我如何在以下请求中确定用户是否已通过身份验证?在 .NET Framework 项目中,我曾经使用

(ClaimsIdentity)Thread.CurrentPrincipal.Identity.IsAuthenticated;

但是,这会返回一个带有空声明或默认声明的身份。到目前为止,这是我的设置:

我从 OpenIdConnect.Server 开始框架和示例代码在他们的 Get Started部分。这很好用,我的客户收到了 Bearer Token。我已按照以下方式在我的 Startup.cs 中构建它:

public class Startup
{
    [...]

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry(Configuration);
        services.AddMvc();
        services.AddAuthentication();
        [...]
    }

    public void Configure([...])
    {
        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseMvc();
        app.UseOpenIdConnectServer(options =>
        {
            [code of example]
        }
    }

在客户端,我将检索到的 token 用于进一步的请求

The Bearer Token is transmitted in the header.

现在,我现在如何访问当前登录的用户声明或我如何知道他/她是否已通过身份验证?

我试过了

// within api controller:
var isAuth = this.User.Identity.IsAuthenticated

// using DI
public class MyClass(IHttpContextAccessor httpContextAccessor) {
    public void MyMethod() {
        var isAuth = httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
    }
}

但这总是返回 false 并且声明是一些默认值。 我错过了什么吗?我是否需要安装一些额外的服务或中间件?

最佳答案

OpenID Connect 服务器中间件需要注意的一件事是它不会为您验证传入的访问 token (它只会发出它们)。由于您使用的是默认 token 格式(加密),因此您可以为此使用 AspNet.Security.OAuth.Validation 包:

public class Startup
{
    [...]

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry(Configuration);
        services.AddMvc();
        services.AddAuthentication();
        [...]
    }

    public void Configure([...])
    {
        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseOpenIdConnectServer(options =>
        {
            [code of example]
        });
        app.UseOAuthValidation();
        app.UseMvc();
    }
}

关于c# - 使用 open id connect server 在 asp.net core 中检索声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43628520/

相关文章:

PHP 密码无效,即使有效

Sharepoint:如何部署自定义身份验证提供程序?

android facebook webview登录不带用户登录

c# - 添加范围然后查找重复项或检查每个项目的冲突是否更快?

c# - 使用 MVC Core 时将参数传递给 main 方法

javascript - 向按钮添加 onclick 事件会导致页面错误

android - java.lang.string 无法转换为 jsonarray asp.net

c# - 为什么 DrawRectangle 在我的 PictureBox 中绘制一个十字

c# - 管道未正确读取数据

c# - 在 WinForms 应用程序中编译 ASPX