Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

c# - DataProtectorTokenProvider ValidateAsync Always False

I'm trying to generate and validate a token with DataProtectorTokenProvider<TUser> I generate the code using GenerateAsync method in POST Action and then use ValidateAsync to validate it in another action PUT

public class VerifyPhoneNumberController : ControllerBase
{
    ...
    private readonly DataProtectorTokenProvider<ApplicationUser> _dataProtectorTokenProvider;
    private readonly UserManager<ApplicationUser> _userManager;
    ...
    
    public VerifyPhoneNumberController(DataProtectorTokenProvider<ApplicationUser> dataProtectorTokenProvider, 
        UserManager<ApplicationUser> userManager)
    {
        ...
        _dataProtectorTokenProvider = dataProtectorTokenProvider  ?? throw new ArgumentNullException(nameof(dataProtectorTokenProvider));
        _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
        ...
    }

    public async Task<IActionResult> Post([FromBody] PhoneLoginRequest request)
    {
        ...
        var resendToken = await _dataProtectorTokenProvider.GenerateAsync("resend_token", _userManager, user);
        // here token is valid
        var isTokenValid = await _dataProtectorTokenProvider.ValidateAsync("resend_token", resendToken, _userManager, user);
        ...
    }


    public async Task<IActionResult> Put([FromBody] ResendOtpCodeRequest request)
    {
        ...
        // same token here is invalid
        if (!await _dataProtectorTokenProvider.ValidateAsync("resend_token", request.ResendToken, _userManager, user))
        {
            return BadRequest("Invalid resend token");
        }
        ...
    }
}

However, the response from the ValidateAsync method is always false.

When I generate the code and validate within the same action(POST), it return true.

Why I can't call method ValidateAsync in a separate request ?

I debug ValidateAsync method and for somehow it returning false when it tries to compare the userId and actualUserdId

var userId = reader.ReadString();
var actualUserId = await manager.GetUserIdAsync(user);
if (userId != actualUserId)
{
    Logger.UserIdsNotEquals();
    return false;
}

[Source:]https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Core/src/DataProtectorTokenProvider.cs

Am I missing something obvious ? It is like the DataProtectorTokenProvider injected in my controller is not keeping data in memory.

Am I getting new instance of DataProtectorTokenProvider per request ?

question from:https://stackoverflow.com/questions/65648448/dataprotectortokenprovider-validateasync-always-false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I debug ValidateAsync method and for somehow it returning false when it tries to compare the userId and actualUserdId

Here is the reason why you always get false when excute if (userId != actualUserId).

You should use userId .Equals(actualUserId) instead of ==.

When comparing an object reference to a string (even if the object reference refers to a string), the special behavior of the == operator specific to the string class is ignored. If two objects you are comparing are referring to the same exact instance of an object, then both will return true, but if one has the same content and came from a different source (is a separate instance with the same data), only Equals will return true.

Test Codes

        string s1 = "test";
        string s2 = "test1".Substring(0, 4);
        object s3 = s2;

        Console.WriteLine("s1  ReferenceEquals s3:     "+ $"{object.ReferenceEquals(s1, s3)}");
        Console.WriteLine("s1  ==              s3:     " + $"{s1 == s3}");
        Console.WriteLine("s1  Equals          s3:     " + $"{s1.Equals(s3)}");

Test Result

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...