24 April 2023

Microsoft Authentication Library (MSAL) Overview


The Microsoft Authentication Library (MSAL) is a powerful library designed to simplify the authentication process for applications that connect to Microsoft services like Azure Active Directory (Azure AD), Microsoft Graph, and Office 365. MSAL is available for various platforms, including .NET, Java, Python, and JavaScript.

In this article, we will explore how MSAL works, how to implement it using code samples, and why it is better than its predecessor, the Azure Active Directory Authentication Library (ADAL).

How MSAL Works

MSAL provides a simple and consistent API for authenticating users and acquiring access tokens to access Microsoft services. It abstracts the authentication process by handling the complex details of authentication protocols like OAuth 2.0 and OpenID Connect, allowing developers to focus on building their application logic.

  1. Authentication Request: The application initiates an authentication request by calling the MSAL API with the required parameters like client ID, redirect URI, and scopes.
  2. User Authentication: MSAL redirects the user to the Microsoft sign-in page to enter their credentials. If the user is already authenticated, they will not need to sign in again.
  3. Access Token Retrieval: After successful authentication, MSAL exchanges the authorization code for an access token. The access token is then cached by MSAL for later use.
  4. Token Renewal: MSAL also handles the process of renewing access tokens when they expire. If the user is still authenticated, MSAL can silently renew the token without prompting the user to sign in again.
  5. Token Management: MSAL provides a built-in token cache to manage access tokens securely. It also supports the revocation of access tokens in case of a security breach.

Here is an example of how MSAL works using C#:

string[] scopes = { "user.read" }; string clientId = "your-client-id"; string redirectUri = "http://localhost/myapp"; IPublicClientApplication app = PublicClientApplicationBuilder .Create(clientId) .WithRedirectUri(redirectUri) .Build(); AuthenticationResult result = await app.AcquireTokenInteractive(scopes) .ExecuteAsync();

https://gist.github.com/cjvandyk/49c9e5b467d2e9e38bb4f3bd14f71a26

In the example above, we create a new instance of the PublicClientApplicationBuilder and specify the clientId and redirectUri. We then call the AcquireTokenInteractive method to initiate the authentication process with the specified scopes. After the user is authenticated, we can use the result.AccessToken property to retrieve the access token.

MSAL also supports a variety of authentication scenarios, including device-based authentication like setting up your Roku, conditional access policies, and multi-factor authentication.

Here is an example of how to implement MSAL using JavaScript:

const msalConfig = { auth: { clientId: 'your-client-id', authority: 'https://login.microsoftonline.com/common', redirectUri: 'http://localhost:3000', }, cache: { cacheLocation: 'localStorage', storeAuthStateInCookie: true, } }; const loginRequest = { scopes: ["user.read"] }; const pca = new msal.PublicClientApplication(msalConfig); async function signIn() { const authResult = await pca.loginPopup(loginRequest); console.log('Access Token: ', authResult.accessToken); }

https://gist.github.com/cjvandyk/25367b7d0ffb738ca10b46ec5d91569d

In the example above, we define the MSAL configuration using the msalConfig object, which includes the clientId, authority, and redirectUri. We also define the loginRequest object with the requested scopes. We then create a new instance of the PublicClientApplication and call the loginPopup method to initiate the authentication process. After the user is authenticated, we can use the authResult.accessToken property to retrieve the access token.

Conclusion

In conclusion, the Microsoft Authentication Library (MSAL) is a powerful authentication library that simplifies the authentication process for applications that connect to Microsoft services like Azure AD, Microsoft Graph, and Office 365. It provides a simple and consistent API, abstracting the complexity of authentication protocols like OAuth 2.0 and OpenID Connect. MSAL is available for various platforms, including .NET, Java, Python, and JavaScript, and it has several advantages over its predecessor, Azure Active Directory Authentication Library (ADAL), including cross-platform support, better performance, improved user experience, and support for modern authentication features.

/Code forth
C


19 April 2023

Asymmetric Encryption Primer

Introduction

Asymmetric encryption, also known as public-key encryption, is a type of encryption that uses two different keys to secure the transmission of data. One key, the public key, is shared with anyone who wants to send encrypted messages to the owner of the other key, the private key. Asymmetric encryption is widely used in secure communication protocols such as SSL/TLS, SSH, S/MIME, and PGP.

PGP (Pretty Good Privacy) is a popular encryption software program that uses asymmetric encryption to secure the transmission of data. PGP was developed in 1991 by Phil Zimmermann, a software engineer and privacy advocate. At the time, the US government had strict regulations on the export of encryption technology, and Zimmermann was concerned about the government's ability to monitor private communication. He developed PGP as a way for individuals to communicate privately and securely.

PGP made asymmetric encryption more accessible and easy to use for the general public. Prior to PGP, asymmetric encryption was mostly used by governments and large corporations, and the technology was not widely understood by the general public. PGP's user-friendly interface made it easy for individuals to encrypt and decrypt messages without needing a deep understanding of the underlying technology.

How Asymmetric Encryption Works

In asymmetric encryption, a pair of different keys is used. One key is used for encryption, and the other is used for decryption. These keys are called a public key and a private key.

The public key can be shared with anyone, while the private key is kept secret by the owner. The owner of the private key can use it to decrypt any data encrypted with the corresponding public key. The use of two different keys provides a higher level of security, as the private key is never shared and only the owner can use it to decrypt data.

Asymmetric encryption involves a few steps:

  1. Key Generation: The first step in asymmetric encryption is generating the key pair. The public and private keys are mathematically related but are completely different from each other. The public key is created from the private key using a mathematical algorithm.
  2. Data Encryption: Once the key pair is generated, the sender uses the recipient's public key to encrypt the data. The data is transformed into an unreadable format that can only be deciphered using the recipient's private key.
  3. Data Transmission: The encrypted data can then be sent over an insecure network, such as the internet, to the recipient.
  4. Data Decryption: The recipient uses their private key to decrypt the data. As the private key is never shared, only the recipient can decrypt the data.

Message Integrity Verification

To ensure the integrity of the data, the sender can use a digital signature. The digital signature is created by using the sender's private key to encrypt a message digest, which is a unique summary of the data. The recipient can then use the sender's public key to decrypt the message digest and compare it to the original data to verify its authenticity.

Advantages of Asymmetric Encryption

Asymmetric encryption has several advantages over symmetric encryption, including:

  1. Security: Asymmetric encryption is more secure than symmetric encryption because the private key is never shared. This reduces the risk of a security breach as it is difficult for hackers to intercept the private key.
  2. Key Exchange: In symmetric encryption, a secure key exchange must be established to exchange the key between the sender and the recipient. With asymmetric encryption, only the public key needs to be exchanged, reducing the risk of a key exchange attack.
  3. Scalability: Asymmetric encryption is highly scalable, as only one public key needs to be shared with multiple recipients.

Conclusion

Asymmetric encryption, with the help of PGP, has become a powerful and secure encryption method that is widely used in secure communication protocols. By using two different keys for encryption and decryption, asymmetric encryption provides a higher level of security than symmetric encryption.

PGP, in particular, played a significant role in popularizing asymmetric encryption among the general public. Before PGP, the technology was mainly used by governments and large corporations. PGP's user-friendly interface and accessibility made it easy for individuals to encrypt and decrypt messages without needing a deep understanding of the underlying technology.

Phil Zimmermann's legal battles over PGP's classification as a munition also helped raise awareness about the importance of privacy and the need for secure communication in the digital age. PGP was eventually widely available for download, and it has since become a popular tool for secure communication, email encryption, file encryption, and digital signatures.

In conclusion, asymmetric encryption provides a higher level of security than symmetric encryption, and PGP played a crucial role in making this technology accessible and easy to use for the general public. As technology continues to advance, asymmetric encryption remains an essential tool for securing sensitive data and communication. 

/Code forth
C



13 October 2022

What do I use?

I posted a short list of my most used tools at

http://blog.cjvandyk.com/p/essentials.html

This is not an exhaustive list but will be growing over time so be sure to bookmark it and check back every so often. 😎


Code forth
C


23 February 2022

How do I - Get a certificate thumbprint from my local certificate store?

Using Powershell it's pretty easy to get your thumbprint.  To get the list of all certificates in the local machine wide store, use:

Get-ChildItem -Path Cert:LocalMachine\MY

To get the list of all certificates in for the currently logged on user, use:

Get-ChildItem -Path Cert:CurrentUser\MY

Happy coding!
C


22 February 2021

What does the /:x: and /r mean in SharePoint Online sharing URLs?

Ever wondered what the new SharePoint Online URLs are all about?  Take for example https://cjvandyk.sharepoint.us/:x:/r/sites/Site1...
What exactly does the /:x: and the /r between the domain and the /sites mean?  Well wonder no more...

/:b: PDF
/:f: Folder
/:i: Image
/:o: OneNote
/:p: PowerPoint
/:t: Text
/:u: Undefined
/:v: Video
/:w: Word
/:x: Excel

Happy coding...
C

25 January 2021

Extensions 2.0.1 Major version update released!

On Friday morning a major version update of Extensions was released.  The new version brings with it a TON of new extension methods for C# such as:

  1. Most notable is the .Save() and .Load() methods added to the System.Object class.  This allows any object to be serialized to and from disk very rapidly e.g.:

    (object)MyClass.Save(<FilePath>);

    and

    (MyClassDefinition)MyClass = (object)MyClass.Load(<FilePath>);

  2. A series of extensions was added to the System.Double class allowing any number cast as a double to be quickly converted between binary data sizes e.g.:

    double SizeInTB = 2;
    double SizeInKB = SizeInTB.ToKB(Constants.NumberByte.TB);

    Which will return 2,147,483,648 i.e. the number of KB in 2 TB.

  3. A series of extensions was added to both the System.String and Sytem.Text.StringBuilder classes that make it easy to validate strong passwords e.g.:

    string MyPassword = Console.Readline();
    if (MyPassword.IsStrong())
    {
        //Pass.  Input is a strong password.
    }
    else
    {
        //Fail.  Input is NOT a strong password.
    }

    Even better is if you want to exclude say symbols or special characters requiring users to only use upper case, lower case and numbers, you can override the default parameters e.g.:

    if (MyPassword.IsStrong(true, true, true, false))

    The component methods of .IsStrong() can also be used independently e.g.

    MyPassword.HasUpper()
    MyPassword.HasLower()
    MyPassword.HasNumeric()
    MyPassword.HasSymbol()


  4. A series of extensions was added to both the System.String and Sytem.Text.StringBuilder classes that make it easy to validate if a string is a valid US Zip code e.g.:

    MyString.IsZipCode()

    The method handles both 5 digit and 9 digit zip codes.

  5. Extension methods was also added to make other string based operations easier e.g.

    MyString.IsLower()
    MyString.IsUpper()

  6. Extension methods from previous versions were enhanced by adding the option to ignore white space as part of these methods:

    MyString.IsAlphabetic()
    MyString.IsAlphaNumeric()
    MyString.IsNumeric()

  7. On the lighter side of things, if you've ever wondered what it was like to live in the Morse Code era, you can leverage to silly methods to see for yourself like this:

    "My message I want to send".ToMorseCode().MorseCodeBeep();

For a more detail of what Extensions offer, see:







Add Extensions to your toolbox and make your coding life a little easier.  

Happy coding
C

Microsoft Authentication Library (MSAL) Overview

The Microsoft Authentication Library (MSAL) is a powerful library designed to simplify the authentication process for applications that conn...