17

この記事に基づいて、OWIN ベアラー トークン認証を実装しようとしています。ただし、実装方法がわからないベアラー トークンに必要な追加情報が 1 つあります。

私のアプリケーションでは、ベアラー トークンのユーザー情報 (ユーザー ID など) から推測する必要があります。許可されたユーザーが別のユーザーとして行動できるようにしたくないため、これは重要です。これは実行可能ですか?それは正しいアプローチですか?ユーザー ID が GUID の場合、これは簡単です。この場合は整数です。許可されたユーザーは、推測や力ずくで別のユーザーになりすます可能性がありますが、これは容認できません。

このコードを見ると:

public void ConfigureOAuth(IAppBuilder app)
{
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new SimpleAuthorizationServerProvider()
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        using (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser user = await _repo.FindUser(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("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }
}

必要なものに対応するために承認/認証をオーバーライドすることは可能だと思いますか?

4

3 に答える 3

10

context.Rejected余談ですが、カスタム エラー メッセージを設定する場合は、との順序を入れ替える必要がありcontext.SetErrorます。

    // Summary:
    //     Marks this context as not validated by the application. IsValidated and HasError
    //     become false as a result of calling.
    public virtual void Rejected();

context.Rejectedその後に配置するとcontext.SetError、プロパティはfalsecontext.HasErrorにリセットされるため、正しい使用方法は次のとおりです。

    // Client could not be validated.
    context.Rejected();
    context.SetError("invalid_client", "Client credentials are invalid.");
于 2015-10-30T02:06:59.823 に答える