0

Asp.Net MVC Identity 2.0 を機能させる方法を学んでいます。

OAuthベアラーで機能するこのコードがあります

    [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 のソース コードを確認しましたが、ID に対してチケットがどのように登録されているかわかりません。

私の質問は、このチケットはどのようにして 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);
}

これはほぼすべて、上記のチュートリアルに基づいています。それが役に立てば幸い。

更新このページ の Taiseer によると、トークンを取り消す標準的な方法はありません。

認証されたユーザーからのアクセスの取り消し:ユーザーが長期アクセス トークンを取得すると、アクセス トークンの有効期限が切れていない限り、サーバー リソースにアクセスできます。認可サーバーがカスタム ロジックを実装しない限り、アクセス トークンを取り消す標準的な方法はありません。これにより、生成されたアクセストークンをデータベースに保存し、リクエストごとにデータベースチェックを行う必要があります。ただし、リフレッシュ トークンを使用すると、システム管理者はデータベースからリフレッシュ トークン識別子を削除するだけでアクセスを取り消すことができるため、システムが削除されたリフレッシュ トークンを使用して新しいアクセス トークンを要求すると、リフレッシュ トークンが使用できなくなるため、認可サーバーはこの要求を拒否します。 (これについては詳細を説明します)。

ただし、必要なことを実現できる興味深いアプローチを次に示します。カスタム実装が少し必要です。

于 2016-06-14T17:24:12.897 に答える