如何使用SPA和API设置OpenID 2.0身份验证?

时间:2020-04-23 13:50:25

标签: .net authentication cookies jwt openid

问题


我有一个带有API(.Net Core)的SPA(反应),我想使用仅支持OpenId 2.0的(IdP)身份提供程序进行身份验证。我希望此身份验证也适用于API。

我已经设法通过IdP实施身份验证,以便从用户信息中获得来自它们的回调,并且已经在SPA和API之间实现了基本的JWT身份验证。

但是,由于JWT没有指定SignIn' method, but OpenId 2.0 demands that a SignInScheme`,因此我不知道如何连接两者。

当前的身份验证流程如下: SPA->重定向到API-> API重定向到IdP->用户输入其凭据-> IdP重定向到API-> API对用户进行身份验证-> API使用包含JWT令牌的cookie将用户重定向到SPA-> SPA提取并存储JWT令牌-> SPA随每个请求发送JWT令牌。

我尝试过的


如果我尝试将JWT用作DefaultSignInScheme,但随后出现以下错误

为方案“ Bearer”注册的身份验证处理程序为“ JwtBearerHandler”,不能用于SignInAsync

我尝试使用Cookies作为DefaultSignInScheme和JWT作为DefaultAuthenticatioSchemeDefaultChallengeScheme。但是,这对我来说是错的,因为那时我的API上有一个cookie,清除SPA数据不会注销我。我可以通过检查是否发送了JWT令牌来解决该问题,但这又让人感觉很棘手。

在API上设置cookie之前,我曾尝试将cookie传递回SPA。但是,必须先在API上设置cookie,然后才能与它进行交互。

代码段


Startup.cs with the JWT and Cookie flow

private void ConfigureAuthentication(IServiceCollection services)
    {
        services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["AuthenticationSettings:Secret"])),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            })
            .AddCookie(options =>
            {
                options.Cookie.Name = Constants.Authentication.Cookies.AuthCookie;
                options.Cookie.HttpOnly = true;
                options.Cookie.SameSite = SameSiteMode.None;
            })
            .AddSteam(); // The OpenId 2.0 IdP
    }

0 个答案:

没有答案