question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to access manager after adding Piranha CMS to existing .NET Core 3.1 project

See original GitHub issue

I have an existing .NET Core 3.1 project which already has a database created. It’s using Identity for authentication with users and roles already created.

I’m trying to add Pirahna CMS to the application. I want to allow admin users the ability to create pages that would be accessible via a URL slug to non-authenticated users. Ideally, the admin user wouldn’t need to log into the Piranha Manager (but even if they can with their existing account, that is fine).

I’m running into an issue where I can’t access the manager via http://mysite/manager. When I try to access the URL I see the following in the logs:

info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] Authorization failed. info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[13] AuthenticationScheme: Identity.Application was forbidden.

I’ve read that access to the manager can be granted via roles/claims. I manually created a role in my existing Identity role table called “PiranhaAdmin” and I assigned that role to my user. However I still can’t access the manager so I’m assuming this is wrong.

I tried following the Getting Started guide to set everything up but I’m not sure if I’m missing something.

This is my code from the ConfigureServices method in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Configure database context
    services.AddDbContext<ApplicationDbContext>(options =>
    {
        options.UseSqlServer(new SqlConnection(Configuration.GetConnectionString("DefaultConnection")),
            x =>
            {
                x.MigrationsAssembly("MyApplication.Data");
            });
    });

    // Configure Identity implementation
    services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.SignIn.RequireConfirmedAccount = false)
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders()
        .AddUserManager<ApplicationUserManager>()
        .AddRoleManager<ApplicationRoleManager>();

    // Configure localization
    // ... ommitting code related to localization configuration

    // Configure controllers with Localization
    services.AddControllersWithViews(options =>
    {
        options.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline)));
    })
    .AddViewLocalization(
        LanguageViewLocationExpanderFormat.Suffix,
        opts => { opts.ResourcesPath = "Resources"; })
    .AddDataAnnotationsLocalization();

    // Configure Razor Pages with Localization
    services.AddRazorPages(options => { options.Conventions.Add(new CultureTemplateRouteModelConvention()); })
    .AddViewLocalization(
        LanguageViewLocationExpanderFormat.Suffix,
        opts => { opts.ResourcesPath = "Resources"; })
    .AddDataAnnotationsLocalization()
    .AddRazorRuntimeCompilation()
    .AddPiranhaManagerOptions();  

    // Add PiranhaCMS
    services.AddPiranha();
    services.AddPiranhaApplication();
    services.AddPiranhaBlobStorage(new StorageCredentials(Configuration["Azure:StorageAccount"],
        Configuration["Azure:StorageKey"]), Configuration["Azure:ContainerName"]);
    services.AddPiranhaImageSharp();
    services.AddPiranhaManager();
    services.AddPiranhaTinyMCE();
    services.AddPiranhaMemoryCache();
    services.AddPiranhaEF<SQLServerDb>(db =>
        db.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    // Adding custom application services here
    // ... code ommitted
}

And here is the code from my Configure method in Startup.cs:

public void Configure(
    IApplicationBuilder app, 
    IWebHostEnvironment env,
    IApi api)
{
    // Initialize Piranha
    App.Init(api);

    // Configure cache level
    App.CacheLevel = Piranha.Cache.CacheLevel.Full;

    // Build content types
    new ContentTypeBuilder(api)
        .AddAssembly(typeof(Startup).Assembly)
        .Build()
        .DeleteOrphans();

    // Configure editor
    //Piranha.Manager.Editor.EditorConfig.FromFile("editorconfig.json");

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    // Add call to use Piranha
    app.UsePiranha();

    app.UseRouting();
    app.UseRequestLocalization();

    app.UseAuthentication();
    app.UseAuthorization();

    

    // Configure Piranha
    app.UsePiranhaIdentity();
    app.UsePiranhaManager();
    app.UsePiranhaTinyMCE();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "LocalizedDefault",
            pattern: "{culture:culture}/{controller=Home}/{action=Index}/{id?}"
        );
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();

        endpoints.MapPiranhaManager();
    });
}

At this point the connection to the database is working because I see the new Piranha tables that were created.

I’ve read the Authentication doc (https://piranhacms.org/docs/architecture/authentication) which is where I got the idea to create and assign the PiranhaAdmin role.

I also read the Authentication Extension doc (https://piranhacms.org/docs/extensions/authentication) and tried to create a custom implementation of ISecurity. I added it to DI container and placed breakpoints in each method but they’re never triggered. This was my ISecurity implementation:

public class MyAuthService : ISecurity 
{
    public bool Authenticate(string username, string password)
    {
        return true;
    }

    public async Task<bool> SignIn(object context, string username, string password)
    {
        return true;
    }

    public Task SignOut(object context)
    {
        return;
    }
}

I wouldn’t expect it to trigger anything in that class because it’s not getting to the point where I can provide credentials.

So I’m not sure what I’m missing or doing wrong here. Any help is greatly appreciated.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
howardmatcommented, May 15, 2020

After assigning the Admin claim with a few others (Pages, PagesAdd) I was able to see the manager. Now I can try getting some pages setup 😃

Thanks so much for your help!

0reactions
tidyuicommented, May 14, 2020

As you can see there are a lot of claims for accessing the different parts of the manager.

Skärmavbild 2020-05-14 kl  13 12 02
Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to login to PiranhaCMS after setup
I've tried using existing database, the incluede CE database, and event with a new database. It all comes down to the same problem,...
Read more >
Project Setup
NET Core . Start by creating a new empty directory with the name you want for your project. We will name the directory...
Read more >
Application Setup
This section shows how to setup and configure Piranha in your Application Startup and is intended for users who wants to create their...
Read more >
Middleware
The middleware components are added when calling UseCms in ConfigureServices . The following code sets up middleware for all available content.
Read more >
Piranha CMS - Open Source, Cross Platform Asp.NET Core ...
Piranha is the fun, fast and lightweight framework for developing cms-based web applications with .NET.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found