Asp.net Core收到Bearer错误=“ invalid_token”,error_description =“签名无效”

时间:2020-01-29 08:24:46

标签: c# asp.net api asp.net-core .net-core

我正在研究dotnet核心API。我可以生成令牌,也可以通过此站点jwt.ms检查令牌。一切正常。但是当我发送带有此令牌的请求时,它说(请检查图像)check postman output with token

Startup.cs

namespace blogapi
{
    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.AddDbContext<ApplicationDbContext>(x => x
                .UseMySql(Configuration.GetConnectionString("DefaultConnection"))
                .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));

            services.AddCors();
            //services.AddControllers();

            services.AddScoped<IPostRepository, PostRepository>();
            services.AddScoped<IUserRepository, UserRepository>();

            services.AddAutoMapper(typeof(Maps));

            // services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            // {
            //     builder.AllowAnyOrigin()
            //         .AllowAnyMethod()
            //         .AllowAnyHeader();
            // }));

            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get<AppSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(x =>
                {
                    // x.Events = new JwtBearerEvents
                    // {
                    //     OnTokenValidated = context =>
                    //     {
                    //         var userService = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
                    //         var userId = int.Parse(context.Principal.Identity.Name);
                    //         var user = userService.GetById(userId);
                    //         if (user == null)
                    //         {
                    //             // return unauthorized if user no longer exists
                    //             context.Fail("Unauthorized");
                    //         }
                    //
                    //         return Task.CompletedTask;
                    //     }
                    // };
                    x.RequireHttpsMetadata = false;
                    x.SaveToken = true;
                    x.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key: key),
                        ValidateIssuer = false,
                        ValidateAudience = false,
                        RequireExpirationTime = false,
                        ValidateLifetime = true
                        // ValidateIssuerSigningKey = true,
                        // IssuerSigningKey = new SymmetricSecurityKey(key),
                        // ValidateIssuer = false,
                        // ValidateAudience = false
                    };
                });

            //services.AddControllersWithViews();
            services.AddMvc(options => options.EnableEndpointRouting = false);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/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.UseHttpsRedirection();
            }

            app.UseStaticFiles();

            // app.UseRouting();
            //
            // //app.UseCors(builder => builder.WithOrigins("http://localhost:4200"));
            // app.UseCors("MyPolicy");
            //
            // app.UseAuthorization();
            //
            // app.UseEndpoints(endpoints =>
            // {
            //     endpoints.MapControllerRoute(
            //         name: "default",
            //         pattern: "{controller=Home}/{action=Index}/{id?}");
            // });

            //app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            //app.UseEndpoints(endpoints => endpoints.MapControllers());
        }
    }
}

PostController.cs

namespace blogapi.Controllers.Api
{
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [Route("api/[controller]")]
    [ApiController]
    public class PostController : ControllerBase
    {
        private readonly IPostRepository _repo;
        private readonly IUserRepository _userRepository;
        private readonly IMapper _mapper;

        public PostController(IPostRepository repo, IMapper mapper, IUserRepository userRepository)
        {
            _repo = repo;
            _mapper = mapper;
            _userRepository = userRepository;
        }

        // GET api/post
        [AllowAnonymous]
        [HttpGet]
        public IEnumerable<PostViewModel> GetPosts()
        {
            var posts = _repo.FindAll().ToList();
            var model = _mapper.Map<List<Post>, List<PostViewModel>>(posts);

            return model;
        }

        User GetSecureUser()
        {
            var id = int.Parse(HttpContext.User.Claims.First().Value);
            return _userRepository.GetById(id);
        }

        // POST api/post
        [HttpPost]
        public CreatePostRequest AddPost([FromBody] CreatePostRequest postRequest)
        {
            var post = new Post
            {
                Title = postRequest.Title,
                Description = postRequest.Description,
                UserId = HttpContext.GetCurrentUserId()
            };
            //_repo.Create(post);
            return postRequest;
        }

        [AllowAnonymous]
        // GET api/post/{id}
        [HttpGet("{id}")]
        public Post GetPost(int id)
        {
            return _repo.FindById(id);
        }
    }
}

我已经尝试过此link给出的解决方案,但找不到。任何帮助将不胜感激。

示例令牌:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJydW1pQGdtYWlsLmNvbSIsIklkIjoiMSIsIm5iZiI6MTU4MDI4NjA5NiwiZXhwIjoxNTgwNTQ1Mjk2LCJpYXQiOjE1ODAyODYwOTZ9.G-9e2uNzBcznazaII1_p5EVjtKtVES6XalXPEnlef6c

0 个答案:

没有答案