簡體   English   中英

在 .net 核心 3.1 中,如何從不記名令牌返回數據?

[英]In .net core 3.1 how can I return data from a bearer token?

我正在嘗試從承載令牌返回一些數據,以用作我在端點中調用的 function 中的參數。 目前,當我測試代碼時,我需要作為參數的兩個字符串 userName 和 applicationName 返回 null 所以我得到 500。這很好,但我需要 userName 和 applicationName 來存儲數據以用作 function GetAbsoluteTimeout(); 我怎樣才能做到這一點?

端點:

        [ProducesResponseType(typeof(int), StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(StatusCodeResult), StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(typeof(StatusCodeResult), StatusCodes.Status500InternalServerError)]
        [Consumes(MediaTypeNames.Application.Json)]
        [Produces(MediaTypeNames.Application.Json)]
        [IDMAuthorize]
        public IActionResult GetAbsoluteTimeoutForClaimsPrincipal()
        {
            DateTime startTime = DateTime.Now;
            try
            {
                string logText = LogFormatter.Format(
                                   WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                   startTime, DateTime.Now, Privilege.NotApplicable,
                                   "Get Absolute Timeout For Claims Principal", "Attempting to get the absolute timeout for the current user.");
                logger.LogInfo(logText);

                string userName = Convert.ToString(JsonConvert.DeserializeObject(HttpContext.Request.Headers["email"]));
                string applicationName = Convert.ToString(JsonConvert.DeserializeObject(HttpContext.Request.Headers["client_id"]));
                int timeout = 0;

                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(applicationName))
                {
                    timeout = GetAbsoluteTimeout(userName, applicationName);
                }

                logText = LogFormatter.Format(
                                   WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                   startTime, DateTime.Now, Privilege.NotApplicable,
                                   "Get Absolute Timeout For Claims Principal", "Successful retrieval of the absolute timeout for the current user.");
                logger.LogInfo(logText);

                return Ok(timeout);
            }
            catch (Exception ex)
            {
                string logText = LogFormatter.Format(
                                    WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                    startTime, DateTime.Now, Privilege.ViewIMUData,
                                     "Get Absolute Timeout For Claims Principal", ex.ToString());

                logger.LogError(logText, ex);
                return StatusCode(Constants.InternalServerErrorCode, "Failed to get absolute timeout for claims principal. Please check logs for more details. ");
            }

        }

以下是來自 JWT 不記名令牌的數據:

"client_id": "JITWebAdmin",
  "scope": [
    "openid",
    "profile",
    "email",
    "jitwebapi"
  ],
  "sub": "dd458da9-5de6-4f79-8756-e4756fef63a3",
  "auth_time": 1588098606,
  "idp": "idm-JadenCCE21-8a9fa4f4-62c2-4c8f-afe6-4ffb740e2327",
  "updated_at": 1566433758,
  "tenant": "default",
  "preferred_username": "admin",
  "email": "admin@email.com",
  "email_verified": "true",
  "login_attempt": "{\"LoginDate\":\"2020-04-28 18:28:46Z\",\"WasSuccessful\":true,\"IpAddress\":\"10.160.176.79\"}",
  "name": "admin",
  "amr": [
    "external"
  ]
}

我使用此代碼向jwt添加聲明並發出令牌:

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(EncryptionKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[]
    {
        new Claim(ClaimTypes.Name, user.Username),
        new Claim(ClaimTypes.NameIdentifier , user.Id.ToString()),
    }),
    Expires = DateTime.UtcNow.AddDays(1),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);

例如,在這行代碼new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())中,您可以在令牌中放入任何您想要的內容。

當您想讀取 controller 中的數據時,只需使用以下代碼:

var userId = HttpContext.User.Claims.SingleOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM