V
V
Victor P.2018-11-06 14:38:56
Angular
Victor P., 2018-11-06 14:38:56

Why doesn't authentication work in .net core with angular 5?

Good afternoon!
Created the latest .net core 2.1 template with Angular 5+.
Decided to add standard authentication.
Everything turned out and earned, but after the publication it does not work hard.
Here are my sources (I cut out the excess):
Startup.cs

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

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(c => c.AddPolicy("AllowSpecificOrigin", builder =>
            {
                builder
                .AllowCredentials()
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.SlidingExpiration = true;
                    options.Cookie.SameSite = SameSiteMode.Lax;
                    options.Cookie.HttpOnly = false;
                });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors("AllowSpecificOrigin");
            app.UseAuthentication();

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

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

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
    }

I added the corses (as well as the cookie settings) later, I thought maybe there was something hidden in them. But, again, this is one project that contains both Angular files and api. That is, all requests are absolutely on the same domain.
AccountController.cs
[Route("api/[controller]")]
    [ApiController]
    public class AccountController : Controller
    {
        [HttpPost("[action]")]
        [AllowAnonymous]
        public async Task<IActionResult> LogIn([FromBody] LoginDto model)
        {
            if (model.Email.ToLower() == "jeer" && model.Password == "123")
            {
                var claims = new[] { new Claim(ClaimTypes.Name, model.Email),
                    new Claim(ClaimTypes.Role, "admin") };

                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(identity));

                var usr = new UserDto
                {
                    UserName = model.Email,
                    Roles = new List<string> { "admin" }
                };

                return Ok(usr);
            }

            return Unauthorized();
        }
}

Yes, I'm not using the database yet, I've hardcoded my login/password. And it works (from visualstudio debug).
Next, I try to throw an authorization attribute (filter) on one of the methods. And here the problem is that if I run the project from the studio on F5, then User.Identity.Name == jeer. And if I publish to the hosting or to my computer in the c:/publish folder and bind the usual IIS to this folder, then the angular files are launched, authentication passes, but after that User.Identity.Name == null.
PeresmehController.cs
[HttpGet("[action]")]
        //[Authorize] // - делает редирект
        [EnableCors("AllowSpecificOrigin")]
        public async Task<List<string>> List()
        {
            var kk = User.Identity.Name; // null

            // тут вызов базы
            return null;
        }

From angular I call with standard post/get:
public login(model: LoginDto): Observable<UserDto> {
    return this.http.post<UserDto>('/api/Account/Login', model, { withCredentials: true });
  }

  public getList(): Observable<string[]> {
    return this.http.get<string[]>('/api/Peresmeh/List', { withCredentials: true });
  }

5be17c92d3e23878326449.png5be17ca2b19d2708536268.png
I tried to separate projects and authentication worked for me after cors was configured correctly. In the same project, nothing works. Where did the dog dig?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question