2017-04-26 62 views
2

我即将在我的asp.net核心应用程序中实施基于承载的身份验证。来自.NET Framework的核心内容对我来说还是很新的。从服务器获取令牌已经很好。但是,如何在跟随请求中确定用户是否已通过身份验证?在.NET Framework项目中,我曾经使用过使用开放ID连接服务器检索asp.net核心中的声明

(ClaimsIdentity)Thread.CurrentPrincipal.Identity.IsAuthenticated; 

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

我已经开始框架和示例代码在其Get Started部分。这很好,我的客户收到一个无记名令牌。我在我的下列方式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] 
     } 
    } 

在客户端,我用了进一步要求

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和权利要求一些默认值。 我错过了什么吗?我是否需要安装一些附加服务或中间件?

回答

1

使用OpenID Connect服务器中间件需要注意的一件事是,它不会验证传入的访问令牌(它只发布它们)。由于您使用的是默认令牌格式(加密),你可以使用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(); 
    } 
} 
+0

谢谢,这是缺少的部分。 –