如何使用配置参数或变量启用或禁用身份验证?

How to enable or disable authentication using config parameter or variable?

我想在配置中实现一个开关,允许启用 (windowsAuth=true) 或禁用 [​​=25=] 身份验证 (windowsAuth=false),因此它将被用作匿名。

如何以尽可能简单的方式实现这一点,或者也许已经有一些东西可以使用了?

我尝试将以下设置禁用。

<system.web>
    <authentication mode = "None" />
    <authorization >
        <allow users="*" />
    </authorization>
</system.web>

但是在SwaggerUI中点击Try Request时,仍然出现user/pw window的提示

代码下方

private void SetupPlugins(Container container)
{
    container.Register<IDbConnectionFactory>(c =>
        new OrmLiteConnectionFactory(connString, SqlServerDialect.Provider));

    container.RegisterAs<OrmLiteCacheClient, ICacheClient>();

    container.Resolve<ICacheClient>().InitSchema();

    container.Register<IAuthRepository>(c =>
        new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));

    container.Resolve<IAuthRepository>().InitSchema();

    Plugins.Add(new AuthFeature(() => new AuthUserSession(), 
    new IAuthProvider[] {
            new AdGroupAuthProvider(container.Resolve<IActiveDirectoryAuthHelper>(),
            GlobalConfiguration.Instance.AllowedActiveDirectoryGroup)
        }
    ));
}

internal class AdGroupAuthProvider : BasicAuthProvider
{
    private readonly IActiveDirectoryAuthHelper _adLoggingHelper;
    private readonly string _loggedUserAdGroup;

    public AdGroupAuthProvider(IActiveDirectoryAuthHelper loggingHelper, string loggedUserAdGroup)
    {
        _adLoggingHelper = loggingHelper;
        _loggedUserAdGroup = loggedUserAdGroup;
    }
    public override bool Authenticate(IServiceBase loggingServiceBase, string userName, string password)
    {
        return _adLoggingHelper.HasUserAssignedGroup(userName, password, _loggedUserAdGroup);
    }
}

[Authenticate(ApplyTo.Get)]
[Route("/someRoute", "GET")]
public class someRequest { ...}

据我所知,无法在运行时在代码中禁用 Windows 身份验证,因为它是在请求到达 ServiceStack 和您的 ASP.NET 之前由 IIS/ASP.NET 触发的申请.

最后,我找到了快速 enable/disable 身份验证的解决方案。我们可以通过动态添加 Authenticate 属性 来解决它。这也可以很容易地更改为使用不同的身份验证提供程序。

因此,我们可以很容易地通过这个 AuthenticateAttribute 来确定请求 A、B 或 C 是​​否必须启用身份验证。

private void SetupPlugins(Container container, ILog log)
{ ...
    bool activeDirectoryAuthentication = ToBoolean(GlobalConfiguration.Instance.ActiveDirectoryAuthentication);
    ApplyTo applyTo = ApplyTo.Get;
    if (!activeDirectoryAuthentication) applyTo = ApplyTo.None;

    typeof(RequestA).AddAttributes(new AuthenticateAttribute(applyTo));
    typeof(RequestB).AddAttributes(new AuthenticateAttribute(applyTo));
    typeof(RequestC).AddAttributes(new AuthenticateAttribute(applyTo));
    ...
 }