Impersonating user with Entity Framework

你说的曾经没有我的故事 提交于 2019-11-27 04:53:03

问题


So we have our web app up and going with entity framework. What we'd like to do is impersonate the current user when we're accessing the DB. We're not interested in setting impersonation up in our web config.

Ideally using something like this: http://geekswithblogs.net/jkurtz/archive/2007/08/27/114992.aspx when we're about to access data.

UPDATED: I'm looking for a way to abstract this code out so I don't have to have it in every repository function call.


回答1:


Your EF connection string is going to need to be set up for using a trusted connection.

You won't need to set up Impersonation in your web.config, but you do need to be using Windows Authentication.

Then just do this:

using (((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
using (var dbContext = new MyEntityFrameworkContainer())
{
    ...
}

Any code inside the curly braces of the using statements will run as the authenticated user.



来源:https://stackoverflow.com/questions/1954944/impersonating-user-with-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!