Saltar al contenido principal

Sign users in to a .NET desktop app

This guide explains how to run the Casdoor example for .NET desktop apps and how to add the same sign-in flow to your own app. The example shows the Casdoor sign-in page in a WebView2 window.


Learning outcomes​

  • Configure and run the example app.
  • Open the Casdoor sign-in window from your app.
  • Exchange the authorization code for a token and read the user.

What you need​

Sample code​


Run the example​

  1. Clone casdoor-dotnet-desktop-example.

  2. Set the following values. All of them are strings.

    NombreDescripciónArchivo
    DomainEl host/dominio de tu servidor CasdoorCasdoorVariables.cs
    ClientIdEl ID de Cliente de tu aplicación CasdoorCasdoorVariables.cs
    AppNameEl nombre de tu aplicación CasdoorCasdoorVariables.cs
    CallbackUrlLa ruta de la URL de callback para tu aplicación Casdoor. Si no se proporciona, será casdoor://callbackCasdoorVariables.cs
    ClientSecretEl Secreto de Cliente de tu aplicación CasdoorCasdoorVariables.cs
  3. Start the app.

    • In Visual Studio: Open casdoor-dotnet-desktop-example.sln and press Ctrl + F5.
    • On the command line: Run dotnet run in src/DesktopApp.
  4. In the app window, click Casdoor Login.

    Main window of the example app

    The Casdoor sign-in page opens in a window.

    Casdoor sign-in window

  5. Sign in. The app shows the profile of the user.

    User profile in the example app

Recording of the complete sign-in flow

Add sign-in to your app​

Open the sign-in window​

Create the sign-in window and subscribe to the event that delivers the authorization code:

var login = new Login();
// Triggered when login succeeds, you will receive an auth code in the event handler
login.CodeReceived += Login_CodeReceived;
login.ShowDialog();

Exchange the code for the user​

In the event handler, exchange the authorization code for a token and read the user from it:

public async Task<string?> RequestToken(string clientId, string clientSecret, string code)
{
var body = new
{
grant_type = "authorization_code",
client_id = clientId,
client_secret = clientSecret,
code
};

var req = new RestRequest(_requestTokenUrl).AddJsonBody(body);
var token = await _client.PostAsync<TokenDto>(req);

return token?.AccessToken;
}

public async Task<UserDto?> GetUserInfo(string token)
{
var req = new RestRequest(_getUserInfoUrl).AddQueryParameter("accessToken", token);

return await _client.GetAsync<UserDto>(req);
}

...

var token = await _casdoorApi.RequestToken(
CasdoorVariables.ClientId,
CasdoorVariables.ClientSecret,
authCode,
);

var user = await _casdoorApi.GetUserInfo(token);

See also​