OpenId Connect, best approach for bearer client side token to invoke WebApi after MVC signing?

I hope someone can advise me on this please.

I was following a modified form of this tutorial, Getting Started with thinktecture Identity server , to try to configure a site using OpenId Connect authentication.

I have this setup:

Asp.NET MVC project acting as an identity server

Asp.NET MVC project serving as a secure website

This setting works great. When someone tries to access a controller with the [Authorize] attribute on a secured website, they are redirected to the Identity server for login, and then redirected back to the secured site after successful login.

Now I would like to add a web api to the mix. I created a WebApi project, but unlike the tutorial, which calls it server side using "service account", I would like to call it client side (JQuery) from a secure website with the current user id.

I understand that I need to use a bearer token in the authentication header.

My question is, how do I get the bearer token for the current user on the client side so that I can set the title? (The user is already signed in.)

Many thanks for your help

+3


source to share


2 answers


If you are using .Net Framework 4.5.1 in your Identity Server application, you may already have TokenEndpointPath set as "/ Token". Review the Startup.Auth.cs file in the App_Start folder.

The caller can obtain the bearer token from the endpoint / Token by POSTing the correct username / password to the endpoint. I created some simple code to experiment with my own ASP.NET Web Api 2 project using the new Windows Identity Foundation framework. You may find something useful in it:

http://codepen.io/randomfactor/pen/bNpBoP?editors=101



    # THIS IS CoffeeScript (because we are not barbarians)
    # start by trying to get an access token
    $.ajax {
      type: 'POST'
      url: "#{appUrl}/Token"
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
      data: {
        grant_type: 'password'
        username: $('#login-name').val()
        password: $('#password').val()
      }
    }
    .then (data) ->
      

Run codeHide result


Be warned that by definition, codepen makes a Cross Origin resource request for your Identity Server project. To make this work, you will need to modify your Identity Server project to support CORS, as described in the codepun comments.

If you want to bundle your Identity Server with a secure website and Web Api project in .Net 4.5.1 (highly recommended!), This will simplify some things and you won't need CORS changes.

0


source


I think you can inject them into the DOM in _Layout.cshtml. Better initialize some OidcClient and AJAX before submitting . What do you think @PinpointTownes?



0


source







All Articles