小编Tea*_*oft的帖子

.Net Core 2 JWT、Angular 2 通过角色授权不起作用

我在用 JWT 生成的令牌中有以下有用的负载

{ "sub": "flamelsoft@gmail.com", "jti": "0bca1034-f3ce-4f72-bd91-65c1a61924c4", " http://schemas.microsoft.com/ws/2008/06/identity/claims/角色":"管理员","exp":1509480891,"iss":" http://localhost:40528 ","aud":" http://localhost:40528 "}

使用此代码 Startup.cs

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<DBContextSCM>(options =>
        options.UseMySql(Configuration.GetConnectionString("DefaultConnection"), b =>
         b.MigrationsAssembly("FlamelsoftSCM")));

        services.AddIdentity<User, Role>()
            .AddEntityFrameworkStores<DBContextSCM>()
            .AddDefaultTokenProviders();

        services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

        services.AddAuthentication()
             .AddJwtBearer(cfg =>
             {
                 cfg.RequireHttpsMetadata = false;
                 cfg.SaveToken = true;

                 cfg.TokenValidationParameters = new TokenValidationParameters()
                 {
                     ValidIssuer = Configuration["Tokens:Issuer"],
                     ValidAudience = Configuration["Tokens:Issuer"],
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                 };

             });

        services.AddMvc();
    }
Run Code Online (Sandbox Code Playgroud)

账户控制器.cs

        [HttpPost]
    [Authorize(Roles="Administrator")]
    public async Task<IActionResult> Register([FromBody]RegisterModel model)
    {
        try
        {
            var user = new User { …
Run Code Online (Sandbox Code Playgroud)

c# jwt asp.net-core-mvc angular2-jwt asp.net-core-2.0

3
推荐指数
1
解决办法
2512
查看次数