public IActionResult RequestToken([FromBody] JwtTokenRequest request)
        {
            if (request == null)
            {
                return(Unauthorized("Invalid Request"));
            }

            if (!ModelState.IsValid)
            {
                _logger.LogInformation("JWT Authenticate Error - incoming request for jwt token was Invalid.");
                return(Unauthorized(ModelState));
            }

            string token;

            if (_authService.IsAuthenticated(request, out token))
            {
                _logger.LogInformation("JWT Authenticate OK - incoming request authorised for: " + request.Username);
                return(Ok(token));
            }

            //
            _logger.LogInformation("JWT Authenticate Error - incoming request denied for: " + request.Username);
            return(Unauthorized("Invalid Request"));
        }
Beispiel #2
0
        public bool IsAuthenticated(JwtTokenRequest request, out string token)
        {
            token = string.Empty;

            try
            {
                // this can't happen but because these stupid VS 'code enhancers' are flagging it lets add some unnecessary clutter code in
                if (request == null)
                {
                    return(false);
                }

                // now check agains our injected user checker
                if (!_userManagementService.IsValidUser(request.Username, request.Password))
                {
                    return(false);
                }

                var claim = new[]
                {
                    new Claim(ClaimTypes.Name, request.Username)
                };
                var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
                var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var jwtToken = new JwtSecurityToken(
                    _tokenManagement.Issuer,
                    _tokenManagement.Audience,
                    claim,
                    expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration),
                    signingCredentials: credentials
                    );

                // had to do this (can't remember why so quickly..)
                Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;

                // https://stackoverflow.com/questions/50590432/jwt-securitytokeninvalidsignatureexception-using-rs256-pii-is-hidden
                token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error occurred in JWT IsAuthenticated - " + ex.Message);
            }

            return(false);
        }