Search code examples
c#.netasp.net-mvcasp.net-mvc-4stormpath

How to handle Stormpath ID Site JWT response


I'm trying to create an ASP.NET application with Stormpath ID Site authorization. I create request and response action and successfully got the account.

But what next? How to tell the application that the user is authenticated?

public async Task<RedirectResult> Callback(string jwtResponse)
{
    var client = Request.GetStormpathClient();
    var app = await client.GetApplicationAsync(appUrl);
    var requestDescriptor = HttpRequests.NewRequestDescriptor()
    .WithMethod("GET")
    .WithUri("http://localhost:50084/Auth/Callback?jwtResponse=" + jwtResponse)
    .Build();
    var idSiteListener = app.NewIdSiteAsyncCallbackHandler(requestDescriptor);
    var accountResult = await idSiteListener.GetAccountResultAsync();
    var account = accountResult.GetAccountAsync().Result; //Account
    //What I must do here to tell application that user is authenticated
    return Redirect("/");
}

Solution

  • Instead of getting the account from the ID Site response, you could exchange the JWT for a Stormpath access token:

    public async Task<RedirectResult> Callback(string jwtResponse)
    {
        var client = Request.GetStormpathClient();
        var app = await client.GetApplicationAsync(appUrl);
    
        var exchangeRequest = new StormpathTokenGrantRequest
        {
            Token = jwtResponse
        });
    
        var grantResponse = await application.ExecuteOauthRequestAsync(exchangeRequest);
    
        // Return grantResponse.AccessTokenString in a secure HTTPOnly cookie, or as a JSON response
    }
    

    If you use the Stormpath ASP.NET plugin, you can enable ID Site and this will be handled for you automatically.

    Disclaimer: I'm the package author.