OWIN Security - How to Implement OAuth2 Refresh Tokens

前端 未结 4 1716
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 09:24

I am using the Web Api 2 template that comes with Visual Studio 2013 has some OWIN middleware to do User Authentication and the likes of.

In the OAuthAuthoriza

4条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 10:22

    Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:

    private string ComputeHash(Guid input)
    {
        byte[] source = input.ToByteArray();
    
        var encoder = new SHA256Managed();
        byte[] encoded = encoder.ComputeHash(source);
    
        return Convert.ToBase64String(encoded);
    }
    

    In CreateAsync:

    var guid = Guid.NewGuid();
    ...
    _refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
    context.SetToken(guid.ToString());
    

    ReceiveAsync:

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        Guid token;
    
        if (Guid.TryParse(context.Token, out token))
        {
            AuthenticationTicket ticket;
    
            if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
            {
                context.SetTicket(ticket);
            }
        }
    }
    

提交回复
热议问题