Przejdź do głównej zawartości

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.

    NameDescriptionFile
    DomainThe host/domain of your Casdoor serverCasdoorVariables.cs
    ClientIdThe Client ID of your Casdoor applicationCasdoorVariables.cs
    AppNameThe name of your Casdoor applicationCasdoorVariables.cs
    CallbackUrlThe path of the callback URL for your Casdoor application. If not provided, it will be casdoor://callbackCasdoorVariables.cs
    ClientSecretThe Client Secret of your Casdoor applicationCasdoorVariables.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​