HttpContext.User.Claims ноль элементов в базе контроллеров - PullRequest
0 голосов
/ 08 июня 2019

Я включаю AWS-CognitoIdentity Provider в свой проект ASP.Net Core Web Api, и после ознакомления с официальной документацией я все еще получаю HttpContext.User NULL.Существует ли пошаговое руководство, которое ранее кто-то использовал для успешной работы провайдера AWS-CognitoIdentity.

Я настроил CognitoIdentity в моем Startup.cs и позже в других моих контроллерах, я пытаюсь получить доступ к Пользователю.

public class Startup
{
    private static readonly ILog logger = LogManager.GetLogger(typeof(Startup));

    private string poolId;
    private string appClientId;
    private static string providerName;

    private static AmazonCognitoIdentityProviderClient provider;
    private static CognitoUserPool pool;

    public IConfiguration Configuration { get; }




    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        appClientId = Configuration.GetValue<string>("AWS:UserPoolClientId");
        providerName = Configuration.GetValue<string>("AWS:ProviderName");
        poolId = Configuration.GetValue<string>("AWS:UserPoolId");
        AWSConfigs.RegionEndpoint = RegionEndpoint.EUWest2;
        provider = new AmazonCognitoIdentityProviderClient();
        pool = new CognitoUserPool(poolId, appClientId, provider, "");


    }


    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<IdentityOptions>(options =>
        {
            options.Lockout.MaxFailedAccessAttempts = 10;
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
        });

        services.AddCognitoIdentity();
        services.AddAuthentication("Bearer").AddJwtBearer(options =>
        {

            options.Audience = Configuration.GetValue<string>("AWS:UserPoolClientId");
            options.Authority = Configuration.GetValue<string>("AWS:ProviderName");

            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = Configuration.GetValue<string>("AWS:ProviderName"),
                ValidateIssuerSigningKey = true,
                ValidateIssuer = true,
                ValidateLifetime = true,
                ValidAudience = Configuration.GetValue<string>("AWS:UserPoolClientId"),
                ValidateAudience = true,

                IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
                {
                    var json = new WebClient().DownloadString(Configuration.GetValue<string>("AWS:MetadataAddress"));
                    var keys = JsonConvert.DeserializeObject<JsonWebKeySet>(json).Keys;
                    return (IEnumerable<SecurityKey>)keys;
                },


            };
            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    Console.WriteLine("Message Received-------------------------------------------------------------\n");
                    return Task.CompletedTask;
                },
                OnTokenValidated = context =>
                {
                    Console.WriteLine("TokenValidated Received-------------------------------------------------------\n");
                    return Task.CompletedTask;
                }
            };
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(
        IApplicationBuilder app,
        IHostingEnvironment env,
        UserManager<CognitoUser> _userManager,
        SignInManager<CognitoUser> _signInManager)
    {


        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAuthentication();
        app.UsePermissions();

        app.UseMvc();

        app.UseSwagger();

    }
}

Контроллер

namespace DataControllers
{
    //[Authorize]
    [Route("api/[controller]/[action]")]
    public class ContentController : Controller
    {
        private readonly CognitoUserManager<CognitoUser> _userManager;



        public ContentController(UserManager<CognitoUser> userManager)
        {

            _userManager = userManager as CognitoUserManager<CognitoUser>;
        }

        [HttpGet]
        public async Task<IActionResult> Menu()
        {

            var email = User.Claims.FirstOrDefault(e => e.Type == "email"); ;

        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...