Sunday, June 21, 2020

Sample api call using Azure AD authentication

This post explains a very nice sample app which first authenticates a user with azure ad, then retrieves a temporary access token for the user and finally calls an api (secured with azure ad authentition) using the retrieved access token

https://stackoverflow.com/questions/39206370/add-authentication-token-to-ajax-call-for-a-web-api-secured-using-azure-active-d

<html>
    <head>
        <title>Minimal sample using ADAL.JS</title>
        <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.11/js/adal.min.js"></script>
    </head>
    <body>
        <p>
            <!-- #2: Use ADAL's login() to sign in -->
            <a href="#" onclick="authContext.login(); return false;">Log in</a> |
            <a href="#" onclick="authContext.logOut(); return false;">Log out</a>
        </p>

        <script type="text/javascript">

            // #1: Set up ADAL
            var authContext = new AuthenticationContext({
                clientId: 'c24f035c-1ff6-4dfa-b76d-c75a29ad2c3c',
                postLogoutRedirectUri: window.location
            });

            // #3: Handle redirect after token requests
            if (authContext.isCallback(window.location.hash)) {

                authContext.handleWindowCallback();
                var err = authContext.getLoginError();
                if (err) {
                    // TODO: Handle errors signing in and getting tokens
                }

            } else {

                // If logged in, get access token and make an API request
                var user = authContext.getCachedUser();
                if (user) {

                    console.log('Signed in as: ' + user.userName);

                    // #4: Get an access token to the Microsoft Graph API
                    authContext.acquireToken(
                        'https://graph.microsoft.com',
                        function (error, token) {

                            // TODO: Handle error obtaining access token
                            if (error || !token) { return; }

                            // #5: Use the access token to make an AJAX call
                            var xhr = new XMLHttpRequest();
                            xhr.open('GET', 'https://graph.microsoft.com/v1.0/me', true);
                            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
                            xhr.onreadystatechange = function () {
                                if (xhr.readyState === 4 && xhr.status === 200) {
                                    // TODO: Do something with the response
                                    console.log(xhr.responseText);
                                } else {
                                    // TODO: Do something with the error 
                                    // (or other non-200 responses)
                                }
                            };
                            xhr.send();
                        }
                    );
                } else {

                    console.log('Not signed in.')
                }
            }
        </script>
    </body>
</html>

Azure AD authentication token format

Temporary authentication tokens generated when a user tries to log in using azure ad have the following format

{ "typ": "JWT", "alg": "RS256", "kid": "X5eXk4xyojNFum1kl2Ytv8dl..." }.{ "iss": "https://contoso0926tenant.b2clogin.com/c64a4f7d-3091-4c73-a7.../v2.0/", "exp": 1549651031, "nbf": 1549647431, "aud": "f2a76e08-93f2-4350-833c-965...", "oid": "1558f87f-452b-4757-bcd1-883...", "sub": "1558f87f-452b-4757-bcd1-883...", "name": "David", "tfp": "B2C_1_signupsignin1", "nonce": "anyRandomValue", "scp": "read", "azp": "38307aee-303c-4fff-8087-d8d2...", "ver": "1.0", "iat": 1549647431 }.[Signature]

More information about requesting the tokens can be found at https://docs.microsoft.com/en-us/azure/active-directory-b2c/access-tokens

Monday, June 15, 2020

Powershell - Unable to download from URI 'https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409'

To install SQLServer module in powershell we need to add the nuget package provider first with command:

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force

 
While trying to install this nuget package provider I was getting an error like so:

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201
-Force
WARNING: Unable to download from URI 'https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409' to ''.
WARNING: Unable to download the list of available providers. Check your internet connection.
Install-PackageProvider : No match was found for the specified search criteria for the provider 'NuGet'. The package provider requires 'PackageManagement'
and 'Provider' tags. Please check if the specified package has the tags.
At line:1 char:1
+ Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (Microsoft.Power...PackageProvider:InstallPackageProvider) [Install-PackageProvider], Exception
    + FullyQualifiedErrorId : NoMatchFoundForProvider,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackageProvider  


1. Open Powershell (As Admin)

2. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

3. Try it again!

Regex Email validation in c# dot net core

 Use this regex /^_?[a-zA-Z0-9]([a-zA-Z0-9]*[._+-])*[a-zA-Z0-9_]+@(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))*\.[A-...