使用邮递员

时间:2017-11-01 18:11:53

标签: c# json asp.net-core

我正在关注此Tutorial以及使用基于声明的授权部分保护控制器我在Postman中收到 404 Not Found 错误。我完全按照教程,我只是运行.net core v2.0.0。

Tutorial的DashboardController.cs在我的项目中,名为BordViewController.cs。

这是我的BordViewController.cs。问题是,控制不在这个类中,但是当我删除[Authorize(Policy = "ApiUser")]时,它可以工作。

  using Microsoft.AspNetCore.Authorization;
   using Microsoft.AspNetCore.Mvc;

namespace DotNetGigs
{

    [Authorize(Policy = "ApiUser")]
    [Route("api/[controller]")]
    public class BordViewController : Controller
    {       
        public BordViewController()
        {

        }

         // GET api/dashboard/home
        [HttpGet("home")]
        public IActionResult GetHome()
        {
            return new OkObjectResult(new { Message = "This is secure data!" });
        }
    }
}

这是我的startup.cs文件

private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));


        public Startup()
        {
            var builder  = new ConfigurationBuilder();            
            builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory().ToString(),"Configuration.json"));
            Configuration = builder.Build();
        }

        public IConfiguration Configuration {get;set;} 

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<AppDBcontext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),b=>b.MigrationsAssembly("LoginApp")));

           services.AddSingleton<IJWTfactory, JWTFactory>();

           var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));



            // Configure JwtIssuerOptions
            services.Configure<JwtIssuerOptions>(options =>
            {
                options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
                options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
                options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);});

            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JWTclaimIden.Rol, Constants.Strings.JWTclaims.ApiAccess));
            });

            services.AddIdentity<AppUser, IdentityRole>(o =>
                {
                    // configure identity options
                    o.Password.RequireDigit = false;
                    o.Password.RequireLowercase = false;
                    o.Password.RequireUppercase = false;
                    o.Password.RequireNonAlphanumeric = false;
                    o.Password.RequiredLength = 6;
                })
                .AddEntityFrameworkStores<AppDBcontext>()
                .AddDefaultTokenProviders();

            var tokenValidationParameters = new TokenValidationParameters
            {
                    ValidateIssuer = true,
                    ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                    ValidateAudience = true,
                    ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = _signingKey,

                    RequireExpirationTime = false,
                    ValidateLifetime = false,
                    ClockSkew = TimeSpan.Zero
            };


            services.AddAuthentication(options =>
                {
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(options => 
                    {                   // options.Audience = Configuration.GetSection("TokenProviderOptions:Audience").Value;
                                        //options.Issuer = Configuration.GetSection("TokenProviderOptions:Issuer").Value;
                                        // options.SaveToken = true;
                        options.TokenValidationParameters = tokenValidationParameters;
                        options.RequireHttpsMetadata = false;
                    });

            services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
            services.AddAutoMapper();            
        }





        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }


           app.UseAuthentication();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseMvc();
        }

我是c#和.net核心的新手,如果有人可以帮助我弄清楚我犯的错误,我会非常感激。如果您还要我添加其他文件,请告诉我。

Postman Code代码段

 GET /api/boardview/home HTTP/1.1
    Host: localhost:5000
    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJuaWtoaWxrYTU4NUBnbWFpbC5jb20iLCJqdGkiOiJmMTc1ZjdiNy1iN2ZmLTQxM2UtYjM5Ny0yYTQyYmI3NjMxZmQiLCJpYXQiOjE1MDk1NTY2MzQsInJvbCI6ImFwaV9hY2Nlc3MiLCJpZCI6ImJlOWJmZjc5LThlNDEtNDEwYS1iN2E3LTBjOGQxNDExYjQ5YyIsIm5iZiI6MTUwOTU1NjYzNCwiZXhwIjoxNTA5NTYzODM0LCJpc3MiOiJMb2dpbkFwcCIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC8ifQ.NbwKHjH8h
    Cache-Control: no-cache
    Postman-Token: 18e932c2-ac73-5539-60a1-04b7b981e37a

JwtIssureOptions

"JwtIssuerOptions": {
          "Issuer":"LoginApp",
          "Audience":"http://localhost:5000/"
      }

0 个答案:

没有答案