Validate an Access Token at the Resource Server and Respond Accordingly

341 views Asked by At

We've already asked and received a answer about how to do Resource Owner Password Credential flow. Configure the authorization server endpoint We're able to receive an access token from the Identity Server and to store it in the Relying Party's data store.

What we need now is to learn how to validate the access token at the Resource Server.

In the Startup of our Resource Server, we currently have this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication();
}

public void Configure(IApplicationBuilder app)
{
    // Add a new middleware validating access tokens issued by the server.
    app.UseOAuthBearerAuthentication(options =>
    {
        options.AutomaticAuthentication = true;
        options.Audience = "http://localhost:50000/";
        options.Authority = "http://localhost:50000/";
    });

    app.Run(async (context) =>
    {
        // this runs on each request not just per application startup
        await context.Response.WriteAsync(DateTime.Now.ToString() + 
            " Hello Resource Owner Password Flow...");
    });
}

What do we need to add within, say, a Controller/Action in the Resource Server, to check whether access token validation succeeded? E.g. in psuedo-code:

public string MyAction()
{
    if(AccessTokenIsValid())
    {
        return "one thing.";
    } 
    else
    {
        return "another.";
    }
}
1

There are 1 answers

9
Kévin Chalet On BEST ANSWER

It should be super easy:

public string MyAction()
{
    if (User.Identity.IsAuthenticated)
    {
        return "one thing.";
    } 
    else
    {
        return "another.";
    }
}

You could also use the new approach ASP.NET 5 favors, which is basically the same snippet iterating over the different identities of the ClaimsPrincipal to determine if there's an authenticated one.

public string MyAction()
{
    if (User.Identities.Any(identity => identity.IsAuthenticated))
    {
        return "one thing.";
    } 
    else
    {
        return "another.";
    }
}