Single Sign-On Implementation in VB.NET for ZenDesk

If you would like your users to get automatically authenticated with ZenDesk, why not create a single sign-on method using VB.NET (ASP.NET) and the JWT – web authentication method?

zendesk-sso-1

Here are the steps of the single sign-on authentication process:

  1. An unauthenticated user (not already logged in) navigates to your Zendesk URL (for example, https://mycompany.zendesk.com/).
  2. The Zendesk SSO mechanism recognizes that SSO is enabled and that the user is not authenticated.
  3. The user is redirected to the remote login URL configured for the SSO settings (for example, https://mycompany.com/zendesk/sso).
  4. A script on your side authenticates the user using your proprietary login process.
  5. Your script builds a JWT request that contains the relevant user data.
  6. You redirect the customer to the Zendesk endpoint at https://mycompany.zendesk.com/access/jwt with the JWT payload.
  7. Zendesk parses the user detail from the JWT payload and then grants the user a session.

https://support.zendesk.com/hc/en-us/articles/203663816-Setting-up-single-sign-on-with-JWT-JSON-Web-Token-

First, create an ASHX handler which will handle all sign-in request. I have named mine SSO.ASHX. The link to direct your users to Zendesk should be: https://website/SSO.ashx.

Your SSO.ashx class:

<%@ WebHandler Language="VB" Class="SSO" %>

Imports System
Imports System.Web

Public Class SSO : Implements IHttpHandler, System.Web.SessionState.IRequiresSessionState


    Private Const SHARED_KEY As String = "your token"
    Private Const SUBDOMAIN As String = "your zendesk subdomain"

    Public Sub ProcessRequest(ByVal context As  _
            System.Web.HttpContext) Implements _
            System.Web.IHttpHandler.ProcessRequest
        Dim t As TimeSpan = (DateTime.UtcNow - New DateTime(1970, 1, 1))
        Dim timestamp As Double = CDbl(t.TotalSeconds)

        Dim payload As Dictionary(Of String, Object) = New Dictionary(Of String, Object)()

        ''get user name and email based on session id
        Dim d As New DataLayer
        Dim strEmail As String = d.GetUserEmail(context.Session("ClientID"), context.Session("ID"))
        Dim strName As String = d.GetUserFullName(context.Session("ClientID"), context.Session("ID"))
        Dim strClientName As String = d.GetClientName(context.Session("ClientID"))
        payload.Add("iat", timestamp)
        payload.Add("jti", System.Guid.NewGuid().ToString())
        payload.Add("name", strName)
        payload.Add("email", strEmail)
        payload.Add("external_id", context.Session("ID"))
        payload.Add("organization", strClientName)
        payload.Add("role", "user")


        Dim token As String = JWT.JsonWebToken.Encode(payload, SHARED_KEY, JWT.JwtHashAlgorithm.HS256)
        Dim redirectUrl As String = "https://" + SUBDOMAIN + ".zendesk.com/access/jwt?jwt=" + token

        Dim returnTo As String = context.Request.QueryString("return_to")

        If (returnTo IsNot Nothing) Then
            redirectUrl += "&return_to=" + HttpUtility.UrlEncode(returnTo)
        End If

        context.Response.Redirect(redirectUrl)
    End Sub

    Public ReadOnly Property IsReusable() As Boolean _
            Implements System.Web.IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class
Advertisements

How to create a JSON POST request from a GET method

Let’s say you find a security hole in your system from old developers – leaving one of your webservices exposed:

http://mywebservice/MyService.asmx/SendEmail?Username=1234&Password=1224!&EmailFrom=no-reply@carra-lucia-ltd.co.uk&EmailTo=carra_lucia@hotmail.com&Subject=MySubject&Message=Dear%20Administrator,test%20mail%20here

Now how would you transform this into a POST string with JSON?


  var myURL = "http://mywebservice/MyService.asmx/SendEmail";
        var dataToUse = $.parseJSON('{"Username": "1234","Password":"1224!","EmailFrom":"no-reply@carra-lucia-ltd.co.uk","EmailTo":"carra_lucia@hotmail.com","Subject":"MySubject","Message":"' + msg + '"}');
        $.ajax({
            type: "POST",
            url: myURL,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            data: dataToUse,
            crossDomain: true,
            success: function (response) {
                //email was sent
                alert("Email has been sent successfully!");
            },
            error: function (jqXHR, error, errorThrown) {
                if (jqXHR.status && jqXHR.status == 400) {
                    alert(jqXHR.responseText);
                } else {
                    alert("Something went wrong. We could not send your email.");
                }
            }
        });

MySubject

Using jQuery ajax to call asmx webservice methods

One imprtant distinction is what I mean by a JSON object and JSON format.  A JSON object is an object that can be used by javascript

var o = {data: 'value'};
alert (o.data); // this works as o is an object

JSON format is simply a literal string that can be turned into a JSON object if we parse it

var f = "{data: 'value'}";
alert (f.data); // this won't work as f is just a string and string doesn't have a data property

The following code calls a webservice that has three different SayHello functions.

[WebMethod]
public string SayHello(string firstName, string lastName)
{
    return "Hello " + firstName + " " + lastName;
}

[WebMethod]
public string SayHelloJson(string firstName, string lastName)
{
    var data = new { Greeting = "Hello", Name = firstName + " " + lastName };

    // We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below)
    // SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName };

    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

    return js.Serialize(data);
}

[WebMethod]
public SayHello SayHelloObject(string firstName, string lastName)
{
    SayHello o = new SayHello();
    o.Greeting = "Hello";
    o.Name = firstName + " " + lastName;

    return o;
}

“SayHello” returns a string

“SayHelloJson” returns a string that is an object in JSON format

“SayHelloObject” returns an object.  The SayHello class is here

public class SayHello
{
    public string Greeting { get; set; }
    public string Name { get; set; }
}

I have added the comments inline on the code, but the examples cover calling all three types of webservice method, and they also cover getting simple text back and getting JSON objects back, and also sending parameters in form encoded formats and also JSON formats.

Enjoy

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="WebTest.ajax.test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        http://../Scripts/jquery-1.4.1.js
</head>
<body>
    <form id="form1" runat="server">
    

Example A

Example B

Example C

Example D

Example E
/* SayHello returns a string SayHelloJson returns a string that is an object in JSON format SayHelloObject returns an object [WebMethod] public string SayHello(string firstName, string lastName) { return "Hello " + firstName + " " + lastName; } [WebMethod] public string SayHelloJson(string firstName, string lastName) { var data = new { Greeting = "Hello", Name = firstName + " " + lastName }; // We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below) // SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName }; System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); return js.Serialize(data); } [WebMethod] public SayHello SayHelloObject(string firstName, string lastName) { SayHello o = new SayHello(); o.Greeting = "Hello"; o.Name = firstName + " " + lastName; return o; } public class SayHello { public string Greeting { get; set; } public string Name { get; set; } } */ $(document).ready(function () { // SayHello returns a string we want to display. Examples A, B and C show how you get the data in native // format (xml wrapped) as well as in JSON format. Also how to send the parameters in form-encoded format, // JSON format and also JSON objects. To get JSON back you need to send the params in JSON format. // Example A - call a function that returns a string. // Params are sent as form-encoded, data that comes back is text $.ajax({ type: "POST", url: "MyWebService.asmx/SayHello", data: "firstName=Aidy&lastName=F", // the data in form-encoded format, ie as it would appear on a querystring //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // if you are using form encoding, this is default so you don't need to supply it dataType: "text", // the data type we want back, so text. The data will come wrapped in xml success: function (data) { $("#searchresultsA").html(data); // show the string that was returned, this will be the data inside the xml wrapper } }); // Example B - call a function that returns a string. // Params are sent in JSON format, data that comes back is JSON $.ajax({ type: "POST", url: "MyWebService.asmx/SayHello", data: "{firstName:'Aidy', lastName:'F'}", // the data in JSON format. Note it is *not* a JSON object, is is a literal string in JSON format contentType: "application/json; charset=utf-8", // we are sending in JSON format so we need to specify this dataType: "json", // the data type we want back. The data will come back in JSON format success: function (data) { $("#searchresultsB").html(data.d); // it's a quirk, but the JSON data comes back in a property called "d"; {"d":"Hello Aidy F"} } }); // Example C - call a function that returns a string. // Params are sent as a JSON object, data that comes back is text $.ajax({ type: "POST", url: "MyWebService.asmx/SayHello", data: { firstName: 'Aidy', lastName: 'F' }, // here we are specifing the data as a JSON object, not a string in JSON format // this will be converted into a form encoded format by jQuery // even though data is a JSON object, jQuery will convert it to "firstName=Aidy&lastName=F" so it *is* form encoded contentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: "text", // the data type we want back, so text. The data will come wrapped in xml success: function (data) { $("#searchresultsC").html(data); // show the data inside the xml wrapper } }); // SayHelloJson returns a .net object that has been converted into JSON format. So the method still return a // string, but that string is an object in JSON format. It is basically an object within an object. We still // get the "d" property back as in Example B, but "d" is an object represented in JSON format itself. // Example D - call a function that returns a string that is an object in JSON format. // Params are sent in JSON format, data that comes back is a string that represents an object in JSON format $.ajax({ type: "POST", url: "MyWebService.asmx/SayHelloJson", data: "{ firstName: 'Aidy', lastName: 'F' }", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var myData = JSON.parse(data.d); // data.d is a JSON formatted string, to turn it into a JSON object // we use JSON.parse // now that myData is a JSON object we can access its properties like normal $("#searchresultsD").html(myData.Greeting + " " + myData.Name); } }); // SayHelloObject returns a typed .net object. The difference between this and Example D is that in Example D // the "d" property is an object in JSON format so we need to parse it to make it a JSON object. Here the // "d" property is already an actual JSON object so no need to parse it. // Example E - call a function that returns an object. .net will serialise the object as JSON for us. // Params are sent in JSON format, data that comes back is a JSON object $.ajax({ type: "POST", url: "MyWebService.asmx/SayHelloObject", data: "{ firstName: 'Aidy', lastName: 'F' }", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var myData = data.d; // data.d is a JSON object that represents out SayHello class. // As it is already a JSON object we can just start using it $("#searchresultsE").html(myData.Greeting + " " + myData.Name); } }); }); </form> </body> </html>

A Simple .NET Twitter API Wrapper Using LINQ

Fantastic piece of software!

Sean's Stuff

In the world of software demos, doing something with Twitter has replaced Hello World as the most common target of a demo.  At the risk of polluting the world with yet another chunk of code that does something with Twitter–I’d like to play around a bit with Silverlight charting and Twitter seems a great context for demoing what is possible.

But before I can start creating a Silverlight demo, I need a basic Twitter API wrapper in .NET.  So here’s a starting point–a simple example that uses LINQ to get a list of people that you follow.  This is a good starting point for later demos.

Twitter provides a simple REST API that lets you do basically everything you’d want to do using simple HTTP GET, POST and DELETE requests.

You can learn everything you need to know about the Twitter API at the Twitter API Wiki.

Basic Concepts

View original post 2,061 more words