如何向RazorPages添加授权? [英] How to add authorization to RazorPages?

查看:628
本文介绍了如何向RazorPages添加授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了当前的官方Microsoft文档并且找不到适当的方法来涵盖如何处理RazorPages的授权.

I have looked at the current official Microsoft Docs and was unable to find anything properly covering how to handle authorization for RazorPages.

我发现您可以像这样将AuthorizeAttribute添加到PageModel:

I figured out that you can add the AuthorizeAttribute to the PageModel like so:

// using Microsoft.AspNetCore.Authorization

[Authorize]
public class IndexModel : PageModel
{
    ...
}

我不想在每个页面上重复此操作.有更好的方法吗?

I don't want to repeat this for every page. Is there a better way?

推荐答案

您可以在ConfigureServices方法下配置授权.这是一个示例:

You can configure authorization under the ConfigureServices method. Here is an example :

services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AuthorizeFolder("/MembersOnly");
        options.Conventions.AuthorizePage("/Account/Logout");

        options.Conventions.AuthorizeFolder("/Pages/Admin", "Admins"); // with policy
        options.Conventions.AllowAnonymousToPage("/Pages/Admin/Login"); // excluded page

        options.Conventions.AllowAnonymousToFolder("/Public"); // just for completeness
    });

上面的示例是从示例在官方存储库中提供.

AuthrorizeFolder将限制对整个文件夹的访问,而AuthorizePage将根据单个页面来限制访问. AllowAnonymousToFolderAllowAnonymousToPage与此相反.

The AuthrorizeFolder will restrict access to the entire folder, whereas the AuthorizePage would be restricting access based on the individual page. The AllowAnonymousToFolder and AllowAnonymousToPage doing the opposite, accordingly.

对于上述特定文档,到今天为止,该文档仍在完成中..但是,您可以阅读其进度并在此处进行跟踪 https://github.com/aspnet/Docs/issues/4281

For specific documentation on the above, as of today, the documentation is still being completed. However, you can read about the progress of it and track it here https://github.com/aspnet/Docs/issues/4281

这篇关于如何向RazorPages添加授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆