Dan*_*son 5 c# asp.net-mvc identity
我环顾四周,试图找到针对我的特定问题的答案。我基本上是使用外部库来检查用户是否通过用户名和密码在我们的域内得到了授权。
var authenticatedUser = ECNSecurity.SecurityChecker.AuthenticateUser(model.Username, model.Password);
无论用户是不是,都返回true或false。我希望能够在某些控制器方法上使用[Authorize]属性。是否可以在不使用身份的情况下做到这一点?还是我需要获取身份并创建自己的继承了Identity UserModel的用户?然后,当我将该用户标记为已通过身份验证时,将以某种方式获取[Authorize]属性?
我正在看教程和阅读,但是我确实有一个更具体的用例,我找不到直接的答案。如果我问的太愚蠢,请原谅我在此安全/授权领域的经验不足。也许我没意识到的是[Authorize]属性仅适用于Identity用户。
任何输入将不胜感激。谢谢。
如果您只想授权过滤器工作,则不需要 ASP.NET Identity。
您只需要ASP.NET MVC 中的OWIN Cookie 中间件。如果需要,您还可以添加用户名等声明。
您需要执行以下几个步骤 -
在启动时配置 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")
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在GitHub上查看我的工作示例项目。