如何在WPF中处理AuthenticationState?

huangapple go评论70阅读模式
英文:

How to handle AuthenticationState in WPF?

问题

我有一个使用 JWT 从 API 获取用户声明的 .NET 7 WPF 应用程序。登录过程正常工作。但是我不知道应该在 WPF 部分存储用户信息在哪里。在 ASP.NET Core 中,我使用 AuthenticationStateProvider,但似乎在 WPF 中没有这样的选项。

无论如何,以下是我目前的代码:

public partial class MainWindow
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly ILogger<MainWindow> _logger;

    public MainWindow(IHttpClientFactory httpClientFactory, ILogger<MainWindow> logger)
    {
        InitializeComponent();
        _httpClientFactory = httpClientFactory;
        _logger = logger;
    }

    private async void LoginButton_Click(object sender, RoutedEventArgs e)
    {
        var client = _httpClientFactory.CreateClient();
        var tokenResponse =
            await client.PostAsJsonAsync("https://localhost:5001/api/login/pos", new LoginCredentials(UsernameTextBox.Text, PasswordBox.Password));

        if (tokenResponse.IsSuccessStatusCode)
        {
            LoginResult loginResult = await tokenResponse.Content.ReadFromJsonAsync<LoginResult>();
            string token = loginResult.Token;
            SetPrincipal(token);
        }
        else
        {
            MessageBox.Show(await tokenResponse.Content.ReadAsStringAsync(), "Login failed");
        }
    }

    private void SetPrincipal(string token)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var jwtToken = tokenHandler.ReadJwtToken(token);

        var claims = jwtToken.Claims;
        var identity = new ClaimsIdentity(claims);
        var principal = new ClaimsPrincipal(identity);

        System.Threading.Thread.CurrentPrincipal = principal;
        AppDomain.CurrentDomain.SetThreadPrincipal(principal);
    }
}

我正在阅读关于 Thread.CurrentPrincipal 的内容,但不确定这是否是正确的方法。

在 .NET 7 WPF 应用程序中存储和访问用户信息是否有常见的方法,还是我需要自己实现它?

英文:

I am having a net 7 Wpf app that get's the user claims from an API on login using jwt. The login process is working. But i don't know where i should store the user's information on the Wpf side. In asp.net core I use the AuthenticationStateProvider but it seems there is no such option for Wpf.

Anyway here's the current code i have:

public partial class MainWindow
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger&lt;MainWindow&gt; _logger;

        public MainWindow(IHttpClientFactory httpClientFactory, ILogger&lt;MainWindow&gt; logger)
        {
            InitializeComponent();
            _httpClientFactory = httpClientFactory;
            _logger = logger;
        }

        private async void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            var client = _httpClientFactory.CreateClient();
            var tokenResponse =
                await client.PostAsJsonAsync(&quot;https://localhost:5001/api/login/pos&quot;, new LoginCredentials(UsernameTextBox.Text, PasswordBox.Password));

            if (tokenResponse.IsSuccessStatusCode)
            {
                LoginResult loginResult = await tokenResponse.Content.ReadFromJsonAsync&lt;LoginResult&gt;();
                string token = loginResult.Token;
                SetPrincipal(token);
            }
            else
            {
                MessageBox.Show(await tokenResponse.Content.ReadAsStringAsync(), &quot;Login failed&quot;);
            }
        }

        private void SetPrincipal(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var jwtToken = tokenHandler.ReadJwtToken(token);

            var claims = jwtToken.Claims;
            var identity = new ClaimsIdentity(claims);
            var principal = new ClaimsPrincipal(identity);
     
            System.Threading.Thread.CurrentPrincipal = principal;
            AppDomain.CurrentDomain.SetThreadPrincipal(principal);
        }
    }

I was reading about Thread.CurrentPrincipal but I am unsure if that is the correct approach.

Is there a common approach to store and access user information in a net 7 Wpf app or do I have to implement it myself?

答案1

得分: 1

在一个.NET 7 WPF应用程序中存储和访问用户信息是否有常用的方法,还是我需要自己实现?

如果您没有要求跨不同实例/运行的应用程序存储信息,您可以将其存储在应用程序的某个变量中,例如:

public static class ApplicationService
{
    internal static string Token { get; set; }
}

如果您在应用程序中使用IPrincipal执行授权操作,使用Thread.CurrentPrincipal属性存储它似乎是一个不错的方法。

英文:

>Is there a common approach to store and access user information in a net 7 Wpf app or do I have to implement it myself?

If you don't have a requirement to store the information across different instances/runs of your app, you could just store it in a variable somewhere in your application, e.g.:

public static class ApplicationService
{
    internal static string Token { get; set; }
}

If you use an IPrincipal to perform authorization in your app, storing it using the Thread.CurrentPrincipal property seems like a good approach.

huangapple
  • 本文由 发表于 2023年6月27日 19:45:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定