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

时间:2019-06-19 16:28:46

标签: c# authentication servicestack app-config anonymous

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

如何以可能的简便方式实现这一目标,或者已经准备好使用某些东西?

我试图将以下设置禁用。

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

但是,当我在SwaggerUI中单击“尝试请求”时,仍然会出现“用户/密码”窗口的提示。

代码下方

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 { ...}

2 个答案:

答案 0 :(得分:0)

据我所知,不可能在运行时在代码中禁用Windows身份验证,因为它是由IIS / ASP.NET在请求到达ServiceStack和ASP.NET应用程序之前触发的。

答案 1 :(得分:0)

最后,我找到了快速启用/禁用身份验证的解决方案。我们可以通过动态添加身份验证属性来解决该问题。也可以轻松更改为使用其他身份验证提供程序。

因此,我们可以通过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));
    ...
 }