MVC Core 如何强制/设置所有操作的全局授权? [英] MVC Core How to force / set global authorization for all actions?

查看:23
本文介绍了MVC Core 如何强制/设置所有操作的全局授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为 MVC Core 中的所有操作强制/设置全局授权?

我知道如何注册全局过滤器 - 例如我有:

I know how to register global filters - for example I have:

Setup.cs

services.AddMvc(options =>
{
    options.Filters.Add(new RequireHttpsAttribute());
});

这很好用,但我不能为 Authorize 添加相同的内容:

and this works fine, but I can't add the same for Authorize:

options.Filters.Add(new AuthorizeAttribute());

我有错误:

无法从Microsoft.AspNet.Authorization.AuthorizeAttribute()"转换为System.Type"

(方法.Add()需要IFilterMetadata类型)


我知道 - 从类似的问题 - 这适用于 MVC4-5...所以必须在 MVC Core 上进行一些更改...


I know - from similar questions - that this works on MVC4-5... So something must changed on MVC Core...

有人知道吗?

推荐答案

services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

这篇关于MVC Core 如何强制/设置所有操作的全局授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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