Example #1
0
        public static JwtPayload DecodeToken(string token, string secret, out bool validated)
        {
            var jwtPayload = new JwtPayload();

            var segments = token.Split('.');

            var invalidToken = segments.Length != 3;

            if (!invalidToken)
            {
                try
                {
                    jwtPayload = JsonConvert.DeserializeObject(
                        Encoding.UTF8.GetString(Base64Decode(segments[1])), typeof(JwtPayload));

                    var rawSignature = segments[0] + '.' + segments[1];

                    validated = Verify(rawSignature, secret, segments[2]);
                }
                catch (Exception exception)
                {
                    validated = false;
                }
            }
            else
            {
                validated = false;
            }

            return jwtPayload;
        }
Example #2
0
        public static string EncodeToken(JwtPayload jwtPayload, string secret)
        {
            const string algorithm = "HMAC256";

            var header = new JwtHeader
            {
                typ = "JWT",
                alg = algorithm
            };

            var jwt = Base64Encode(JsonConvert.SerializeObject(header)) + "." + Base64Encode(JsonConvert.SerializeObject(jwtPayload));

            jwt += "." + Sign(jwt, secret);

            return jwt;
        }
        public IHttpActionResult Login([FromBody] DataModel.SecurityModel.Login _user)
        {
            const string errorMessage = "Invalid User Name / Password";

            var response = new HttpResponseMessage();

            users user = _userRepository.FindBy(x => x.userName == _user.userName).SingleOrDefault();

            if (user != null)
            {
                if (user.userPassword == _user.userPassword)
                {
                    string secret = TokenManager.Base64Encode(SecurityConstants.KeyForHmacSha256);

                    var currentTime =
                        (long)(DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime()).TotalSeconds;

                    var payload = new JwtPayload
                    {
                        iss = SecurityConstants.TokenIssuer,
                        sub = user.id.ToString(),
                        iat = currentTime,
                        exp = currentTime + 604800
                    };

                    string jwt = TokenManager.EncodeToken(payload, secret);

                    response.StatusCode = HttpStatusCode.OK;
                    response.Headers.Add("Authorization", jwt);

                    return ResponseMessage(response);
                }
            }

            response.StatusCode = HttpStatusCode.Unauthorized;
            response.ReasonPhrase = errorMessage;

            return ResponseMessage(response);
        }