无法授权我的前端.Net核心应用

我陷入了一个不寻常的问题。

我有以下内容:

  1. 使用.net核心的Web API项目
  2. 使用Refit SDK调用API。
  3. 第三次从.Net核心Razor Pages前端(单独的项目)中调用这些API。

这正在使用Jwt承载令牌。

下面是API项目的启动文件代码。

services.AddMvc(options =>
                {
                    options.EnableEndpointRouting = false;
                    options.Filters.Add<ValidationFilter>();
                })
                .AddFluentValidation(mvcConfiguration => mvcConfiguration.RegisterValidatorsFromAssemblyContaining<Startup>())
                ;

            var jwtSettings = new JwtSettings();
            configuration.Bind(nameof(jwtSettings),jwtSettings);
            services.AddSingleton(jwtSettings);

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)),ValidateIssuer = false,ValidateAudience = false,RequireExpirationTime = false,ValidateLifetime = true
            };

            services.AddSingleton(tokenValidationParameters);

            services.AddAuthentication(x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(x =>
                {
                    x.SaveToken = true;
                    x.TokenValidationParameters = tokenValidationParameters;
                });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("MustWorkForChapsas",policy =>
                    {
                        policy.AddRequirements(new WorksForCompanyRequirement("chapsas.com"));
                    });
            });

            services.AddSingleton<IAuthorizationHandler,WorksForCompanyHandler>();

这就是我在API控制器中使用授权的方式。

 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [ApiExplorerSettings(GroupName = "V1")]
    public class FaqsController : ControllerBase
    {
        protected readonly ILogger _logger;
        private readonly IFaqService _faqService;
        private readonly IMapper _mapper;
        private readonly IUriService _uriService;

这就是我通过改装生成SKD的方式。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EdgeTours.API.Contracts.V1.Requests;
using EdgeTours.API.Contracts.V1.Requests.Queries;
using EdgeTours.API.Contracts.V1.Responses;
using EdgeTours.Model.CommonViewModels;
using Refit;

namespace EdgeTours.API.Sdk.V1
{
    [Headers("Authorization: Bearer")]
    public interface IFaqApi
    {
        [Get("/api/v1/faqs")]
        Task<ApiResponse<PagedResponse<FaqViewModel>>> GetallAsync(string FaqId = null,int? PageNumber = 1,int? PageSize = 100);

一切正常,当我尝试从浏览器访问无承载令牌的API时,甚至收到401错误。

无法授权我的前端.Net核心应用

该API在前端项目中正常工作。

这是前端项目的启动文件的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using microsoft.AspNetCore.Builder;
using microsoft.AspNetCore.Identity;
using microsoft.AspNetCore.Identity.UI;
using microsoft.AspNetCore.Hosting;
using microsoft.AspNetCore.Http;
using microsoft.AspNetCore.HttpsPolicy;
using microsoft.AspNetCore.Mvc;
using microsoft.EntityFrameworkCore;
using microsoft.Extensions.Configuration;
using microsoft.Extensions.DependencyInjection;
using EdgeTours.Repository.Context;
using microsoft.AspNetCore.Authentication.JwtBearer;
using System.Net;

namespace EdgeTours.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseStaticfiles();
            app.UseCookiePolicy();
            app.UseAuthentication();

            app.UseMvc();
        }
    }
}

问题:

我无法重定向到登录页面,因为未启用授权。如果您能帮助我配置我的剃须刀页面类以及启动文件以启用身份验证,以便在API调用无效时将我重定向到我的登录页面,我将不胜感激。

viktors 回答:无法授权我的前端.Net核心应用

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3154614.html

大家都在问