【问题标题】:Allow all api controlleraction requests when in demo mode在演示模式下允许所有 api controlleraction 请求
【发布时间】:2018-02-15 22:34:57
【问题描述】:

我有一个 webapi,我在其中使用属性 [AllowAnonymous] 和 [AuthorizeAttribute] 控制访问。我还创建了一个自定义属性来为授权添加一些逻辑。 Web api 使用不记名令牌进行身份验证。 我的项目中有一个设置(一个名为 InDemo 的布尔值),目的是让我的所有操作都允许匿名请求,换句话说,就像所有操作都具有 [AllowAnonymous] 属性一样。

OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider("self"),
                AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(30000),
                AllowInsecureHttp = true
             };

            app.UseOAuthBearerTokens(OAuthOptions);


public class CustomApiAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (Settings.Default.InDemo)
           return true;

        // ... more custom validations
    }
}

只要我的请求包含有效的不记名令牌,就可以正常工作,然后调用 IsAuthorized 并且我可以绕过自定义验证。但是,如果令牌无效,则永远不会调用 IsAuthorized 并且会发送“此请求的授权已被拒绝”响应。 现在我想在 InDemo 设置为 true 时忽略令牌,即具有 [AllowAnonymous] 的行为。

【问题讨论】:

    标签: c# asp.net-web-api oauth bearer-token


    【解决方案1】:

    好的,这就是我解决它的方法。 我让我的 CustomApiAuthorizeAttribute 实现 IAuthenticationFilter 并将上下文原则设置为始终经过身份验证的原则。

        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            if (Settings.Default.AllowAnonymous)
                      context.Principal = new AuthenticatedPrincipal(Thread.CurrentPrincipal);
        }
    
        public class AuthenticatedPrincipal : IPrincipal
        {
            private readonly IPrincipal principalToWrap;
    
            public AuthenticatedPrincipal(IPrincipal principalToWrap)
            {
                this.principalToWrap = principalToWrap;
                Identity = new AuthenticatedIdentity(principalToWrap.Identity);
            }
    
            public bool IsInRole(string role)
            { return principalToWrap.IsInRole(role); }
    
            public IIdentity Identity { get; }
        }
    
        public class AuthenticatedIdentity : IIdentity
        {
            public AuthenticatedIdentity(IIdentity identityToWrap)
            {
                Name = identityToWrap.Name;
                AuthenticationType = identityToWrap.AuthenticationType;
            }
    
            public string Name { get; }
            public string AuthenticationType { get; }
    
            public bool IsAuthenticated => true;
        }
    

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 2018-02-14
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 2014-10-31
      相关资源
      最近更新 更多