0

我正在学习如何使用 Asp.Net MVC Identity 2.0。

我有适用于 OAuth Bearer 的代码

    [HttpGet]
    [ActionName("Authenticate")]
    [AllowAnonymous]
    public String Authenticate(string user, string password)
    {
        if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(password))
        {
            return "Failed";
        }

        var userIdentity = UserManager.FindAsync(user, password).Result;
        if (userIdentity != null)
        {
            if (User.Identity.IsAuthenticated)
            {
                return "Already authenticated!";
            }

            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, user));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));

            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(1));

            string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
            return AccessToken;
        }
        return "Failed in the end";
    }

这是 Startup.Auth.cs 的代码

    //This will used the HTTP header Authorization: "Bearer 1234123412341234asdfasdfasdfasdf"
    OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
    app.UseOAuthBearerAuthentication(OAuthBearerOptions);

我查看了 ClaimsIdentity 和 AuthenticationTicket 的源代码,但没有看到票证是如何为身份注册的。

我的问题是这张票是如何在 Owin 管道中注册的?

我的目标是尽可能撤销这张票。

提前致谢。

4

1 回答 1

0

首先,这是Taiseer Joudeh 撰写的关于 ASP.NET Identity 2 的精彩教程。

这是将承载令牌处理添加到 OWIN 应用程序管道的行。

app.UseOAuthBearerAuthentication(OAuthBearerOptions);

另外,您是否自己编写了授权提供程序?我的启动代码看起来更像这样:

app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

PublicClientId = "self";
OAuthServerOptions = new OAuthAuthorizationServerOptions
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/Token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1440),     //TODO: change to smaller value in production, 15 minutes maybe
    Provider = new SimpleAuthorizationServerProvider(PublicClientId),
    RefreshTokenProvider = new SimpleRefreshTokenProvider()
};

app.UseOAuthAuthorizationServer(OAuthServerOptions);

OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
app.UseOAuthBearerAuthentication(OAuthBearerOptions);

然后我的 SimpleAuthorizationServerProvider 有一个像这样的 Grant 方法:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";

    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

    var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

    ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

    if (user == null)
    {
        context.SetError("invalid_grant", "The user name or password is incorrect.");
        return;
    }

    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    identity.AddClaim(new Claim("sub", context.UserName));

    foreach (var role in userManager.GetRoles(user.Id))
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, role));
    }

    var props = new AuthenticationProperties(new Dictionary<string, string>
    {
        {"as:client_id", context.ClientId ?? string.Empty}
    });

    var ticket = new AuthenticationTicket(identity, props);
    context.Validated(ticket);
}

几乎所有这些都是基于上面提到的教程。希望能帮助到你。

更新根据本页上 的泰瑟尔,没有标准的方法来撤销令牌。

撤销经过身份验证的用户的访问:一旦用户获得长期访问令牌,只要他的访问令牌未过期,他就能够访问服务器资源,除非授权服务器实现自定义逻辑,否则没有标准的方法来撤销访问令牌这迫使您将生成的访问令牌存储在数据库中,并对每个请求进行数据库检查。但是使用刷新令牌,系统管理员可以通过简单地从数据库中删除刷新令牌标识符来撤销访问,因此一旦系统使用已删除的刷新令牌请求新的访问令牌,授权服务器将拒绝此请求,因为刷新令牌不再可用(我们将详细介绍这一点)。

但是,这是一种有趣的方法,可以满足您的需求。它只需要一些自定义实现。

于 2016-06-14T17:24:12.897 回答