JohnnyBegg43
JohnnyBegg43

Reputation: 117

How to disable access - request to standard MVC Controller with Bearer token

I have simple Cookie and Bearer Token authorization in my MVC project with WebApi. I want to disable access by Bearer on my standard MVC controllers.

This is my situation now:

I want to have:

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))
            }
        });
}

Is it possible to have custom authorization attribute? Like this: [Authorize("OnlyCookie"]

I saw similar solution, but it was for SinglePageAplication, and I dont know how to implement it in my .NET MVC 4 application - I saw it here: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme

When I tried add 'AuthenticationScheme = "Cookie"', compilator gives me error: CookieAuthenticationOptions' does not contain a definition for 'AuthenticationScheme

Upvotes: 1

Views: 1088

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23220

You don't that property because you're not using ASP.Net Core. The link you post on your question is ASP.Net Core not ASP.NEt MVC.

You can do the same by creating a custom authorization filter attribute. Let name it CustomAuthorizeAttribute and the implementation will be:

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);
    }
}

So you can use it like this on your controller:

[CustomAuthorize(DefaultAuthenticationTypes.ApplicationCookie)]

Upvotes: 2

Related Questions