public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType, out TokenResponse response)
        {
            SecurityToken token = null;
            response = new TokenResponse { TokenType = tokenType };

            var result = TryIssueToken(appliesTo, principal, tokenType, out token);
            if (result == false)
            {
                return false;
            }

            var ts = token.ValidTo.Subtract(DateTime.UtcNow);
            response.ExpiresIn = (int)ts.TotalSeconds;

            if (tokenType == TokenTypes.JsonWebToken || tokenType == TokenTypes.SimpleWebToken)
            {
                var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[tokenType];
                response.AccessToken = handler.WriteToken(token);
            }
            else
            {
                var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
                var sb = new StringBuilder(128);
                handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token);

                response.AccessToken = sb.ToString();
            }

            return result;
        }
 public static HttpResponseMessage CreateTokenResponse(this HttpRequestMessage request, TokenResponse response)
 {
     Tracing.Information("Returning token response.");
     return request.CreateResponse<TokenResponse>(HttpStatusCode.OK, response);
 }