WebApi Owin OAuth(二)access_token过期刷新

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qhgccy/article/details/50997465

产生刷新access_token的凭据refreshl_token主要由AuthenticationTokenProvider产生,在Providers目录新建RefreshOAuthProvider,并重写AuthenticationTokenProvider里的方法:

using System;
using System.Threading.Tasks;
using Microsoft.Owin.Security.Infrastructure;
using System.Security.Cryptography;
using SSXLX.Api.Entity;
using SSXLX.Api.Interface;
using Microsoft.Practices.Unity;

namespace SSXLX.WebApi.Providers
{
    public class RefreshOAuthProvider : AuthenticationTokenProvider
    {
        public override async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var refreshTokenId = Guid.NewGuid().ToString("n");

            var tokenInfo = new RefreshToken()
            {
                Id = GetHash(refreshTokenId),
                UserName = context.Ticket.Identity.Name,
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(20)
            };

            context.Ticket.Properties.IssuedUtc = tokenInfo.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = tokenInfo.ExpiresUtc;
            tokenInfo.ProtectedTicket = context.SerializeTicket();

            var result = await DependencyInjectionConfig.Containter.Resolve<IToken>().SaveRefreshTokenInfo(tokenInfo);
            if (result)
            {
                context.SetToken(refreshTokenId);
            }
        }

        public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            string hashedTokenId = GetHash(context.Token);

            var refreshToken = await DependencyInjectionConfig.Containter.Resolve<IToken>().GetRefreshTokenInfo(hashedTokenId);

            if (refreshToken != null)
            {
                context.DeserializeTicket(refreshToken.ProtectedTicket);
                await DependencyInjectionConfig.Containter.Resolve<IToken>().RemoveRefreshTokenInfo(hashedTokenId);
            }
        }

        public string GetHash(string input)
        {
            HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();
            byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(input);
            byte[] byteHash = hashAlgorithm.ComputeHash(byteValue);

            return Convert.ToBase64String(byteHash);
        }
    }
}

登陆时同时返回refresh_token的值,请求刷新时重新生成access_token,这里的refresh_token持久化是通过Redis来做的。

CreateAsync里保存refresh_token的信息await DependencyInjectionConfig.Containter.Resolve<IToken>().SaveRefreshTokenInfo(tokenInfo);

ReceiveAsync验证Redis里的refresh_token信息,并移除原来的refresh_token持久化的值,使其只能使用一次。

通过接口刷新access_token:

1、登陆获取access_token


结果:

{"access_token":"icS3zXQl18wRSDIjnrV7ooFeq9O5JVo1d-w9ASxg1skAUlSawB1wddrGN1qO9dArsOda-Kyn4yOViSKok_qcWjTl6xdwaWJcGxRqk7smDFetDbtRSGfXjJ4OD92P3o9Ez07FjyUSa4QILptKr7hwCXY-Dn8ktf_IEgsoHFFmVxTnS81DXxIl_u0_UUapKn64w7WiD4taoDHgNCqLSlyOpAIAdFs1wmsYD5GSVrvMQ3C1RsnSU-yInnBPKNkov2nqCtN6pfRCk_je7hg7EP8RpA","token_type":"bearer","expires_in":1199,"refresh_token":"0de71a2f56cf40a889b39e67b307d863","UserName":"aaa","UserID":"6d609e9e42a34bfc88bedbaaec9675d1",".issued":"Mon, 28 Mar 2016 06:29:18 GMT",".expires":"Mon, 28 Mar 2016 06:49:18 GMT"}

2、根据refresh_token刷新access_token:


结果:

{"access_token":"tTNAA44kUH0ENlE2xDG-FA_bDd-WSmjC1IQ-KMaC5QchZIWnoYE7HL27fC5DZZLSEltVoTF4rWt9gIA4uGGJzSVtNHKufg1zNi2wPWVLdrxY0DVa7LcORoeyjdR7SvYS0NwQKxO2I5kCLdpTFmVHiAD-951yIiyJ8H-0uUGrpW40pmxSaMisDcZZs2dwaaVMGi7d1bkVJEOQG49D6GUwpM_-SOtvaC1Y1RAOJSN7Chg-40IcKTxcRX0en01ex29WVltkwB2KApjauyywGrBpWYWERFw3s7s9G5tulWC88E4","token_type":"bearer","expires_in":1199,"refresh_token":"7bab9ce2977a44878a6a166e83c25e0b","UserName":"aaa","UserID":"6d609e9e42a34bfc88bedbaaec9675d1",".issued":"Mon, 28 Mar 2016 06:34:29 GMT",".expires":"Mon, 28 Mar 2016 06:54:29 GMT"}

登陆获取access_token和刷新access_token是同一个接口地址,只是请求的参数不同:

1、登陆:登陆名、密码、grant_type(固定值“password”)

2、刷新:refresh_token(登陆返回的refresh_token)、grant_type(固定值“refresh_token”)


展开阅读全文

新浪 oauth access_token获取问题

12-15

/// rn /// 请求ACCESS的Token rn /// rn /// 获得授权临时Token的时候获得的参数 rn /// 获得授权临时Token的时候获得的验证代码 rn /// 获得授权临时Token的时候获得的密钥 rn /// 返回ACCess Token rn public string GetAccessToken(string oauth_token, string oauth_verifier, string oauth_token_secret)rn rn string thisquestadd = "http://api.t.sina.com.cn/oauth/access_token";rn string myrandomnum = oauthnonce(); //随机数 rn string unixtime = GenerateTimeStamp();//时间戳 rn string token_parameter = "oauth_consumer_key=" + sinaid + "&oauth_nonce=" + myrandomnum + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp =" + unixtime + "&oauth_token=" + oauth_token + "&oauth_verifier=" + oauth_verifier + "&oauth_version=1.0";rn string code_token_parameter = "POST&" + Uri.EscapeDataString(thisquestadd) + "&" + Uri.EscapeDataString(token_parameter);rn string miyuetemp = sinakey + "&" + oauth_token_secret;rn string signvl = ToBase64hmac(code_token_parameter, miyuetemp);rn string token_newparameter = "oauth_consumer_key=" + sinaid + "&oauth_nonce=" + myrandomnum + "&oauth_signature_method=HMAC-SHA1&oauth_token=" + oauth_token + "&oauth_timestamp =" + unixtime + "&oauth_verifier=" + oauth_verifier;rn string QQreturnstr = RequestUrl(thisquestadd, token_parameter + "&oauth_signature=" + Uri.EscapeDataString(signvl));rn return QQreturnstr;rn rnrnrn都一天多了,我这样获取始终得到的结果是 远程服务器返回错误: (401) 未经授权。rnrequest token的两个参数都获取到了,用那两个参数+一堆别的参数来获取access_token。但是就是获取不到rn还有一个问题,每次我刷新页面的时候,算出来的 signvl都会改变,参数都是死的,这个怎么会变?我不太懂... 论坛

没有更多推荐了,返回首页