WebApi核心2.2 JWT令牌未获得授权

时间:2019-05-13 16:51:30

标签: 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.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);
    }

Startup类内部:

public void ConfigureServices(IServiceCollection services)
    {
        var SymmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).
            AddJwtBearer(options => {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,                    
                IssuerSigningKey = SymmetricSecurityKey
            };
        });

在控制器中,我只放了[Authorize(Roles ="Host")]。即使删除Roles属性,结果仍然相同,401 Unauthorized

1 个答案:

答案 0 :(得分:1)

检查您的密钥和jwt配置,您的启动类应如下所示:

<div id="container">
  <style>
    #graph-container {
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      position: absolute;
    }
  </style>
  <div id="graph-container"></div>
</div>

g.nodes.push(...............)
g.edges.push(................)

s = new sigma({
  graph: g,
  renderer: {
    container: 'graph-container',
    type: 'canvas'
  },
  settings: {
    minNodeSize: 6,
    maxNodeSize: 6,
    minEdgeSize: 3,
    maxEdgeSize: 3
  }
});
layout();

function layout(){
      dagreListener = sigma.layouts.dagre.configure(s, {
      directed: true, 
      rankdir: 'LR',  
      easing: 'quadraticInOut', 
      duration: 800
    });

    // Bind the events:
    dagreListener.bind('start stop interpolate', function(e) {
      console.log(e.type);
    });

    // Start the DAG layout:
    sigma.layouts.dagre.start(s);
}

s.bind('clickNode', function(e) {
    s.graph.read({nodes: nodes, edges: edges});
    layout();
});