HttpContext.User.IsAuthenticated имеет значение null в другом контроллере - PullRequest
0 голосов
/ 17 октября 2019

Это мой AccountController:

    public class AccountController : Controller
    {
    private readonly IConfiguration _config;
    private  IHttpContextAccessor _httpContextAccessor;
    private readonly HttpClient _httpClient;
    public AccountController(IHttpContextAccessor httpContextAccessor,IConfiguration config, HttpClient httpClient)
    {
        _httpContextAccessor = httpContextAccessor;
        _config = config;
        _httpClient = httpClient; 
    }


    [HttpGet]
    public IActionResult Index()
    {
        var JWToken = HttpContext.Session.GetString("JWToken");
        if (!string.IsNullOrEmpty(JWToken))
        {
            return RedirectToAction("Index", "Home");
        }
        else 
        {

            return View();

        }  
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async  Task<IActionResult> Index(LoginViewModel model )
    {
        if (!ModelState.IsValid)
        {
            ViewBag.Error = "Email or password is not valid";
            return View(model);
        }
       //password se koduje
        model.Password = PasswordEncoder.EncodePassword(model.Password, model.Password);


        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        /// Posto injectujemo HTTP client dodaje se samo end point u url-u
        HttpResponseMessage HttpResponseMessage = await _httpClient.GetAsync("Authentication/Authenticate/email/" + model.Email + "/password/" + model.Password);
        if (HttpResponseMessage.StatusCode == HttpStatusCode.OK)
        {
            var userToken = HttpResponseMessage.Content.ReadAsStringAsync().Result;
            User  userResult = JsonConvert.DeserializeObject<User>(userToken);                                             
            if (userResult.AcessToken != null)
            {
                var handler = new JwtSecurityTokenHandler();
                var tokenS = handler.ReadToken(userResult.AcessToken) as JwtSecurityToken;
                var claimsIdentity = new System.Security.Claims.ClaimsIdentity(tokenS.Claims, AuthenticationTypes.Password);
                var principal = new System.Security.Claims.ClaimsPrincipal(new[] { claimsIdentity });
                _httpContextAccessor.HttpContext.User = principal;

                //Save token in session object
                _httpContextAccessor.HttpContext.Session.SetString("JWToken", userResult.AcessToken);
                _httpContextAccessor.HttpContext.Session.SetString("UserRoleOrg", JsonConvert.SerializeObject(userResult.ListOfRoleOrg));

                ViewBag.Name = userResult.Firstname;
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ViewBag.Error = "Incorrect username or password. Please try again.";
                return View();
            }

        }
        else
        {
            ViewBag.Error = "Incorrect username or password. Please try again.";
            return View();

        }                   
    }
    [HttpGet]
    public IActionResult Logoff()
    {
        HttpContext.Session.Clear();
        return RedirectToAction("Index", "Home");

    }

Это мой класс StartUp:

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        Uri endPointA = new Uri(Configuration.GetValue<string>("AppSettings:Api")); // this is the endpoint HttpClient will hit
        HttpClient httpClient = new HttpClient()
        {
            BaseAddress = endPointA,
        };

        ServicePointManager.FindServicePoint(endPointA).ConnectionLeaseTimeout = 60000; // sixty seconds

        services.AddSingleton(httpClient);
        //services.AddAuthentication();
        services.AddControllersWithViews().AddRazorRuntimeCompilation();
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
        });
        services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddHttpContextAccessor();          

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            //app.UseHsts();
        }
        app.UseCookiePolicy();
        app.UseStaticFiles();

        app.UseSession();

        app.UseAuthentication();
        app.UseHttpsRedirection();


        //app.UseRouting();
        app.Use(async (context, next) =>
        {
            var JWToken = context.Session.GetString("JWToken");
            if (!string.IsNullOrEmpty(JWToken))
            {
                context.Request.Headers.Add("Authorization", "Bearer " + JWToken);
            }
            await next();
        });


        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Account}/{action=Index}/{id?}");
        });

    }

Итак, вопрос в том, почему isAut = _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated trueв AccountController, и в любом другом контроллере нет никаких претензий и пользователя в _httpContextAccessor.HttpContext.User и returni IsAuthenticated имеет значение false!

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