【问题标题】:Web API 2 use Windows Authentication for public usersWeb API 2 对公共用户使用 Windows 身份验证
【发布时间】:2016-01-21 04:40:37
【问题描述】:

如何在 WEB API 中为也将在公共网络上的内部用户使用 Windows 身份验证? REST API 将面向公众,需要对 Intranet 用户和 Internet 用户进行身份验证。基本上,不在 Active Directory 上的任何人都将无法访问它,并且将授权另外一个 AD 组。

目前的 REST 服务有一个安全过滤器,可以使用属性过滤器来验证令牌。

public class RestAuthorizeAttribute : AuthorizeAttribute
{
    private const string SecurityToken = "token";

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (Authorize(actionContext))
        {
            return;
        }

        HandleUnauthorizedRequest(actionContext);
    }


    private bool Authorize(HttpActionContext actionContext)
    {
        try
        {
            HttpRequestMessage request = actionContext.Request;

            //Extract Token from the Request. This will work for all.
            // E.g \api\Facilitiles\Token\298374u23lknndsjlkfds==
            //      \api\Ward\123\Token\298374u23lknndsjlkfds==
            string path = request.RequestUri.LocalPath;

            int indexOfToken = path.IndexOf(SecurityToken) + SecurityToken.Length + 1; 

            string token = path.Substring(indexOfToken);

            bool isValid = SecurityManager.IsTokenValid(token, IpResolver.GetIp(request),request.Headers.UserAgent.ToString());
            return isValid;
        }
        catch (Exception ex)
        {
            string av = ex.Message;
            return false;
        }
    }
}

然后将其应用于特定的控制器,如下所示:

[RestAuthorize]
[RoutePrefix("api/patient")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class PatientDetailsController : ApiController
{

    PatientDetailsRetriever _patientDetailsRetriever;

    // GET: api/patient/meds/personId/{personId}/token/{token}
    [Route("meds/personId/{personId}/token/{token}")]
    [HttpGet]
    public HttpResponseMessage GetMeds(Int64 personId, string token)
    {
        List<Medication> meds;
.....

客户端生成令牌,其中包括用户名、密码和域等。

在 IIS (web.config) 中启用 Windows 身份验证足以验证本地用户。但是当用户在网络之外并发送凭据时,这如何工作?

【问题讨论】:

    标签: rest asp.net-web-api2 windows-authentication


    【解决方案1】:

    我找到了答案on this SO post

    //create a "principal context" - e.g. your domain (could be machine, too)
    using(PrincipalContext pc = new PrincipalContext(ContextType.Domain,   "YOURDOMAIN"))
    {
        // validate the credentials
        bool isValid = pc.ValidateCredentials("myuser", "mypassword");
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 2017-03-04
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2014-05-02
      • 2016-07-17
      相关资源
      最近更新 更多