Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 未授权WebApi core 2.2 JWT令牌_C#_Asp.net Core - Fatal编程技术网

C# 未授权WebApi core 2.2 JWT令牌

C# 未授权WebApi core 2.2 JWT令牌,c#,asp.net-core,C#,Asp.net Core,我能够生成令牌,但如果我尝试在控制器中进行授权,它将无法工作 我创建了一个类JWT,但没有设置发行者或受众 private List<Claim> Claim = new List<Claim>(); public string GetUserToken(string tp,string id) { var sck = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.G

我能够生成令牌,但如果我尝试在控制器中进行授权,它将无法工作

我创建了一个类JWT,但没有设置发行者或受众

private List<Claim> Claim = new List<Claim>();
    public string GetUserToken(string tp,string id)
    {
        var sck = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
        var sc = new SigningCredentials(sck, SecurityAlgorithms.HmacSha256Signature);

        if(tp == "Host")
        {
            Claim.Add(new Claim(ClaimTypes.Role, "Host"));
            Claim.Add(new Claim(ClaimTypes.Name, id));
        }
        else
        {
            Claim.Add(new Claim(ClaimTypes.Role, "Client"));
            Claim.Add(new Claim(ClaimTypes.Name, id));
        }

        var token = new JwtSecurityToken(               
            expires: DateTime.Now.AddDays(30),
            signingCredentials: sc,
            claims: Claim
            );
        return new JwtSecurityTokenHandler().WriteToken(token);
    }

在我的控制器中,我只需要放置[AuthorizeRoles=Host]。即使删除Roles属性,结果仍然相同,检查您的密钥和jwt配置,您的启动类应该如下所示:

public void ConfigureServices(IServiceCollection services)
        {

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

            //Get the key from configuration file section
            var appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);

            //jwt configuration 
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x => {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //Configuration of cors to allow request of anothers 
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            //Use the authentication service
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvc();
        }

它确实有这些信息。在configure方法中,我只有app.UseAuthentication;。我会添加其他的和测试相同的东西,未经授权!请分享你的创业计划file@NathielPaulino您确定正在使用DefaultChallenge和Authentication吗Scheme@Zachdev你有两次身份验证,那可能会把事情搞砸
public void ConfigureServices(IServiceCollection services)
        {

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

            //Get the key from configuration file section
            var appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);

            //jwt configuration 
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x => {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //Configuration of cors to allow request of anothers 
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            //Use the authentication service
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvc();
        }