Implementing Basic and JWT Token authentication with C# .NET


Authentication is probably the first thing you will encounter when building a secure Enterprise application and understanding how you can authenticate your application with different authentication protocols including third party authentication flows is really important. Whether you are building an app with ASP.NET, ASP.NET Core, WPF, UWP, Xamarin.Forms Xamarin Android, Xamarin iOS or .NET Core, all these frameworks provides
client side networking libraries managed under System.NET namespace. Among all the classes HttpClient has significant important. It can handle both HTTP and HTTPS connections. The beauty of this class is that it provides both hight level api and low level modification options to work with HTTP connections and you can make any modification  within the pipeline like handling HTTP message request/response, filtering, certificates, authorization and much more.

In a nutshell, over HTTP most of the times you will work with two kinds of authentication:
1) Basic (username/password based)
2) Token (access token and/or refresh token based)

Both of these authentication categories require that http request contains Authorization header. The format of the Authorization header in HTTP request is:

Authorzation: {schema} {parameter}

where schema is type of authentication being used and parameter is the value of the credentials/token.

Basic Authentication

 Basic authentication requires an http request to have an Authorization header key with value of Basic and base64 encoded string containing username and password separated by colon(:). Below here take a look at HTTP Request that has a Basic authentication header:

Fiddler Http Request composition

In case of Basic authentication, the value for schema is "Basic" and parameter is base64 representation of username and password separated by collon (":") like administrator:password

Note: In modern browsers and utilities you can also pass credential in url  and they will automatically convert it into authorization header where the credentials are base64 encoded string. The format is:

https://{username}:{password}@{hostname/}

Take a look at the url of the http request:
Fiddler Http Request with credentials in URL
Now look at the response about the request sent by fiddler, fiddler automatically converted url into Basic Authorization header when sending http request.
Http request header and JSON response from Windows IoT Server

Token Based Authentication

Token based authentication are widely used in OAuth, OpenId and access key based authentication. They also require that http request header contain Authorization key with value Bearer {Token} where Token is the value secret key of api token.

Lets see an example of usage of Token based authentication:

Token based Bearer authentication
Http reponse against bearer authentication

Basic authentication in C#

Lets see how to implement Basic authentication in C#. Initialize HttpClient class with default constructor. Get a byte array by passing string parameter containing username and password separated by colon (:) to static method GetBytes defined in Encoding class and overridden by ASCII class. Get an instance of AuthenticationHeaderValue class by calling its two parameter constructor passing in Basic as first parameter and credentials byte array as second parameter then assign the instance to Authorization property of DefaultRequest property under HttpClient instance (or simply htpClient.DefaultRequestHeaders.Authorization). Finally, call GetAsync instance method of httpClient object to get HttpResponseMessage. You can see authentication success result under HttpRespnseMessage response object's StatusCode enum received from GetAsync() method.

If you have an https website and using self-signed signed certificate checkout code here on how to ignore self-signed certificated exceptions.

Token Authentication in C#

Lets see how to implement Bearer authentication in C#. As discussed earlier, Bearer Authentication is token based where you will receive an access token from either OAuth2.0 or OpenId endpoint or some Auth providers might directly provide you an API Secret Key which is a token.. Once you have the JWT token, your simply need to pass it on the Authorization header with Bearer scheme (no need to convert token to base64 encoded string).

In C#, initialize HttpClient class with default constructor. Get an instance of AuthenticationHeaderValue class by calling its two parameter constructor passing in Bearer as first parameter and token as second parameter then assign the instance to Authorization property of DefaultRequest property under HttpClient instance (or simply htpClient.DefaultRequestHeaders.Authorization). Finally, call GetAsync instance method of httpClient object to get HttpResponseMessage. You can see authentication success result under HttpRespnseMessage response object's StatusCode enum received from GetAsync() method.

If you have an https website and using self-signed signed certificate checkout code here on how to ignore self-signed certificated exceptions.

Just a last note, if you have an https website and get certificate related exception when running the code above you then register a certificate validator callback to return true.

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

Comments

  1. FL Studio Crack is the latest powerful music production tool. ... Firstly, download the FL Studio Crack from the below setup button. FL Studio Crack Version

    ReplyDelete
  2. I just wanted to let you know that you are on my mind every single day of the year, especially today on Christmas. I hope you have the biggest smile today Christmas Wishes For Loved Ones

    ReplyDelete
  3. 06EF8AFA5CSamsonCD00807F5A26 November 2024 at 02:12

    DF90975319
    şov

    ReplyDelete
  4. 9C9C25BCF0Caitlin106263A8DB26 November 2024 at 07:09

    C73D829092
    beğeni

    ReplyDelete
  5. One of the essentials of Canada is its climate. Winters can be very cold, especially in the northern regions, with lots of snow and ice. Summers, however, can be warm and pleasant, especially in southern areas. Canadians are used to adapting to different weather conditions, making winter sports like skiing and ice hockey very popular.

    ReplyDelete
  6. Corteiz Clothing has emerged as a disruptive force. Known for its exclusivity, rebellious ethos, and powerful connection to youth culture, Corteiz (stylized as Crtz) has become a household name in the UK’s streetwear scene—and it's rapidly gaining global traction.

    ReplyDelete
  7. "I finally got my hands on one of the Flower Skate Deck tees — totally worth the hype. The details in the print are insane."

    ReplyDelete
  8. "I’ve noticed their drops sell out way too fast. Either they need to up production or make it more accessible to real fans, not just resellers."

    ReplyDelete
  9. Corteiz, also stylized as CRTZ. Founded in London by Clint Ogbenna, better known as Clint419, CRTZ has quickly grown from an underground label into a cultural phenomenon, known for its exclusivity, rebellious branding, and deep connection with youth identity. It’s not just fashion – it’s a movement.

    ReplyDelete
  10. Elle met un point d’honneur à offrir un service rapide et efficace.

    ReplyDelete
  11. kanye west klamotten particularly the Yeezy Boost 350, became a cultural phenomenon. The collaboration with Adidas blended Kanye's design vision with the brand’s technical capabilities, such as Boost technology

    ReplyDelete
  12. Spiders can produce silk from special glands called spinnerets. They use silk to make webs, catch prey, protect eggs, and even travel through the air. Spider silk is very strong and flexible, stronger than steel of the same thickness.

    ReplyDelete
  13. Kanye's influence on streetwear has reshaped the way people view celebrity fashion. Among his many contributions, one standout piece has gained iconic status: the Kanye West pullover. More than just a garment, it’s a symbol of a larger movement that blends minimalism, utility, and high fashion.

    ReplyDelete
  14. Comme des Garçons is known for its experimental and artistic style. The brand often uses asymmetry, layering, and oversized shapes. Kawakubo’s philosophy is to create fashion as a form of art rather than just clothes.

    ReplyDelete
  15. The quality of Godspeed Clothing is unmatched. From stitching to fabric, everything feels premium and built to last.

    ReplyDelete
  16. Sisters Seekers encourages personal growth. Members learn new skills, develop confidence, and explore their passions. The group helps women overcome challenges and reach their goals.

    ReplyDelete
  17. This hoodie is popular for its streetwear-inspired style. It pairs well with jeans, joggers, or leggings. Many fashion enthusiasts wear it as a statement piece, often layering it with jackets or accessories to enhance the overall look.

    ReplyDelete
  18. Alchemy used many symbols and secret codes. Colors, shapes, and mystical signs represented different elements and spiritual stages. Alchemists often wrote in riddles to keep their knowledge secret.

    ReplyDelete
  19. godspeed clothing has attempted to intersect its fashion with music, urban art, and cultural movements. For instance, they’ve released limited drops tied to The LOX, a hip-hop group.

    ReplyDelete
  20. Many Pokémon Centers have shops inside. Trainers can buy items like Poké Balls, potions, and berries. These supplies help trainers in battles and on their adventures.

    ReplyDelete
  21. The style of Trapstar often includes graphic hoodies, t-shirts, jackets, and accessories. Their designs often feature bold logos, prints, and messages that reflect street culture and individuality. The aesthetic is edgy and often appeals to young people.

    ReplyDelete
  22. The hoodies are made from soft and durable materials. Many use cotton and polyester blends that keep the wearer warm and comfortable.

    ReplyDelete
  23. Black, grey, and white are the most common colors for Chrome Hearts hoodies. Occasionally, limited-edition versions come in brighter colors or tie-dye patterns, which collectors often seek.

    ReplyDelete
  24. I've been collecting Kapital for a few years now, and the quality is always top tier. The denim especially — fades beautifully and lasts forever.

    ReplyDelete
  25. Lattafa was founded in the 1980s by Sheikh Shahid Ahmad and Shoaib Iqbal. The brand began as a vision to deliver high-quality, luxurious fragrances to local customers in the Middle East. Over the years, this vision has grown into a globally recognized brand, exporting to major GCC countries and beyond. Since its official launch in 1992, Lattafa has continued to honor its founders' legacy by crafting perfumes that capture personality, leave lasting impressions, and evoke positive emotions.

    ReplyDelete
  26. Judaism also has a tradition of seven heavens called “Shamayim.” These are seen as spiritual realms, each with its own purpose and divine presence. The idea appears in some Jewish mystical texts.

    ReplyDelete
  27. Made primarily from durable denim fabric, the hoodie also includes soft cotton or fleece lining inside. This combination ensures both comfort and longevity, making it suitable for daily wear.

    ReplyDelete
  28. Essentials hoodies are made from soft and high-quality materials, often a blend of cotton and polyester.

    ReplyDelete
  29. Sp5der Blue stands out as a signature element that blends bold aesthetics with cultural relevance. This vibrant hue isn't just a color—it's become a statement in fashion, symbolizing confidence, creativity, and rebellion against the ordinary.

    ReplyDelete
  30. Stone Island kurtka often has a simple but recognizable design. Features like the compass patch on the sleeve and functional pockets make the jacket stand out. The design focuses on both fashion and comfort.

    ReplyDelete
  31. “Charles Jeffrey’s use of color and texture is next level. It’s like Vivienne Westwood meets fantasy RPG — in the best way.”

    ReplyDelete
  32. Cough syrup that contains codeine and promethazine has been around for decades. Codeine is an opioid, and promethazine is an antihistamine often used to treat nausea or allergies. When combined, they create a sedative effect, often leading to euphoria, drowsiness, and a slowed sense of reality

    ReplyDelete
  33. "There’s just something about that Trapstar logo — clean, edgy, and iconic. I love how the hoodie pairs well with everything from cargos to joggers."

    ReplyDelete
  34. The brand's logo features a stylized palm tree, symbolizing unity and the shared love within the Pink Palm Puff community.

    ReplyDelete
  35. Eme Studios UK (often seen as Eme Studios) is a clothing brand operating in the UK market, selling streetwear and lifestyle apparel. Their product range includes hoodies, tracksuits, jackets, beanies, and casual wear aimed at people who want both style and comfort.

    ReplyDelete
  36. “First time hearing about Corteiz from this blog. Just checked out their site—now I get why people are obsessed. Super minimal but powerful designs.”

    ReplyDelete
  37. Sp5der has quickly become a staple in street fashion. The Sp5der Store, both online and in select physical locations, has emerged as the go-to destination for fans of edgy, artistic, and unapologetically bold clothing.

    ReplyDelete
  38. "A little on the pricey side, but honestly worth every penny. The stitching and quality feel luxury-grade. You can tell it’s not mass-produced."

    ReplyDelete
  39. Trapstar to jedna z tych marek, która stale podnosi poprzeczkę. Fajne wzory, dobra jakość i świetne dopasowanie. Na pewno jeszcze nie raz kupię coś z ich kolekcji!

    ReplyDelete
  40. „Ein oft unterschätzter Bereich! Stellvertretungen übernehmen oft große Verantwortung, bekommen aber selten die Anerkennung, die sie verdienen. Vielleicht wäre mehr Transparenz über ihre Aufgaben hilfreich.“

    ReplyDelete
  41. Life taught Matty Boy to be patient, resilient, and brave. Every challenge became a stepping stone toward his best self.

    ReplyDelete
  42. Designed for today’s trendsetters, Kroen Clothing combines minimal style with bold accents, giving you the perfect wardrobe essentials.

    ReplyDelete
  43. Many entries in HMDD focus on cancer-related microRNAs. Researchers use this database to explore which miRNAs are linked to tumor growth, metastasis, and treatment resistance.

    ReplyDelete
  44. Sp5der is a streetwear brand founded in 2019 by American rapper Young Thug, whose real name is Jeffery Williams. Initially launched in Atlanta, Georgia, the brand is now based in Los Angeles, California. Sp5der emerged as a visual commentary on the pulse of the South, reflecting a loud, boisterous sense of self-expression inspired by Atlanta and the community that shapes it.

    ReplyDelete

Post a Comment

Popular posts from this blog

.NET Core 3 officially comes to Windows IoT Core

Setting up CI and CD pipeline in Azure DevOps for ASP.NET Core and Azure Web Apps

Microsoft Azure DevOps : A Complete CI & CD solution in the cloud

Securing Powershell Scripts with Code-Signing Certificate

Setting up Free Custom Domain on Microsoft Azure Web App Service

Understanding Powershell ExecutionPolicy and securing Powershell CmdLets/Scripts with Code-Signing Certificate

Microsoft Azure Blob Storage - Managing Blobs and storage containers from C#

Xamrin Android Push Notification using Firebase Cloud Messaging

Fundamental of Powershell Scripting