首页 > 解决方案 > 如何使用 AspNetCore 2.2 对 Angular 获取或发布请求进行身份验证和授权?

问题描述

我已经设置了一个 dotnet angular 项目,然后在 StartUp.cs 文件中实现了如下身份验证。

public void ConfigureServices(IServiceCollection services)
{

    services.AddScoped<IPasswordHasher<CustomUser>, 
        PasswordHasherWithOldMembershipSupport<CustomUser>>();

    services.AddIdentity<CustomUser, IdentityRole>()
        .AddEntityFrameworkStores<AuthenticationContext<CustomUser>>()
        .AddDefaultUI()
        .AddDefaultTokenProviders();

    var connection = configuration.GetConnection("Authentication");
    services.AddDbContext<AuthenticationContext<CustomUser>>(options =>
        options.UseSqlServer(connection));

    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<AuthMessageSender.ISmsSender, AuthMessageSender>();


    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseAuthentication();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });
    ...
 }

IdentityHostingStartUp.cs 文件在启动时运行以配置身份验证。

public class IdentityHostingStartup : IHostingStartup
{
    public void Configure(IWebHostBuilder builder)
    {
        builder.ConfigureServices((context, services) =>
        {
            services.AddAuthentication();
            services.Configure<IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase = true;
                options.Password.RequiredLength = 6;
                options.Password.RequiredUniqueChars = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers = true;

                // User settings.
                options.User.RequireUniqueEmail = false;
            });

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(15);

                options.LoginPath = "/Identity/Account/Login";
                options.AccessDeniedPath = "/Identity/Account/AccessDenied";
                options.SlidingExpiration = true;
            });
        });
    }
}

如果用户未登录,我的角度代码中有一个自定义重定向可以转到身份验证页面。

import { Inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AuthService {
  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {

    http.get<Boolean>(baseUrl + "api/Home/Status").subscribe((authenticated) => {
      if (!authenticated) {
        window.location.href = baseUrl + "/Identity/Account/Login";
      }
    });
  }

最后,我的 HomeController 代码检查登录用户的身份验证状态。

[HttpGet("[action]"), AllowAnonymous]
public Boolean Status()
{
    var user = _accessor.HttpContext.User;
    return User.Identity.IsAuthenticated;
}

Status(或任何其他调用的 api 控制器操作)操作始终具有 null 用户名、用户声明,并且即使在登录后 IsAuthenticated 也始终返回 false。

这把我逼到了墙角。我已经阅读了尽可能多的帖子并尝试了尽可能多的选项,但似乎没有任何效果。

在某些时候,我注意到用户名按预期填写。我以为解决了。但是,从那时起它已经停止工作,即使我没有改变任何东西并且我无法解决这个问题。

标签: angularjsasp.net-coreauthorizationasp.net-identity

解决方案


当您的调试设置设置为未选中 EnableSSL 时,会发生这种情况。如果您要在未启用 SSL 的情况下进行部署,这也会成为问题。如下图所示,一旦我启用 SSL,应用程序身份 cookie 就会包含在 ajax 请求中。

在此处输入图像描述


推荐阅读