Monday, February 29, 2016

WSO2 App Manager - Using JWT to send application user details to Backend Application

JSON Web Token (JWT) is a means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature (JWS) and/or encrypted using JSON Web Encryption (JWE).

For more information regarding JWT configuration with WSO2 AppM please refer below articles.

How to Configure samples:

Here I'm trying to provide a sample .NET backend application which decode the JWT token and retrieve the Last name 

To test this, you need to build this application and host the binary in a IIS server. Then create a WebApp in WSO2 AppM and provide the relevant url as the backend url.  Also do not forget to add the 'lastname' as a claim mapping as explained in above articles.

Sample code to read header token values using ASP.NET (with C#.NET back end)

namespace Sample{
 public partial class _Default: System.Web.UI.Page {
  protected void Page_Load(object sender, EventArgs e) {
   try {
    if (!Page.IsPostBack) {
     //store the value of claim :
     String lastName = "";

     //check for X-JWT-Assertion parameter
     if (Request.Headers["X-JWT-Assertion"] != null) {
      reqHeader = Request.Headers["X-JWT-Assertion"].ToString();
      string[] stringSeperator = new string[] {
      //split the encoded string and send to decode
      string decodedHeader = base64Decode(reqHeader.Split(stringSeperator, StringSplitOptions.None)[1].ToString() + "=");
      decodedHeader = decodedHeader.Replace("\"", "'"); //format json string
      JObject obj = new JObject();
      obj = (JObject) JsonConvert.DeserializeObject(decodedHeader); //Decode Object

      if (obj[""] != null) {
       lastName = obj[""].ToString();

   } catch (Exception ex) {
    //lblErr.Text = "Error: " + ex.Message;


  //base64 decodes the given encoded string (data :encoded string)
  public string base64Decode(string data) {
   try {
    System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
    System.Text.Decoder utf8Decode = encoder.GetDecoder();
    byte[] todecode_byte = Convert.FromBase64String(data);
    int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
    char[] decoded_char = new char[charCount];
    utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
    string result = new String(decoded_char);
    return result;
   } catch (Exception e) {
    throw new Exception("Error in base64Decode" + e.Message);

More samples: 

No comments:

Post a Comment