Identity Server by leastprivilege在Azure上无法正常运行

时间:2017-04-06 08:35:41

标签: oauth-2.0 azure-web-sites identityserver3 least-privilege

我正在尝试实现遵循OAUTH2 / OIDC协议的架构。为了做到这一点,我为客户端提供了STS(Identity Server v3 by leastprivilege),ASP.NET WebApi和ASP.NET MVC应用程序。我的目标是在Azure上托管STS和REST服务,以便不同的客户端可以将它们用作公共服务。到现在为止还挺好。在我决定添加一个使用其中一个重定向流程的新客户端 - 授权代码流之前,一切似乎都顺利完美地运行。我想利用它提供的刷新令牌选项。我想向该客户提供短期访问令牌(10分钟),并让他使用刷新令牌以获取新令牌。这就是代码中的所有内容:

STS:

new Client 
{
    ClientId = "tripgalleryauthcode",
    ClientName = "Trip Gallery (Authorization Code)",
    Flow = Flows.AuthorizationCode, 
    AllowAccessToAllScopes = true,
    RequireConsent = false,

    RedirectUris = new List<string>
    {
        Tripgallery.Constants.TripgalleryMvcAuthCodePostLogoutCallback
    },           

    ClientSecrets = new List<Secret>()
    {
        new Secret(Tripgallery.Constants.TripgalleryClientSecret.Sha256())
    },

    // refresh token options
    AccessTokenType = AccessTokenType.Jwt,
    AccessTokenLifetime = 600,
    RefreshTokenUsage = TokenUsage.OneTimeOnly, // Every time generates new refresh token. Not only access token.
    RefreshTokenExpiration = TokenExpiration.Sliding,
    SlidingRefreshTokenLifetime = 1296000,

    PostLogoutRedirectUris = new List<string>()
    {
        Tripgallery.Constants.TripgalleryPostLogoutCallback
    }
}

Mvc应用程序(客户端):

private ObjectCache _cache;
private readonly string tokensCacheKey = "Tokens";

public HomeController()
{
    _cache = MemoryCache.Default;
}

// GET: Home
public ActionResult Index()
{
    var authorizeRequest = new AuthorizeRequest(Constants.BoongalooSTSAuthorizationEndpoint);

    var state = HttpContext.Request.Url.OriginalString;

    var url = authorizeRequest.CreateAuthorizeUrl(
    "tripgalleryauthcode",
    "code",
    "openid profile address tripgallerymanagement offline_access",
    Constants.TripgalleryMvcAuthCodePostLogoutCallback,
    state);

    HttpContext.Response.Redirect(url);
    return null;
}

public async Task<ActionResult> StsCallBackForAuthCodeClient()
{
    var authCode = Request.QueryString["code"];

    var client = new TokenClient(
    Constants.TripgallerySTSTokenEndpoint,
    "tripgalleryauthcode",
    Constants.TripgalleryClientSecret
    );

    var tokenResponse = await client.RequestAuthorizationCodeAsync(
    authCode,
    Constants.TripgalleryMvcAuthCodePostLogoutCallback
    );

    this._cache[this.tokensCacheKey] = new TokenModel()
    {
        AccessToken = tokenResponse.AccessToken,
        IdToken = tokenResponse.IdentityToken,
        RefreshToken = tokenResponse.RefreshToken,
        AccessTokenExpiresAt = DateTime.Parse(DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToString(CultureInfo.InvariantCulture))
    };

    return View();
}

public ActionResult StartCallingWebApi()
{
    var timer = new Timer(async (e) =>
    {
        var cachedStuff = this._cache.Get(this.tokensCacheKey) as TokenModel;
        await ExecuteWebApiCall(cachedStuff);
    }, null, 0, Convert.ToInt32(TimeSpan.FromMinutes(20).TotalMilliseconds));

    return null;
}

private async Task ExecuteWebApiCall(TokenModel cachedStuff)
{
    // Ensure that access token expires in more than one minute
    if (cachedStuff != null && cachedStuff.AccessTokenExpiresAt > DateTime.Now.AddMinutes(1))
    {
        await MakeValidApiCall(cachedStuff);
    }
    else
    {
        // Use the refresh token to get a new access token, id token and refresh token
        var client = new TokenClient(
            Constants.TripgallerySTSTokenEndpoint,
            "tripgalleryauthcode",
            Constants.TripgalleryClientSecret
        );

        if (cachedStuff != null)
        {
            var newTokens = await client.RequestRefreshTokenAsync(cachedStuff.RefreshToken);

            var value = new TokenModel()
            {
                AccessToken = newTokens.AccessToken,
                IdToken = newTokens.IdentityToken,
                RefreshToken = newTokens.RefreshToken,
                AccessTokenExpiresAt =
                    DateTime.Parse(
                        DateTime.Now.AddSeconds(newTokens.ExpiresIn).ToString(CultureInfo.InvariantCulture))
            };

            this._cache.Set(this.tokensCacheKey, (object)value, new CacheItemPolicy());

            await MakeValidApiCall(value);
        }
    }
}

问题是,如果我在Azure上托管STS,出于某种原因,如果我决定在访问令牌过期后20分钟或更长时间内使用刷新令牌,则会出现错误。无论我刷新令牌的生命周期是15天。

enter image description here

这是STS生成的日志:

w3wp.exe Warning: 0 : 2017-04-06 12:01:21.456 +00:00 [Warning] AuthorizationCodeStore not configured - falling back to InMemory
w3wp.exe Warning: 0 : 2017-04-06 12:01:21.512 +00:00 [Warning] TokenHandleStore not configured - falling back to InMemory
w3wp.exe Warning: 0 : 2017-04-06 12:01:21.512 +00:00 [Warning] ConsentStore not configured - falling back to InMemory
w3wp.exe Warning: 0 : 2017-04-06 12:01:21.512 +00:00 [Warning] RefreshTokenStore not configured - falling back to InMemory
w3wp.exe Information: 0 : 2017-04-06 12:01:22.371 +00:00 [Information] Start token request
w3wp.exe Information: 0 : 2017-04-06 12:01:22.418 +00:00 [Information] Client secret id found: "tripgalleryauthcode"
w3wp.exe Information: 0 : 2017-04-06 12:01:22.418 +00:00 [Information] Client validation success
w3wp.exe Information: 0 : 2017-04-06 12:01:22.418 +00:00 [Information] Start token request validation
w3wp.exe Information: 0 : 2017-04-06 12:01:22.433 +00:00 [Information] Start validation of refresh token request
w3wp.exe Warning: 0 : 2017-04-06 12:01:22.574 +00:00 [Warning] "Refresh token is invalid"
 "{
  \"ClientId\": \"tripgalleryauthcode\",
  \"ClientName\": \"Trip Gallery (Authorization Code)\",
  \"GrantType\": \"refresh_token\",
  \"RefreshToken\": \"140cfb19405a6a4cbace29646751194a\",
  \"Raw\": {
    \"grant_type\": \"refresh_token\",
    \"refresh_token\": \"140cfb19405a6a4cbace29646751194a\"
  }
}"
w3wp.exe Information: 0 : 2017-04-06 12:01:22.590 +00:00 [Information] End token request
w3wp.exe Information: 0 : 2017-04-06 12:01:22.590 +00:00 [Information] Returning error: invalid_grant
w3wp.exe Information: 0 : 2017-04-06 12:01:29.465 +00:00 [Information] Start discovery request
w3wp.exe Information: 0 : 2017-04-06 12:01:29.512 +00:00 [Information] Start key discovery request

在本地计算机上运行的STS的情况与预期的一样。我可以使用刷新令牌获取新令牌。

enter image description here

RESLOVED: 这个问题确实是 Fred Han - MSFT 所指出的。我需要为刷新令牌实现持久存储。实现它真的很容易。我就这样做了:

Identity Server的Startup.cs

var idServerServiceFactory = new IdentityServerServiceFactory()
                                .UseInMemoryClients(Clients.Get())
                                .UseInMemoryScopes(Scopes.Get());

//...

// use custom service for tokens maintainance
var customRefreshTokenStore = new CustomRefreshTokenStore();
idServerServiceFactory.RefreshTokenStore = new Registration<IRefreshTokenStore>(resolver => customRefreshTokenStore);

var options = new IdentityServerOptions
{
    Factory = idServerServiceFactory,

    // .....

}

idsrvApp.UseIdentityServer(options);

CustomRefreshTokenStore.cs

public class CustomRefreshTokenStore : IRefreshTokenStore
{
    public Task StoreAsync(string key, RefreshToken value)
    {
        // code that uses persitant storage mechanism
    }

    public Task<RefreshToken> GetAsync(string key)
    {
        // code that uses persitant storage mechanism
    }

    public Task RemoveAsync(string key)
    {
        // code that uses persitant storage mechanism
    }

    public Task<IEnumerable<ITokenMetadata>> GetAllAsync(string subject)
    {
        // code that uses persitant storage mechanism
    }

    public Task RevokeAsync(string subject, string client)
    {
        // code that uses persitant storage mechanism
    }
}

1 个答案:

答案 0 :(得分:1)

  

w3wp.exe警告:0:20​​17-04-06 12:01:21.456 +00:00 [警告]未配置AuthorizationCodeStore - 回退到InMemory

     

w3wp.exe警告:0:20​​17-04-06 12:01:21.512 +00:00 [警告]未配置TokenHandleStore - 回退到InMemory

     

w3wp.exe警告:0:20​​17-04-06 12:01:21.512 +00:00 [警告]未配置ConsentStore - 退回InMemory

     

w3wp.exe警告:0:20​​17-04-06 12:01:21.512 +00:00 [警告]未配置RefreshTokenStore - 回退到InMemory

您似乎在内存中存储/维护数据,如果您在Azure网站上托管负载均衡器后面的多个实例,则可能会导致问题。您可以尝试将数据存储在其他数据存储中,而不是存储在内存中。

  

_cache = MemoryCache.Default;

此外,您通过Web API应用程序中的内存存储和检索tokensCacheKey,这在Azure多实例Web场环境中无法正常工作。请将数据存储在外部存储中,例如Azure存储,数据库或Redis缓存。