我可能会在asp.core1中使用DI获得声明,如下所示
public class UserService : IUserService
{
private IHttpContextAccessor _httpContext;
public UserService(IHttpContextAccessor httpContext)
{
_httpContext = httpContext;
}
}
对于In asp.core 2,_httpContext.User.Identity.IsAuthenticated
的值为false
,并且不包含声明。
我的startup.cs看起来像这样:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
// ...
};
});
services.AddCors();
services.AddMvc();
services.AddTransient<IUserService, UserService>();
services.AddTransient<IHttpContextAccessor, HttpContextAccessor();
}