【问题标题】:Testing if a request is anonymous or authenticated WebAPI 2 + Identity测试请求是匿名的还是经过身份验证的 WebAPI 2 + Identity
【发布时间】:2015-11-13 03:56:40
【问题描述】:

我正在使用 WebAPI 2 + ASP.NET 身份

在我的 ApiController 方法之一中,我想测试一个特定的 HTTP 请求是否来自经过身份验证的客户端(即请求是否包含授权标头)。

以下方法可行,但也许有更好的方法?

private AuthContext db = new AuthContext();

// GET api/Orders/
[AllowAnonymous]
public async Task<IHttpActionResult> GetOrder(int id)
{
    // ApplicationUser is an IdentityUser.
    ApplicationUser currentUser = null;

    try
    {
        UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
        currentUser = await userManager.FindByNameAsync(User.Identity.GetUserName());
    }
    catch (Exception)
    {
    }

    if ( currentUser == null )
    {
        // Anonymous request.
        // etc...




    } else {
        // Authorized request.
        // etc...
    }
}

我正在使用默认路由模板。另一种选择是为授权请求和匿名请求(用适当的数据注释装饰)路由到 2 种不同的方法。

【问题讨论】:

  • 你应该可以使用User.Identity.IsAuthenticated -- 你试过了吗?
  • 谢谢,这行得通!错过了那个。如果您想输入答案,我会将其标记为正确。

标签: asp.net-identity asp.net-web-api2 asp.net-web-api asp.net-web-api-routing


【解决方案1】:

在 WebApi 的 ApiController 类中,有一个 User 属性(您已经在代码中使用了该属性:User.Identity.GetUserName())。

这个User 属性是一个IPrincipal 实例,它有一个属性Identity,它是IIdentity 的一个实例。

ApiController 方法的代码中,您可以通过测试User.IdentityIsAuthenticated 属性来测试当前请求的用户是否经过身份验证。

例如:

if ( User.Identity.IsAuthenticated)
{
    // Authenticated user...do something
}
else
{
   // anonymous..do something different
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-09
    • 2018-05-21
    • 2017-06-28
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    相关资源
    最近更新 更多