Answer the question
In order to leave comments, you need to log in
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");
}
});
}
}
[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();
}
}
[HttpGet("[action]")]
//[Authorize] // - делает редирект
[EnableCors("AllowSpecificOrigin")]
public async Task<List<string>> List()
{
var kk = User.Identity.Name; // null
// тут вызов базы
return null;
}
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 });
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question