winforms ASP.NET Core Web API和Azure SignalR服务中的身份验证

lokaqttq  于 8个月前  发布在  .NET
关注(0)|答案(2)|浏览(81)

我有一个ASP.NET Core Web API,其中我托管了一个SignalR集线器。
我已经创建了一个Azure SignalR服务,SignalR中心在启动时连接到该服务,使用创建Azure SignalR服务时提供的连接字符串。
我有一个winforms客户端应用程序,在启动时连接到SignalR集线器。Winforms应用程序的用户使用IWA进行身份验证。
我的Web API只用于托管SignalR Hub,所以我不会在我的Web API中添加/使用控制器。但是添加功能来支持Winforms客户端应用程序。
所以我的问题是,由于它托管在Azure中,我需要保护API免受未经授权的访问。如果我理解正确的话,这可以通过在项目模板附带的控制器上添加[Authorize]来实现?
或者我可以简单地删除控制器,这样外部的任何人都无法访问API?
我是否也需要以某种方式保护我的SignalR集线器免受未经授权的访问?

ttp71kqs

ttp71kqs1#

如果我理解正确的话,这可以通过在项目模板附带的控制器上添加[Authorize]来实现?
是的,要保护和验证Controller/Web API操作方法,必须添加[Authorize]属性。
当我们在创建WebApp时选择身份验证类型时,

默认情况下,Controller Action方法将使用[Authorize]属性进行装饰。

  • 控制器自动生成代码:*
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web.Resource;

namespace SignalR.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "---------"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }     
    }
}
  • 成功通过身份验证的成员将只能访问上述操作方法。

我可以简单地删除控制器,这样外部的人就不能访问API了吗?

  • 由于您已经添加了[Authorize]属性,因此只有经过身份验证的用户才能访问该方法。
  • AFAIK,无需删除控制器。如果删除控制器操作方法,则需要直接访问Azure SignalR服务。
  • 我试图通过删除控制器运行应用程序,我没有遇到任何问题.

  • 在这种情况下,我们需要将[Authorize]标记添加到本文中提到的Azure Signal R方法中。

我是否需要以某种方式保护我的SignalR集线器免受未经授权的访问?
是的,我们也可以为SignalR服务添加[Authorize]属性。
请参阅Various Ways to Authenticate and Authorize SignalR Hubs了解更多详细信息。

py49o6xq

py49o6xq2#

我可以简单地删除控制器,这样外部的人就不能访问API了吗?回答:是
我是否需要以某种方式保护我的SignalR集线器免受未经授权的访问?答:您也可以在您的Web应用程序中添加IWA。
我创建了一个全新的asp.net核心mvc项目(我知道你正在使用webapi),这对我来说很容易在网页上测试。
感谢Harshitha的测试结果,我们可以删除所有的控制器,它也可以正常工作。
我已经在项目中启用了Windows身份验证。比如:

builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme)

. add();
我们需要为hub类添加[Authorize]。

然后我创建一个winform应用程序,下面是我的代码:

Form1.Designer.cs

namespace WinFormsApp1
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            button1 = new Button();
            button2 = new Button();
            richTextBox1 = new RichTextBox();
            SuspendLayout();
            // 
            // button1
            // 
            button1.Location = new Point(38, 28);
            button1.Name = "button1";
            button1.Size = new Size(156, 23);
            button1.TabIndex = 1;
            button1.Text = "without IWA log-in";
            button1.UseVisualStyleBackColor = true;
            button1.Click += button1_Click;
            // 
            // button2
            // 
            button2.Location = new Point(38, 75);
            button2.Name = "button2";
            button2.Size = new Size(156, 23);
            button2.TabIndex = 2;
            button2.Text = "IWA connect to signalr";
            button2.UseVisualStyleBackColor = true;
            button2.Click += button2_Click;
            // 
            // richTextBox1
            // 
            richTextBox1.Location = new Point(38, 127);
            richTextBox1.Name = "richTextBox1";
            richTextBox1.Size = new Size(694, 280);
            richTextBox1.TabIndex = 3;
            richTextBox1.Text = "";
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 15F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(800, 450);
            Controls.Add(richTextBox1);
            Controls.Add(button2);
            Controls.Add(button1);
            Name = "Form1";
            Text = "Form1";
            Load += Form1_Load;
            ResumeLayout(false);
        }

        #endregion
        private Button button1;
        private Button button2;
        private RichTextBox richTextBox1;
    }
}

Form1.cs

using Microsoft.AspNetCore.SignalR.Client;
using System.Data.Common;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        HubConnection _connection;
        public Form1()
        {
            InitializeComponent();
            _connection = new HubConnectionBuilder().WithUrl($"https://localhost:44356/mainHub")
                .WithAutomaticReconnect()
                .Build();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            _connection = new HubConnectionBuilder().WithUrl("https://localhost:44376/mainhub").Build();
            try
            {
                _connection.StartAsync();

                for (int i = 0; i < 10; i++)
                {
                    richTextBox1.AppendText("without IWA log-in   " +DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   " + _connection.State.ToString() + "\r\n");
                    if (_connection.State.ToString() == "Connected" || _connection.State.ToString() == "Disconnected") {
                        return;
                    }
                    Thread.Sleep(1000);
                }
                
            }
            catch (Exception ex)
            {
                richTextBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   " + ex.ToString() + "\r\n");
                throw;
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            _connection = new HubConnectionBuilder().WithUrl("https://localhost:44376/mainhub", options =>
            {
                options.UseDefaultCredentials = true;
            }).Build();
            _connection.StartAsync();
            for (int i = 0; i < 10; i++)
            {
                richTextBox1.AppendText("IWA connect to signalr   " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   " + _connection.State.ToString() + "\r\n");
                if (_connection.State.ToString() == "Connected")
                {
                    return;
                }
                Thread.Sleep(1000);
            }

        }

    }
}

以及测试结果。

最重要的事情

我们应该使用这个包Microsoft.AspNetCore.SignalR.Client并创建基于.net core的Winform应用程序,而不是.net framework。

相关问题