如何禁用访问 - 使用Bearer令牌请求标准MVC控制器

时间:2017-07-09 14:56:57

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-identity

我在使用WebApi的MVC项目中拥有简单的Cookie和Bearer Token授权。我想禁用Bearer在我的标准MVC控制器上的访问。

现在是我的情况:

  • 标准MVC控制器访问承载 Cookie
  • 网络Api控制器访问仅承载

我希望:

  • 标准MVC控制器访问仅限Cookie
  • 网络Api控制器访问仅承载

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter("Bearer"));
    }
}

Startup.Auth.cs

public partial class Startup
{
    public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
        app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
}

是否可以拥有自定义授权属性?像这样: [授权(&#34; OnlyCookie&#34;]

我看到了类似的解决方案,但它适用于SinglePageAplication,我不知道如何在我的.NET MVC 4应用程序中实现它 - 我在这里看到它:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme

当我尝试添加&#39; AuthenticationScheme =&#34; Cookie&#34; &#39;时,compilator会给我错误: CookieAuthenticationOptions&#39;不包含&#39; AuthenticationScheme

的定义

1 个答案:

答案 0 :(得分:1)

你没有那个属性,因为你没有使用ASP.Net Core。您在问题上发布的链接是ASP.Net Core而不是ASP.NEt MVC。

您可以通过创建自定义授权过滤器属性来执行相同操作。我们将它命名为CustomAuthorizeAttribute,实现将是:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public string AuthenticationType { get; private set; }

    public CustomAuthorize(string authenticationType)
    {
        if (string.IsNullOrWhiteSpace(authenticationType))
        {
            throw new ArgumentNullException(nameof(authenticationType));
        }

        this.AuthenticationType = authenticationType;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (!httpContext.User.Identity.AuthenticationType.Equals(this.AuthenticationType, StringComparison.InvariantCultureIgnoreCase))
        {
            return false;
        }

        return base.AuthorizeCore(httpContext);
    }
}

所以你可以在控制器上使用它:

[CustomAuthorize(DefaultAuthenticationTypes.ApplicationCookie)]