public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            //first try to get the client details from the Authorization Basic header
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                //no details in the Authorization Header so try to find matching post values
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret))
            {
                context.SetError("client_not_authorized", "invalid client details");
                return(Task.FromResult <object>(null));
            }

            var dataLayer   = new RepoManager(new DataLayerDapper()).DataLayer;
            var audienceDto = dataLayer.GetAudience(clientId);

            if (audienceDto == null || !clientSecret.Equals(audienceDto.Secret))
            {
                context.SetError("unauthorized_client", "unauthorized client");
                return(Task.FromResult <object>(null));
            }

            context.Validated();
            return(Task.FromResult <object>(null));
        }
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId = data.Properties.Dictionary.ContainsKey("audience") ? data.Properties.Dictionary["audience"] : null;

            if (string.IsNullOrWhiteSpace(audienceId) || audienceId.Length != 32)
            {
                throw new InvalidOperationException("audience missing from AuthenticationTicket.Properties");
            }

            var dataLayer = new RepoManager(new DataLayerDapper()).DataLayer;

            var audienceDto = dataLayer.GetAudience(audienceId);

            if (audienceDto == null)
            {
                throw new InvalidOperationException("invalid_client");
            }

            var keyByteArray = Convert.FromBase64String(audienceDto.Secret);
            var signingKey   = new HmacSigningCredentials(keyByteArray);

            var issued  = data.Properties.IssuedUtc;
            var expires = data.Properties.ExpiresUtc;

            var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);

            var handler = new JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            return(jwt);
        }