DotVVM Authorization with IdentityServer4
Tags: dotvvm, identityserver, csharp, dotnet
Published: 2020-03-21 15:53:34

DotVVM is open source MVVM framework for ASP.Net Core and OWIN and it is member of [.Net Foundation](https://dotnetfoundation.org/). DotVVM is a free to use under Apache License but also have commercial extensions.

DotVVM lets you build interactive web UIs with just C# and HTML using MVVM pattern. DotVVM framework is shipped with many build-in controls like _GridView_, _FileUpload_, _Validators_, and more.
  
To learn more about DotVVM framework visit [DotVVM.com](https://www.dotvvm.com/).
  
In this article we will see how to secure your DotVVM web application using IdentityServer4.
#### What is IdentityServer4?
IdentityServer4 is an OpenID Connect and OAuth2.0 framework for ASP.Net Core. it enables:
-   Authentication as a service
-   Single Sign-n (SSO)
-   Access control for APIs

and more.

It is an open source framework you get its code from [GitHub repository](https://github.com/IdentityServer/IdentityServer4) and the [full documentation](https://identityserver4.readthedocs.io/en/latest/)
  
**_You can check my  [previous article](https://dev.to/dotvvm/dotvvm-crud-application-with-entity-framework-and-cosmos-db-4oah)  to know how to install DotVVM extension._**
  
First of all we need to prepare our IdentityServer4 as our authentication service. IdentityServer4 has different templates to use, for simplicity we will use out of the box IdentityServer4 UI template which provides a complete UI for defining roles, users, clients, claim types,.etc.

1.  To install IdentityServer templates for dotnet CLI run this command in console window.
`dotnet new -i IdentityServer4.Templates`

2.  From cmd or windows PowerShell run following commands
    ```
md dotvvm/src //create folder for our solution
cd dotvvm/src
dotnet new sln -n dotvvm
dotnet new is4admin -n dotvvm.auth
dotnet sln add .\dotvvm.auth\dotvvm.auth.csproj
```
3. Open your solution in vs2019 or vs code, your solution should look like

[![](https://1.bp.blogspot.com/-SmKRZziPs78/XnFDSaXVX6I/AAAAAAAACmg/9wJ_GjwslcsO-4mQAeFhSW9EFl3O52GggCLcBGAsYHQ/s200/solution-explorer.png)](https://1.bp.blogspot.com/-SmKRZziPs78/XnFDSaXVX6I/AAAAAAAACmg/9wJ_GjwslcsO-4mQAeFhSW9EFl3O52GggCLcBGAsYHQ/s1600/solution-explorer.png)

build and run you solution it should see a page like this

[![](https://1.bp.blogspot.com/-W2I28RWc_3I/XnFEFa1D71I/AAAAAAAACms/rPoj8Bj4FqMNAWcotvet6Rsmmza_Q7c6QCLcBGAsYHQ/s400/is4-admin-ui.png)](https://1.bp.blogspot.com/-W2I28RWc_3I/XnFEFa1D71I/AAAAAAAACms/rPoj8Bj4FqMNAWcotvet6Rsmmza_Q7c6QCLcBGAsYHQ/s1600/is4-admin-ui.png)

To add your users, roles, and clients, click on highlighted link then click on start

[![](https://1.bp.blogspot.com/-caYVyzMDyq8/XnFE-XNNTOI/AAAAAAAACm8/Lhe-ajWdhQUDzbst9aQBQvgk2br5Mcm1wCLcBGAsYHQ/s200/admin-start.png)](https://1.bp.blogspot.com/-caYVyzMDyq8/XnFE-XNNTOI/AAAAAAAACm8/Lhe-ajWdhQUDzbst9aQBQvgk2br5Mcm1wCLcBGAsYHQ/s1600/admin-start.png)[![](https://1.bp.blogspot.com/-RjuueYyMiQo/XnFFYvXhCaI/AAAAAAAACnE/3GxE86LKhfU9yWLa8I5JGa9Z_EyJodj1wCEwYBhgL/s200/admin-controls.png)](https://1.bp.blogspot.com/-RjuueYyMiQo/XnFFYvXhCaI/AAAAAAAACnE/3GxE86LKhfU9yWLa8I5JGa9Z_EyJodj1wCEwYBhgL/s1600/admin-controls.png)
Open Users page and click on Add User button then fill the New User form where you define your user and his login credentials.

**_Note : Save user name and password as you will use it when you run your DotVVM application._**

[![](https://1.bp.blogspot.com/-AE97Bf7buCE/XnFHTd3J3RI/AAAAAAAACnQ/nhUylRL4PHUNkGCaE0T3MG__1zkOVuxdgCLcBGAsYHQ/s200/admin-new-user.png)](https://1.bp.blogspot.com/-AE97Bf7buCE/XnFHTd3J3RI/AAAAAAAACnQ/nhUylRL4PHUNkGCaE0T3MG__1zkOVuxdgCLcBGAsYHQ/s1600/admin-new-user.png)

#### Define your application as Client

1.  Open Clients page and click on Add Client button
2.  Select Web App then click Start
3.  Fill your application main details then click Next.
   Client ID : dotvvm-article-sample.
   DotVVM Framework
   https://localhost:5001
   [![](https://1.bp.blogspot.com/-l8tzzPoLHuU/XnFK_m5ek8I/AAAAAAAACnk/JWHh6qlAHBQip7Ljk8-VAUZmTmPp167ngCLcBGAsYHQ/s320/admin-new-client-1.png)](https://1.bp.blogspot.com/-l8tzzPoLHuU/XnFK_m5ek8I/AAAAAAAACnk/JWHh6qlAHBQip7Ljk8-VAUZmTmPp167ngCLcBGAsYHQ/s1600/admin-new-client-1.png)

5.  Callback URL. It is a URL to a page in your DotVVM application where IdentityServer will redirect to it if sign-in is succeeded. Enter https://localhost:5001 then click next.
6.  Post-logout URL: leave it empty and click next
    
7.  Secret: in this screen you specify a secret key for your DotVVM application. That key will be used in DotVVM application to identify your requests to IdentityServer. enter these values and click Add then click Next.

    Type: Shared Secret
   Value: dotvvm-secret
   Expiration Date: 03/18/2025
   [![](https://1.bp.blogspot.com/-qxpN1xyrvKU/XnP-szblwSI/AAAAAAAACn4/JRiVFu37MDsFGiewppBTH0jDlGQzv55fwCLcBGAsYHQ/s320/admin-new-client-secret.png)](https://1.bp.blogspot.com/-qxpN1xyrvKU/XnP-szblwSI/AAAAAAAACn4/JRiVFu37MDsFGiewppBTH0jDlGQzv55fwCLcBGAsYHQ/s1600/admin-new-client-secret.png)

9.  Identity Resource: select all available resource that can be accessible by your DotVVM application then click Next.
    
    [![](https://1.bp.blogspot.com/-R2NqhZgNzeE/XnQA-e-XrKI/AAAAAAAACoI/j-rKe1NZGdkKlz4VP9ll3zJ9PLHrmoAawCLcBGAsYHQ/s320/admin-new-client-identity-resources.png)](https://1.bp.blogspot.com/-R2NqhZgNzeE/XnQA-e-XrKI/AAAAAAAACoI/j-rKe1NZGdkKlz4VP9ll3zJ9PLHrmoAawCLcBGAsYHQ/s1600/admin-new-client-identity-resources.png)
    
10.  Protected Resources:select all available resources that can be accessible by your DotVVM application then click Next.
    
9.  Review your choices and click Save
    
10.  Open your client details and go to Advanced -> Token tab and check Always Include UserClaims In Id Token    
    [![](https://1.bp.blogspot.com/-zrWD1XKoT4Y/XnXZrAGlqMI/AAAAAAAACpY/S9WeTjlh76MnpIkxcqRD87GAFxJH66CjACLcBGAsYHQ/s320/admin-claims.png)](https://1.bp.blogspot.com/-zrWD1XKoT4Y/XnXZrAGlqMI/AAAAAAAACpY/S9WeTjlh76MnpIkxcqRD87GAFxJH66CjACLcBGAsYHQ/s1600/admin-claims.png)
    

**_Differences between different options we have selected is out of scope of this post._**

#### DotVVM Application

We will create a new empty DotVVM application, just include Bootstrap and Authentication sample code.

You can check this [post](https://dev.to/dotvvm/dotvvm-crud-application-with-entity-framework-and-cosmos-db-4oah)  for full steps of DotVVM application creation.

[![](https://1.bp.blogspot.com/-t1iK2SvMyQw/XnQFhcfXMNI/AAAAAAAACok/rvt8RCNDjHcMLzFw15js9uBGhYbBoH_rgCLcBGAsYHQ/s400/new-dotvvm-project.png)](https://1.bp.blogspot.com/-t1iK2SvMyQw/XnQFhcfXMNI/AAAAAAAACok/rvt8RCNDjHcMLzFw15js9uBGhYbBoH_rgCLcBGAsYHQ/s1600/new-dotvvm-project.png)

It is recommended to change you the target framework of your DotVVM application to .Net Core 3.1 and also re-install Microsoft.AspNetCore.Authentication.Cookies package.
1.  Open Program.cs file and add the following line to BuildWebHost method. We specify the URL of the DotVVM application to match what we have used while configuring the IdentityServer client.
 `.UseUrls("https://localhost:5001")`
2.  Install `Microsoft.AspNetCore.Authentication.OpenIdConnect` package.
3.  replace `ConfigureServices` method with the following code
     ```
public void ConfigureServices(IServiceCollection services)
{
   services.AddDataProtection();
   services.AddAuthorization();
   services.AddWebEncoders();
   JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
   services.AddAuthentication(options =>{
         options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
         options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
   })
   .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
   .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>{
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;
        options.SaveTokens = true;
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.ClientId = "dotvvm-article-sample";
        options.ClientSecret = "dotvvm-secret";
        options.ResponseType = "id_token token";
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.CallbackPath = "/signin-oidc";
     });
     services.AddRazorPages();
     services.AddDotVVM<DotvvmStartup>();
}
```
4.  replace the Configure method with the following code
    ```
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      app.UseAuthentication();
      app.UseRouting();
      app.UseAuthorization();
      // use DotVVM
      var dotvvmConfiguration = app.UseDotVVM<DotvvmStartup>(env.ContentRootPath);
      dotvvmConfiguration.AssertConfigurationIsValid();
      // use static files
      app.UseStaticFiles(new StaticFileOptions
        {
           FileProvider = new PhysicalFileProvider(env.WebRootPath)
        });
       app.UseEndpoints(endpoints =>
       {
         endpoints.MapRazorPages();
       });
    }
```
5. Open ViewModels/MasterPageViewModel.cs file and decorate MaterPageViewModel class with Authorize attribute.
`[Authorize]`
`public class MasterPageViewModel : DotvvmViewModelBase`
   
6.  Add the following line to MasterPageVeiwModel class to read name of the logged in user from IdentityServer claims.
`public string Username => Context.HttpContext.User.FindFirst("name")?.Value;`
   
7. Open Views/Default.dothtml file and add this div to content control
`<div class="alert alert-info">Welcome to DotVVM, {{value: Username}}</div>`

8.  First you must run dotvvm.auth project and once you run your dotvvm.web project it will be redirected login page of IdentityServer
    
    [![](https://1.bp.blogspot.com/-l_6l5mdcIpI/XnQRfLuiKZI/AAAAAAAACow/I1BBBCkh2-UH-EE5FWceKDRKo5S7Ip2WwCLcBGAsYHQ/s320/login-page.png)](https://1.bp.blogspot.com/-l_6l5mdcIpI/XnQRfLuiKZI/AAAAAAAACow/I1BBBCkh2-UH-EE5FWceKDRKo5S7Ip2WwCLcBGAsYHQ/s1600/login-page.png)
    
9.  After logging using username and password you have specified while creating user step, you will be redirected to permission pages where IdentityServer asking for your permission.
    
    [![](https://1.bp.blogspot.com/-WrXTX4yGcSI/XnQUYB8AFKI/AAAAAAAACo8/HGDiVnRAnLg2Q11N05UdWnEemUjnn5dlQCLcBGAsYHQ/s320/permissions-page.png)](https://1.bp.blogspot.com/-WrXTX4yGcSI/XnQUYB8AFKI/AAAAAAAACo8/HGDiVnRAnLg2Q11N05UdWnEemUjnn5dlQCLcBGAsYHQ/s1600/permissions-page.png)
    
10.  Check permission you want to allow then click Yes, Allow button to go to your DotVVM application.
    
    [![](https://1.bp.blogspot.com/-Pl7S0vWR3gY/XnXZ-iGD9MI/AAAAAAAACpc/8v_aZR9EpFclyRHJlrNK1dacnHCNWvqYgCLcBGAsYHQ/s320/home.png)](https://1.bp.blogspot.com/-Pl7S0vWR3gY/XnXZ-iGD9MI/AAAAAAAACpc/8v_aZR9EpFclyRHJlrNK1dacnHCNWvqYgCLcBGAsYHQ/s1600/home.png)


#### Summary
In this article we showed how to use IdentityServer4 to Authenticate your DotVVM application.
You can find the complete code sample in [GitHub](https://github.com/miroprocessor/dotvvm-identityserver)