gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:20:12 26 4
gpt4 key购买 nike

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

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

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

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

任何输入将不胜感激。谢谢。

最佳答案

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

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

这里有几个你需要的步骤-

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 查看我的工作示例项目.

关于c# - 使用没有身份的 [Authorize] 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47579173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com