In. net core 3.1, как я могу вернуть данные с токена на предъявителя? - PullRequest
0 голосов
/ 28 апреля 2020

Я пытаюсь вернуть некоторые данные из токена-носителя для использования в качестве параметров в функции, которую я вызываю в моей конечной точке. В настоящее время, когда я тестирую код, две строки userName & applicationName, которые мне нужны в качестве параметров, возвращают значение null, поэтому я получаю 500. Это здорово, но мне нужны и userName, и applicationName, чтобы хранить данные для использования в качестве параметров в функции 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"
  ]
}

1 Ответ

0 голосов
/ 29 апреля 2020

Я использую этот код для добавления претензий к 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()) вы можете поместить в токен все, что захотите.

И когда вы хотите прочитать эти данные в контроллере, просто используйте этот код:

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