SignalR不允许在方法中使用Autorize

时间:2019-01-29 10:15:18

标签: .net-core signalr

我有一些asp.net核心应用程序。 它使用承载身份验证。

我的auth和SignalR座位。我也使用OpenIddict。

ConfigureServices

       services.AddMvc();
       ...
        services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
        {
            builder
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowAnyOrigin()
            .AllowCredentials();
        }));

        //services.AddSignalR();
        services.AddSignalR(hubOptions =>
        {
            hubOptions.EnableDetailedErrors = true;
        });
        ...
services.AddDefaultIdentity<Account>(opt =>
        {
            opt.Password.RequiredUniqueChars = 1;
            opt.Password.RequireNonAlphanumeric = false;
            opt.Password.RequireLowercase = false;
            opt.Password.RequireDigit = false;
            opt.Password.RequireUppercase = false;
            opt.Password.RequiredLength = Account.MinPasswordLength;

            opt.Lockout.AllowedForNewUsers = false;

            opt.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
            opt.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
            opt.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
        })
        .AddUserManager<AccountManager>()
        .AddRoles<AccountRole>()
        .AddEntityFrameworkStores<ApplicationContext>()
        .AddDefaultTokenProviders();

        services.AddOpenIddict()
          .AddCore(opt =>
          {
              opt.UseEntityFrameworkCore()
                 .UseDbContext<ApplicationContext>();
          })
          .AddServer(opt =>
          {
              opt.SetAccessTokenLifetime(TimeSpan.FromMinutes(5));
              opt.UseMvc();
              opt.AllowCustomFlow(WebConstants.AdminGrantType)
                 .EnableTokenEndpoint("/api/common/auth/Token")
                 .AllowRefreshTokenFlow()
                 .DisableHttpsRequirement()
                 .AcceptAnonymousClients();
          });

        services.AddAuthentication()
            .AddOAuthValidation(options =>
            {
                options.Events.OnRetrieveToken = context =>
                {
                    context.Token = context.Request.Query["access_token"];
                    return Task.CompletedTask;
                };
            });

配置

 app.UseCors("CorsPolicy");
            app.UseAuthentication();

            app.UseSignalR(routes =>
            {
                routes.MapHub<SomeHub >("/someHub");
            });

AuthAccountTypeAttribute

public class AuthAccountTypeAttribute : AuthorizeAttribute
{
    public AuthAccountTypeAttribute(params AccountType[] accountType)
    {
        if (accountType.Any())
        {
            Roles = string.Join(',', accountType.Select(x => x.ToString()));
        }
        AuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme;
    }
}

直接使用Hub

[AuthAccountType(AccountType.Admin)]
public class SomeHub : Hub
{
    private readonly AccountManager _accountManager;
    private readonly IUnitOfWork _unitOfWork;


    public SomeHub (AccountManager accountManager, IUnitOfWork unitOfWork)
    {
        _accountManager = accountManager;
        _unitOfWork = unitOfWork;
    }

    public override Task OnConnectedAsync()
    {
        return base.OnConnectedAsync();
    }

    public async Task OnConnectSmth()
    {

    }

}

如果您使用诸如此类的authorize属性,则一切正常,但如果SomeHub在不使用AuthAccountType和OnConnectSmth的情况下使用

[AuthAccountType(AccountType.Admin)]
public async Task OnConnectSmth()
{

}

它返回401。 我能做什么?

SignalR 1.0.4 .Net Core 2.1

如果我使用基本授权,则会遇到相同的问题

[Authorize(AuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)]

或者如何在Authorize Hub中建立匿名连接?

1 个答案:

答案 0 :(得分:0)

没有在ConfigureServices()中设置DefaultScheme。以及Hub中的奇怪规则。 修复:

services.AddAuthentication(options => { options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme; } );