-1

* Scenario: *

I have got a web api service application made in C# Visual Studio 2012. This web service has an "Areas" folder with the default project of Web Api Help Page.

* Problem: *

By requeriment, I must to implement a manual input to authenthicate and authorize the user that can read the Web Api Help Page. But NOT in the web service.

So far so good, I've made an account controller, log in procedures, get roles from the database, etc etc.
But now, what I try to realize is how to write the Application_PostAuthenticateRequest procedure in the global.asax, because the only global.asax that I've is from the main project, the Web API Help Page has not his own.

* QUESTION *
How can I write the Application_PostAuthenticateRequest method without impacting on the main service, in order to use the Authorization attributes ONLY in the Web API Help Page?

Thanks and kind regards,

4

1 回答 1

1

如果我理解您的问题,您只想通过授权路由到特定路径?

如果是这种情况,您可以使用路由作为 WebAPI 2 的一部分

在里面WebAPIConfig.cs添加以下配置

public static void Register(HttpConfiguration config)
{
 //Enable attribute routing
 config.MapHttpAttributeRoutes();

//... additional configuraitons
}

然后在您的 API 控制器中,您可以设置一个独立于默认值的路由并添加您需要的任何属性:

[Route("apiname/authroizedLogin")]
[Authorize(Roles="admin")]
public void IHttpActionResult(string username, stringpassword)
{
   try
   {
    dosomething...
    return Ok(somecontext);
   }
   catch(exception e)
   {
    return BadResponse(e.message);
   }
}

这是一个链接,其中包含有关 WebAPI 2 中路由的更多信息

编辑

关于访问角色。这取决于您的实施。我个人不喜欢使用 global.asx,因为它会更频繁地发出数据库请求。我需要有关您的实施的更多信息才能提出任何真正的建议。但是这里有几个选项。如果您使用基于声明的身份验证,则角色可以是声明的一部分,并将作为 http 上下文/请求的一部分传递给 API。从这里您可以得出身份:

   public long RoleId
    {
        get
        {
            var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
            string id = identity.Claims.Where(c => c.Type == "http://myschema.com/app/claims/roleid")
                .Select(c => c.Value).SingleOrDefault();

            //return 0 if no claim is located
            return (!String.IsNullOrEmpty(id)) ? Convert.ToInt32(id) : 0;
        }
        set
        {
            _userId = value;
        }
    }

如果您不使用声明,则另一种选择是生成一个FormsAuthenticaitonTicket,一旦用户通过身份验证,它就可以被加密并存储为 cookie。

于 2015-02-24T14:16:30.133 回答