使用没有身份的 [Authorize] 属性?

Use [Authorize] Attribute Without Identity?

我环顾四周,试图找到我的具体问题的答案。我基本上是在使用外部库通过用户名和密码检查用户是否在我们的域中获得授权。

var authenticatedUser = ECNSecurity.SecurityChecker.AuthenticateUser(model.Username, model.Password);

Returns true or false 用户是否存在。我希望能够在我的某些控制器方法上使用 [Authorize] 属性。不使用身份就可以做到这一点吗?或者我是否需要获取身份并创建我自己的继承身份用户模型的用户?然后,当我将该用户标记为已通过身份验证时,[Authorize] 属性将以某种方式被拾取?

我正在观看教程和阅读,但我确实有一个更具体的用例,我找不到直接的答案。如果我问的问题太愚蠢,请原谅我在这个 security/authorize 领域缺乏经验。也许我没有意识到 [Authorize] 属性只适用于身份用户。

如有任何意见,我们将不胜感激。谢谢。

如果您只想授权过滤器工作,则不需要 ASP.NET 身份。

您只需要 OWIN Cookie 中间件 在 ASP.NET MVC 中。如果需要,您还可以添加用户名等声明。

以下是您需要执行的几个步骤 -

Startup.cs

在启动时配置 OWIN Cookie 中间件。

[assembly: OwinStartup(typeof(YourApplication.Startup))]
namespace YourApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}

OwinAuthenticationService

public class OwinAuthenticationService : IAuthenticationService
{
    private readonly HttpContextBase _context;
    private const string AuthenticationType = "ApplicationCookie";

    public OwinAuthenticationService(HttpContextBase context)
    {
        _context = context;
    }

    public void SignIn(User user)
    {
        IList<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.GivenName, user.FirstName),
            new Claim(ClaimTypes.Surname, user.LastName),
        };

        ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignIn(identity);
    }

    public void SignOut()
    {
        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignOut(AuthenticationType);
    }
}

您可以在 GitHub 查看我的工作示例项目。

要在 .net framework 版本的 mvc 中使用 cookie 进行授权,您可以简单地使用以下内容

FormsAuthentication.SetAuthCookie(UserName, remember);

remember 是一个布尔值,相当于 "remember me" 选项。

如果需要,请在此处查看我的回答以获取设置中的更多信息How to hide Login fields from the logged user