0

我正在尝试将.NetCore 3.1 代码从承载令牌实现转换为基于 Cookie 的实现还尝试使基于角色的授权与现有代码一起工作。您能帮我更改此代码吗?下面的代码展示了当前如何检索承载令牌,下一部分展示了如何在代码中实现基于角色的授权。

这是当前的承载令牌实现。

var key = Encoding.ASCII.GetBytes(Configuration["AppSettings:Secret"]);

            var signingKey = new SymmetricSecurityKey(key);

            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,
                    ValidateLifetime = true,
                    IssuerSigningKey = signingKey,
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

以下注释当前用于基于角色的授权 -

[Authorize(Roles = "1")]
[Route("api/[controller]")]
[ApiController]

public class JobLogsController : ControllerBase
{
    private readonly EtpRepoContext _context;
    private IJobLogsRepository _jobLogsRepository;
    private IConfiguration _configuration;

    public JobLogsController(EtpRepoContext context, IJobLogsRepository jobLogsRepository, IConfiguration configuration)
    {
        _context = context;
        _jobLogsRepository = jobLogsRepository;
        _configuration = configuration;
    }

    // GET: api/JobLogs
    [HttpGet]
    public async Task<ActionResult<IEnumerable<JobLog>>> GetJobLog()
    {
        return await _context.JobLog.ToListAsync();
    }

    // GET: api/JobLogs/5
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(JobDetail), 200)]
    [ProducesResponseType(typeof(string), 400)]
    public IActionResult FindById([FromRoute] String id)
    {
        string contentStr = "";
        try
        {
            if(id.Length >= 10)
            {
                contentStr = _jobLogsRepository.GetLogById(id);
            }
            else
            {
                contentStr = _jobLogsRepository.GetFileById(id);
            }
            
            var content = Newtonsoft.Json.JsonConvert.SerializeObject(new { content = contentStr });
            return Ok(content);
        }
        catch (Exception ex)
        {
            return StatusCode(500, "Internal server error");
        }
    }

这就是使用 Microsoft 标识模型来声明令牌的方式。

public class ClaimsTransformer : IClaimsTransformation
    {
        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            ClaimsIdentity claimsIdentity = (ClaimsIdentity)principal.Identity;

            // flatten realm_access because Microsoft identity model doesn't support nested claims
            // by map it to Microsoft identity model, because automatic JWT bearer token mapping already processed here
            if (claimsIdentity.IsAuthenticated && claimsIdentity.HasClaim((claim) => claim.Type == "identity"))
            {
                var realmAccessClaim = claimsIdentity.FindFirst((claim) => claim.Type == "identity");
                dynamic realmAccessAsDict = JsonConvert.DeserializeObject<Object>(realmAccessClaim.Value);
                string role = realmAccessAsDict.role.ToString();
                claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", role));

                //var role = realmAccessClaim.
                //var realmAccessAsDict = JsonConvert.DeserializeObject<Object>(realmAccessClaim.Value);
                /*if (realmAccessAsDict["role"] != null)
                {
                    foreach (var role in realmAccessAsDict["role"])
                    {
                        claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", role));
                    }
                }*/
            }

            return Task.FromResult(principal);
        }
    }
}
4

0 回答 0