美文网首页
.net core使用cookie和JwtBearer混合认证方

.net core使用cookie和JwtBearer混合认证方

作者: 看微博也要注册 | 来源:发表于2020-01-21 11:08 被阅读0次

    在setup.cs文件中找到方法

    public void ConfigureServices(IServiceCollection services)

    在方法中加入认证

    services.AddAuthentication(authenticationOptions => authenticationOptions.DefaultScheme = "Cookies")

                            .AddCookie(options =>

                            {

                                options.LoginPath = "/Home/Index/";

                                options.Cookie.HttpOnly = true;

                                options.ExpireTimeSpan = TimeSpan.FromHours(1);

                            }).AddJwtBearer(options =>

                {

                    options.Authority = "ExampleIssuer";

                    options.Audience = "ExampleAudience";

                    options.RequireHttpsMetadata = false;

                    options.IncludeErrorDetails = true;

                    options.TokenValidationParameters = tokenValidationParameters;

                    options.Events = new JwtBearerEvents

                    {

                        OnAuthenticationFailed = c =>

                        {

                            c.NoResult();

                            c.Response.StatusCode = 404;

                            c.Response.ContentType = "text/plain";

                            return c.Response.WriteAsync(c.Exception.ToString());

                        }

                    };

                });

    默认情况下使用cookie 验证,如果只是对外的接口,使用token认证,那么需要在controller加入attribute

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

        [Route("api/[controller]")]

        [ApiController]

    指定controller使用Bearer来做身份认证。

    一个contoller内的方法要分别使用Cookie和Bearer来认证的话,需要拆分开。否则只能有一种身份认证生效,调用另一种认证的接口会返回401。认证失败。

    相关文章

      网友评论

          本文标题:.net core使用cookie和JwtBearer混合认证方

          本文链接:https://www.haomeiwen.com/subject/ihhfpftx.html