The*_*ght 9 c# asp.net security active-directory asp.net-web-api
我们有一个Web API应用程序,它提供了许多客户端可以调用和使用的Web方法.它将在IIS中托管并具有SSL设置.
用户凭据存储在Active Directory中,但客户端不仅仅位于我们的域中,它们可以位于世界的任何地方,因此我们的理解是我们无法使用Windows集成身份验证.
如上所述,在我们的场景中对用户进行身份验证的最佳方法是什么?
我是否应该要求用户在他们提出的每个请求中在标题中传递用户名/密码?然后我以编程方式对我们的Active Directory验证用户凭据(我们已经有一个组件可以执行此操作),例如通过创建在每个操作执行之前运行的自定义ActionFilter?
另一种方法可能是创建一个HttpModule,它在每个请求之前运行并进行身份验证,如果无效则中止请求.
我的自定义属性如下所示:
public class ActiveDirectoryAuthAttribute : ActionFilterAttribute
{
// todo: load from config which can change depending on deployment environment
private static readonly bool ShouldRequireHttps = false;
public override void OnActionExecuting(HttpActionContext actionContext)
{
IPrincipal principal = this.Authentiate(actionContext);
if (principal == null)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
else
{
this.SetPrincipal(principal);
}
}
private IPrincipal Authentiate(HttpActionContext actionContext)
{
if (IsUriSchemaValid(actionContext.Request.RequestUri))
{
// is the client certificate known and still valid?
// is IP valid?
// find user credentials and validate against AD
// create the Principle object and return it
}
return null;
}
private void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
private static bool IsUriSchemaValid(Uri uri)
{
bool result = true;
if (ShouldRequireHttps)
{
if (!string.Equals(uri.Scheme, "https", StringComparison.InvariantCultureIgnoreCase))
{
result = false;
}
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的控制器操作中,我可以访问Principle对象:
IPrincipal principle = this.User;
Run Code Online (Sandbox Code Playgroud)
如上所述,在我们的场景中对用户进行身份验证/授权的最佳方法是什么?
在上面,如何从IPrinciple创建一个对象?是否有任何现有的.NET类,或者我必须创建自定义类?
我最近在 AD 方面做了很多工作,说实话我想不出另一种方法来处理这个问题。
使用 OAuth 类型方法可能更有意义。提供令牌类型路由,该路由最初将获取用户名和密码,然后将自创作和加密的令牌返回给被调用者。进行第一个初始调用后,将令牌发送回被调用者,然后他们可以在每次后续调用 API 的 Authorization 标头中使用该令牌。
令牌在一次调用或很短的时间内有效。每次您认为要使用该令牌时,请发行另一个令牌。
您还可以考虑为此使用自定义 OAuth 实现,而不是使用数据库进行身份验证过程,而是使用 AD 身份存储并使用 OAuth Bearer 令牌。由于您使用的是 SSL,这实际上非常适合您的场景。
| 归档时间: |
|
| 查看次数: |
8035 次 |
| 最近记录: |