.NET


Table of Contents:

Prerequisites
Dependencies
Note on hosting
.NET SDK Setup
Run the .NET Demo App
Setting up an outbound HTTP Proxy Server
.NET Code Analysis / Visual Studio Tutorial
Making a web app available as an authenticator for a mobile app


Prerequisites

Creating an app involves two basic steps:

  1. Register/create an app in the portal and obtain credentials (this is detailed in the 'Create a New App' menu section)
  2. Configure your app using an SDK, making use of these credentials

It is recommended that you first create a demo/test app with a redirect uri of http://127.0.0.1:5000/login in the portal, to enable you to run the SDK demo app and test the SDK functionality.

In the portal, when you create a new app, you will be issued with the Client ID and Client Secret credentials that you need to specify when building your app with the SDK. Note that your Client Secret will only be issued to you once so it must be grabbed when first displayed:

client secret

Client ID can then be copied at any time from the app settings screen:

app settings page

Note that you can control the Login Methods available (QR Code requires customer usage of the mobile app. While Browser Login enables logging in within the desktop browser, without the mobile app)

When creating your app in the portal, you also must specify a redirect_uri endpoint which comes from the url where you are hosting your app:

add app

The SDK will automatically create the redirect uri by appending '/login' to your url. You, of course, are in charge of what the base url of your app is. So it could be http://testapp.com/login, http://12.34.567.89:8080/login or http://127.0.0.1:5000/login as above. Note, however, that the MFA server will not accept 'localhost' as a base url.


Dependencies


Note that the SDK has the following dependencies:

  1. .NET framework 4.5.2 and above
  2. MS Visual Studio 2013 and above
  3. IdentityModel (NuGet package)

Note that, if you are using a version of the .NET framework earlier than 4.5.2, you should use version 1 of this SDK (available at https://github.com/miracl/maas-sdk-dotnet.git), as it supports v 1.x of the IdentityModel NuGet package.


Note on hosting


Please note that, for demo purposes, this documentation shows the use of IIS Express. This is for local testing purposes, and you should use your own chosen method to host a publicly-available web app.


.NET SDK Setup


  1. Navigate to your chosen working projects folder and clone the repository git clone https://github.com/miracl/maas-sdk-dotnet-v2.git (or git clone https://github.com/miracl/maas-sdk-dotnet.git for version 1) or download and extract the zip file from the repository url.

  2. Navigate to the root maas-sdk-dotnet-v2 folder, then open Authentication.sln with Visual Studio

  3. Minimise Visual Studio and navigate back to the root maas-sdk-dotnet-v2 folder. You will see that a '.vs' folder has appeared. Open the file .vs/config/applicationhost.config. In here you should edit the MiraclAuthenticationApp block:
    <site name="MiraclAuthenticationApp" id="3">    
    <application path="/" applicationPool="Clr4IntegratedAppPool">    
    <virtualDirectory path="/" physicalPath="C:\Users\Mike\sdk\maas-sdk-dotnet-v2\Sample" />
    </application>
    <bindings>  
    <binding protocol="http" bindingInformation="*:5000:127.0.0.1" />
    </bindings>
    </site>

    Make sure that bindingInformation is changed from :5000:localhost to :5000:127.0.0.1

Note that these instructions may differ for versions of Visual Studio older than 2015. You may have to edit the config file found in Documents\IISExpress\config\applicationhost.config and create the site name block above.


Run the .NET demo app


Now return to Visual Studio:

  1. Right-click on the top-level 'Authentication' solution and choose 'Build Solution'.

  2. Right-click on '/Samples/MiraclAuthenticationApp' and choose 'Set as Startup Project'.

  3. Open the Web.config file in MiraclAuthenticationApp and edit the following section to insert your app credentials:

    For security, the client ID and secret for a genuine app should not be stored in clear text in a config file. This has only been done here for simple demo purposes. For a production scenario, the client ID and secret should be programmatically accessed via an encrypted API

    <appSettings>
     <add key="webpages:Version" value="3.0.0.0" />
     <add key="webpages:Enabled" value="false" />
     <add key="ClientValidationEnabled" value="true" />
     <add key="UnobtrusiveJavaScriptEnabled" value="true" />
     <add key="ClientId" value="YOUR CLIENT ID"/>
     <add key="ClientSecret" value="YOUR CLIENT SECRET"/>
    </appSettings>  
  4. Then open the Sample/Views/Home/Index.cshtml file and, towards the end of the file, make sure the mpad script has the correct url in order to communicate with the authentication server (note that it begins with 'mcl.cdn.mpin.io'):

    @section scripts{
    <script src="https://mcl.cdn.mpin.io/mpad/mpad.js"  data-authurl="@ViewBag.AuthorizationUri" data-element="btmpin"></script>
    }
  5. Now run the app and it will be automatically opened in your browser:

    image3

    You will notice a tick box which enables you to use the 'preroll id' login facility:

    use preroll id

    This means that a user can enter their email address and it will be automatically baked into the QR code. When the QR code is scanned with the phone app, this will save having to re-input their email address and have one of two effects:

    1. If you are not already registered with the service, you will automatically be sent a confirmation email
    2. If already registered, your ID that has been registered with that email address will be automatically selected

    Once you click the login button, you will be prompted to confirm your identity (if not already registered), create a 4-digit PIN and login.

    Once logged in you will be greeted by the logged in session page:

    image4


Setting up an outbound HTTP Proxy Server


In order to make either the SDK and the Sample Web App work using a proxy server, the Windows Internet configuration options can be changed as such:

  1. Go to Control Panel -> Network and Internet -> Internet Options
  2. Select the Connections tab and the click the LAN Settings button
  3. Select the option Use a proxy server for your LAN and specify the desired proxy server Address and Port
  4. Click the OK button

The SDK and the Sample app should then work through the specified proxy server.


.NET Code Analysis / Visual Studio Tutorial


From here you can choose between a detailed breakdown of the code used to build the demo app, or a simple step-by-step tutorial on creating a similar app in Visual Studio. Please select a tab below:

.NET demo app analysis

Within the MiraclAuthenticationApp folder, key files are:

  1. Web.config
  2. MiraclAuthenticationApp.csproj
  3. /Controllers/HomeController.cs
  4. /Controllers/loginController.cs
  5. *.cshtml files found in /views/
  1. Credentials and Redirect URI

    For security, the client ID and secret for a genuine app should not be stored in clear text in a config file. This has only been done here for simple demo purposes. For a production scenario, the client ID and secret should be programmatically accessed via an encrypted API

    In the root of the samples/MiraclAuthenticationApp folder, web.config is used to specify your app credentials. Here you will see the clientID and ClientSecret:

    <add key="ClientId" value=""/>
    <add key="ClientSecret" value=""/>

    You can then check the baseUri for the demo app by right-clicking on the samples/MiraclAuthenticationApp folder, choosing 'Properties' and then in the 'Web' section, you will see that it is set as http://127.0.0.1:5000:

    image1

    Note that the redirect_uri is automatically constructed by appending /login to the baseUri for the web app. Therefore, since the baseUri for the demo app is http://127.0.0.1:5000, the redirect_uri is automatically set as http://127.0.0.1:5000/login. When creating your own apps, in the app settings in the portal, the entry for Redirect URI must be set to match this.

    Note that the MFA Authentication server does not accept 'localhost' as a base uri for redirects, hence the uri for the demo app is set as 127.0.0.1:5000 and it should be hosted on this url. When creating your own app, you can of course - in the settings for your app in the portal and in the app properties in VS - specify the url and port which you want to use for your app.

  2. Dealing with the Miracl Client Object

    The MiraclClient is created by the /Controllers/HomeController.cs file:

    Here you can see that, when called, the client is initiated with the client id and secret by using ConfigurationManager.AppSettings:

    public async Task<ActionResult> Index()
          {
              if (Client == null)
              {
                  Client = new MiraclClient(new MiraclAuthenticationOptions
                  {
                      ClientId = ConfigurationManager.AppSettings["ClientId"],
                      ClientSecret = ConfigurationManager.AppSettings["ClientSecret"],
                      AuthenticationType = "Cookies"
                  });
              }
    
              var url = await Client.GetAuthorizationRequestUrlAsync(Request.Url.ToString());
              ViewBag.AuthorizationUri = url;
              return View();
          }
    

    The values for ClientId and ClientSecret are obtained from the Web.config file, as mentioned above.

    It is important to note that the Startup.cs file specifies an AuthenticationType of "Cookies" and, in order for Request.GetOwinContext().Authentication.SignIn(identity); to function, the AuthenticationType must also be "Cookies" in HomeController.cs as in the above snippet.

    Client.GetAuthorizationRequestUrlAsync and ViewBag.AuthorizationUri = url; are used to obtain and send the authorization request url which can then, in the .cshtml files which control the front end of your app, be used with mpad.js to send authentication parameters (client_id and redirect_uri) to the server.

    If you want to use a Redirect url other than the default '/login', you can set the CallbackPath of the MiraclClient object to whatever you wish. For example, if you have set the RedirectUrl in the portal to be http://127.0.0.1:5000/signin, you can declare the MiraclClient object thus:

    Client = new MiraclClient(new MiraclAuthenticationOptions
    {
     ClientId = "qij*********ghc",
     ClientSecret = "InOKlcxoY4ijLIP****************Qukb54iXE",
     AuthenticationType = "Cookies",
     CallbackPath = new Microsoft.Owin.PathString("/signin")
    });

    In this you should name the view responsible for handling the callback request signin instead of login and the controller should be called signinController instead of loginController.

    In /Controllers/loginController.cs the client.ValidateAuthorization(Request.QueryString) method is used to complete the authorization query. This will either return null if authorization is denied:

    if (Request.QueryString == null || string.IsNullOrEmpty(Request.QueryString["code"]) || string.IsNullOrEmpty(Request.QueryString["state"]))
              {
                  return View("Error");
              }

    Or will return an access token on success. The ClaimsIdentity object which is necessary for the user to authenticate is created by HomeController.Client.GetIdentity(response);:

    IdentityModel.Client.TokenResponse response = await HomeController.Client.ValidateAuthorization(Request.QueryString);
              if (response != null)
              {
                  var identity = await HomeController.Client.GetIdentity(response);
                  Request.GetOwinContext().Authentication.SignIn(identity);
              }
    
              if (!string.IsNullOrEmpty(response.IdentityToken))
              {
                  ViewBag.IdentityTokenParsed = ParseJwt(response.IdentityToken);
              }
              if (!string.IsNullOrEmpty(response.AccessToken))
              {
                  ViewBag.AccessTokenParsed = ParseJwt(response.AccessToken);
              }  

    In loginController.cs, using ViewBag.Client = HomeController.Client; before the result is returned within public async Task <ActionResult> Index() makes the Get User ID and Get Email methods available in the login/Index.cshtml file:

    ViewBag.Client = HomeController.Client;
    
    return View(response);
    }

    In Controllers/HomeController.cs, Request.GetOwinContext().Authentication.SignOut(); can then be used to log the user out, with client.ClearUserInfo() being used to specify whether all client settings (including options (credentials), state and nonce) are cleared or not:

    if (Logout != null)
                {
                    Client.ClearUserInfo(false);
                    Request.GetOwinContext().Authentication.SignOut();
                }
  3. Notes on the index.cshtml files:

    The login page of the demo app is configured in /Views/Home/Index.cshtml. It makes use of User.Identity.IsAuthenticated to check if the user is already logged in. If not then the login button is created:

    if (User.Identity.IsAuthenticated)
    {
       <button name="Logout" id="LogoutId" title="Test" value="Logout">Logout</button>
    }  
    else
    {
        <div class="inner cover">
            <p class="lead">
                <a id="btmpin"></a>
            </p>
            <p>
                @Html.CheckBox("UsePrerollId") &nbsp; Use PrerollId login
                <div hidden="hidden">
                    <label for="PrerollId" id="lblPrerollId">PrerollId</label>:
                    <br />
                    @Html.TextBox("PrerollId", string.Empty, new { style = "width:500px" })
                </div>
            </p>
        </div>
    }

    Note that the use of <a id="btmpin"></a> is what creates the login button in communication with the mpad.js script.

    Note also that the use of PrerollId will enable capturing the user's email address to bake it into the QR code. Ultimately, it will then be pre-populated in the user's phone app, saving them the trouble of entering their email address twice and enhancing the user experience. At the end of the Home/Index.cshtml file there is a $("#UsePrerollId") javascript which is needed for PrerollId to function.

    The mpad.js library is used to construct the login button. :

    @section scripts{
      <script src="https://mcl.cdn.mpin.io/mpad/mpad.js"  data-authurl="@ViewBag.AuthorizationUri" data-element="btmpin"></script>
      }

    Where:
    data-element is the login button ID (note that this must correspond with <a id="btmpin"> in order for the button to work)
    data-authurl is the authorization URL (this passes the client_id and redirect_uri to the authentication server). As mentioned above, this was fetched with the Client.GetAuthorizationRequestUrlAsync method and sent by ViewBag.AuthorizationUri = url;.

    The logged in session page which presents the refresh/logout options is configured in Views/login/Index.cshtml. Note that the name of the view (login) is the same as the callback path of the server (specified in the redirect uri: baseUri/login) and handles the response of the server.

    Here the 'logout' button is created:

    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <button name="Logout" id="LogoutId" title="Test" value="Logout" type="submit">Logout</button>
    }

    Also, thanks to using ViewBag.Client = HomeController.Client; in loginController.cs, @ViewBag.Client.UserId and @ViewBag.Client.UserEmail can be used to return the email address and ID of the registered user, as in the sample:

    Hi, <b>@ViewBag.Client.UserId</b> !

    Important Note on User Management

    In terms of managing your users, it is important to note that, in the process of providing a secure login solution, the service has also registered your users with a confirmed user email and user ID. Once a user has been authenticated it is possible to make use of the HomeController.Client.UserId and HomeController.Client.UserEmail properties to return string values.

    This removes a considerable amount of pain from the process of managing users and databases!

    For example, if you have a SQL user database and you want to make a check to see if a user is present, or needs added as a new user, then it is possible to make use of the above properties.

    Another example would be if you want to present a web form to capture more information that is needed to provide a user with access to your product features. Here you can use the above properties to prepopulate the ID and email address field, and you do not need to initiate a 'verify by email' process, as this has already been done by the service.

Creating your own .NET app

Now we can walk you through some step-by-step instructions on using Visual Studio to create an app with similar functionality to the demo app.

Note that specific instructions regarding project URL can be adjusted to match the actual URL your app will be using.
Also note that this tutorial is specific to VS 2015 and the step-by-step instructions will be different for different versions of Visual Studio.


When copying sections of code below, please note that there may be unwanted character fragments when the code is pasted into Visual Studio, which will give errors when you run the app. Visual Studio's debugging will indicate where these fragments are.

1. Create a new project

Return to Visual Studio, right-click on the 'Samples' folder and 'Add' -> 'New Project':

image5

  • Choose 'Visual C#' -> 'Web'
  • Name the project and click OK
  • Choose 'MVC' and click OK

2. Set the Project URL

Right-click on the new project folder and choose 'Properties':

image9

In the 'Web' tab, set the project URL and click 'Create Virtual Directory'. At this point, note that the SDK will automatically create your Redirect URL by appending /login on to your project URL:

image10a

If you have chosen the same http://127.0.0.1:5000 url, as with the demo app, you will be shown this message:

image10

Click 'yes' if so, but note that the demo MiraclAuthenticationApp project won't work anymore as you have now taken its project url.

3. Set as Start-up Project

Right-click on the new project folder and click 'Set as Start-up Project':

image11

4. Ensure correct resolution of URL

Right-click on the very top-level solution and choose 'Open Folder in File Explorer':

image12a

Open the file .vs/config/applicationhost.config and change the binding information for your project from localhost to 127.0.0.1:

<site name="WebApplication1" id="3">    
<application path="/" applicationPool="Clr4IntegratedAppPool">    
<virtualDirectory path="/" physicalPath="C:\Users\Mike\sdk\maas-sdk-dotnet-v2\WebApplication1" />
</application>
<bindings>  
<binding protocol="http" bindingInformation="*:5000:127.0.0.1" />
</bindings>
</site>

Now rebuild the very top-level solution:

5. Run the first build of the project

  • Click the play button in the toolbar:

click-play

This will run the first build of the project, and display the default ASP.net page in your browser and confirm that the project is working. You can close this and continue with the project setup.

6. Add References

Right-click on References -> Add Reference:

image14

Select 'Miracl Authentication' and click OK:

image15

Right-click on the project folder (not the references folder!), and select 'Manage NuGet Packages'.

In 'Browse' search for and install the 'IdentityModel' package.

IdentityModel

7. Set Cookies Auth type

Open Startup.cs again and add the following to the top of the file:

using Microsoft.Owin.Security.Cookies;

Then paste the following code into the public void Configuration(IAppBuilder app) method:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = "Cookies"
});  

Then save + close

8. Set the home page Controller

Open /Controllers/HomeController.cs

Insert the following at the top of the file:

using Miracl;
using System.Threading.Tasks;

Then replace the code:

public ActionResult Index()
{
    return View();
}

With:

internal static MiraclClient Client;
       public async Task<ActionResult> Index()
       {
           if (Client == null)
           {
               Client = new MiraclClient(new MiraclAuthenticationOptions
               {
                   ClientId = "dsf******t",
                   ClientSecret = "c_fwe*************vmlsdw[weoredv",
                   AuthenticationType = "Cookies"
               });
           }
​
           var url = await Client.GetAuthorizationRequestUrlAsync(Request.Url.ToString());
           ViewBag.AuthorizationUri = url;
           return View();
       }
​
       [HttpPost]
       public ActionResult Index(string Logout)
       {
           if (Logout != null)
           {
               Client.ClearUserInfo(false);
               Request.GetOwinContext().Authentication.SignOut();
           }
​
           return RedirectToAction("Index");
       }

Be sure to replace ClientID and ClientSecret with the correct values for your app.

For security, the client ID and secret for a genuine app should not be stored in clear text in a script. This has only been done here for simple demo purposes. For a production scenario, the client ID and secret should be programmatically accessed via an encrypted API

Note that AuthenticationType must be set to 'Cookies', as this is what has been specified in the project Startup.

Note that Client.GetAuthorizationRequestUrlAsync and ViewBag.AuthorizationUri = url; are used to obtain and send the authorization request url which can then, in Home/index.cshtml which controls the front end of your app, be used with mpad.js to send authentication parameters (client_id and redirect_uri) to the server.

Then save + close

9. Create home page and login button

Open Views/Home/Index.cshtml and add the following:

@{
    ViewBag.Title = "Home Page";
}
<div class="jumbotron">
    <h1>.Net Web Example</h1>
    <h2>Login Page</h2>
</div>
<div class="row">
    <div class="col-md-8">

        @using (Html.BeginForm())
        {
            if (User.Identity.IsAuthenticated)
            {
                <button name="Logout" id="LogoutId" title="Test" value="Logout">Logout</button>
            }
            else
            {
                <div class="inner cover">
                    <p class="lead">
                        <a id="btmpin"></a>
                    </p>
                    <p>
                        @Html.CheckBox("UsePrerollId") &nbsp; Use PrerollId login
                        <div hidden="hidden">
                            <label for="PrerollId" id="lblPrerollId">PrerollId</label>:
                            <br />
                            @Html.TextBox("PrerollId", string.Empty, new { style = "width:500px" })
                        </div>
                    </p>
                </div>
            }
        }

        <br />
        <br />
        <br />

    @if (User.Identity.IsAuthenticated)
    {
        <div class="col-md-10">
            <h3>Identity</h3>
            <p>
                <dl>
                    @foreach (var claim in System.Security.Claims.ClaimsPrincipal.Current.Claims)
                {
                        <dt>@claim.Type</dt>
                        <dd>@claim.Value</dd>
                    }
                </dl>
            </p>
        </div>
    }

    </div>

    @section scripts{
        <script src="https://mcl.cdn.mpin.io/mpad/mpad.js"  data-authurl="@ViewBag.AuthorizationUri" data-element="btmpin"></script>     
        <script>
            $("#UsePrerollId").change(
            function () {
                var prerollIdContainer = $("#PrerollId").parent();
                prerollIdContainer.toggle();
                if (prerollIdContainer.is(":visible")) {
                    $('#PrerollId').change(function (event) {
                        var prerollIdData = document.getElementById('PrerollId').value;
                        $('#btmpin').attr("data-prerollid", prerollIdData);
                    });
                }
                else {
                    $('#btmpin').removeAttr("data-prerollid");
                }
            });
        </script>
    }

</div>

Using the IsAuthenticated check, this will either display the logout button if the user is already logged in, or display the login button - making use of the mpad.js library.

Note also that the use of PrerollId will enable capturing the user's email address to bake it into the QR code. Ultimately, it will then be pre-populated in the user's phone app, saving them the trouble of entering their email address twice and enhancing the user experience. At the end of the Home/Index.cshtml file there is a $("#UsePrerollId") javascript which is needed for PrerollId to function.

The parameters passed in the mpad.js script are:

  • data-element: the login button ID (corresponds with <div id="btmpin">)
  • data-authurl: the authorization URL (this passes the client_id and redirect_uri to the authentication server). Each SDK has a 'Get Authorization Request URL' method for obtaining this.

Now open the Shared/_Layout.cshtml file and remove the following line:

@Html.Partial("_LoginPartial")

10. Create the logged in page

Right-click on the 'Views' folder and add a new folder called login.

In this folder add a new view called Index which will render as Index.cshtml, and insert the following:

@model IdentityModel.Client.TokenResponse
@{
    ViewBag.Title = "Token response";
}
<h1>.Net Web Example</h1>
<h2>Logged in session</h2>

<br />
<div class="row">
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <button name="Logout" id="LogoutId" title="Test" value="Logout" type="submit">Logout</button>
    }
</div>
<br />
<br />
<p>
    @if (Model.Json != null)
    {
        <strong>Token response:</strong>
        <br />
            <pre>@Model.Json.ToString()</pre>
    }
</p>
<br />
<br />
<div class="col-md-10">
    <div class="col-md-5">
        <p><b>UserID:</b> @ViewBag.Client.UserId<br /></p>
    </div>
</div>
<br />
<br />
<p>
    <strong>Identity token:</strong>
    <pre>@ViewBag.IdentityTokenParsed</pre>
</p>
<p>
    <strong>Access token:</strong>
    <pre>@ViewBag.AccessTokenParsed</pre>
</p>
<p>
    <strong>Token type:</strong>
    <br />
    @Model.TokenType
</p>
<p>
    <strong>Expires:</strong>
    <br />
    @(DateTime.Now.AddSeconds(Model.ExpiresIn).ToString())
</p>
<p>
    <strong>Refresh token:</strong>
    <br />
    @Model.RefreshToken
</p>

The above code will check for a token response and return the details of their access and identity tokens as can be seen from the logged in screenshot:

Note that <p><b>UserID:</b> @ViewBag.Client.UserId<br /></p> will return the ID of the user, as has been set by the authentication server. As you will see below, this ViewBag is set in the login controller.

Also note that a refresh token leaves the access token unchanged. It can be used to request user info without performing a fresh authorization.

11. Create the callback Controller

  • Right-click on Controllers and add a new Controller
  • Choose MCV5 'Empty'
  • Name it loginController

Now open loginController.cs and add the following:

using System.Text;
using System.Threading.Tasks;
using IdentityModel;
using Newtonsoft.Json.Linq;

Now remove the first method inside public class loginController : Controllerand paste the following in its place:

public async Task<ActionResult> Index()
       {
           if (Request.QueryString == null || string.IsNullOrEmpty(Request.QueryString["code"]) || string.IsNullOrEmpty(Request.QueryString["state"]))
           {
               return View("Error");
           }

           IdentityModel.Client.TokenResponse response = await HomeController.Client.ValidateAuthorization(Request.QueryString);
           if (response != null)
           {
               var identity = await HomeController.Client.GetIdentity(response);
               Request.GetOwinContext().Authentication.SignIn(identity);
           }

           if (!string.IsNullOrEmpty(response.IdentityToken))
           {
               ViewBag.IdentityTokenParsed = ParseJwt(response.IdentityToken);
           }
           if (!string.IsNullOrEmpty(response.AccessToken))
           {
               ViewBag.AccessTokenParsed = ParseJwt(response.AccessToken);
           }

           ViewBag.Client = HomeController.Client;

           return View(response);
       }

       private string ParseJwt(string token)
       {
           if (!token.Contains("."))
           {
               return token;
           }

           var parts = token.Split('.');
           var part = Encoding.UTF8.GetString(Base64Url.Decode(parts[1]));

           var jwt = JObject.Parse(part);
           return jwt.ToString();
       }

The client.ValidateAuthorization(Request.QueryString) method is used to complete the authorization query. This will either return null if the necessary parameters are not provided, or will return an access token on success. The ClaimsIdentity object which is necessary for the user to authenticate is created by HomeController.Client.GetIdentity(response);

ViewBag.Client = HomeController.Client; makes it possible, in /login/Index.cshtml to use @ViewBag.Client.UserId and @ViewBag.Client.UserEmail to return the email address and ID of the registered user.

Important Note on User Management

In terms of managing your users, it is important to note that, in the process of providing a secure login solution, the service has also registered your users with a confirmed user email and user ID. Once a user has been authenticated it is possible to make use of the above HomeController.Client.UserId and HomeController.Client.UserEmail properties to return string values.

This removes a considerable amount of pain from the process of managing users and databases!

For example, if you have a SQL user database and you want to make a check to see if a user is present, or needs added as a new user, then it is possible to make use of the above properties.

Another example would be if you want to present a web form to capture more information that is needed to provide a user with access to your product features. Here you can use the above properties to prepopulate the ID and email address field, and you do not need to initiate a 'verify by email' process, as this has already been done by the service.

12. Run the App!

Finally, clean and rebuild the project folder, then click play in the toolbar, and your new app should run in your browser, just as with the demo app.


Making a web app available as an authenticator for a mobile app


Please note that, for demo purposes, this documentation shows the use of IIS Express. This is for local testing purposes, and you should use your own chosen method to host a publicly-available web app.

If you wish to develop a web app which can act as an authenticator for a local login mobile app - as per instructions at Android Local login app - note that, within the sample mobile app this functionality is made available with the following controllers:

  • authzUrlController.cs:
  • authTokenController.cs:

These controllers make the necessary calls to the SDK methods which provide the necessary functionality to enable use of the app as an authenticator. They should be used when creating any app which is intended for this purpose.

Top