AngularJs ASP.NET WebApi Authentication with Thinktecture

cdiazal picture cdiazal · Jun 6, 2014 · Viewed 7.9k times · Source

I´m trying to make an AngularJs web that sends login and password to an ASP.NET WebApi backend and login this user with Thinktecture.

I have Thinktecture working fine with other project, ASP.NET MVC, using WS-Federation. Now I´m trying to do something similar but changing some components and I can´t make it work.

How can I send from ASP.NET WebApi the userName and password to Thinktecture and get it validated?

using System.Collections.Generic;
using System.IdentityModel.Services;
using System.Web.Http;
using WebApi_AngularJs.Model;

namespace WebApi_AngularJs.Controllers
{
    public class AuthorizationController : ApiController
    {    
        // POST: api/Authorization
        public LoginResponse Post([FromBody]Login data)
        {
            //HOW TO SEND data.user and data.password to ThinkTecture and get
            //response if user valid or not??
            var response = new LoginResponse { access_token = "token", data = "data"};
            return response;
        }   

    }
}

Thank you!

Answer

Mohammad Sepahvand picture Mohammad Sepahvand · Jun 8, 2014

There are a few things you need to do. Create an OAuth client that will make token requests, and use that to get access tokens from identity server allowing you to access your web api endpoints. To do this your OAuth client needs to have implicit flow enabled. You then make a login request to Identity server, typically through a pop up window to allow your OAuth client to log in. You need to pass in your OAuth client details in the query string of the login request to Idsrv, an OAuth client config would be what you defined in your Idsrv admin panel for the OAuth client, you would parameterize that and append it to the oauth2/authorzie url:

getIdpOauthEndpointUrl: function () {
                return "https://192.168.1.9/issue/oauth2/authorize";
},
getOAuthConfig: function () {
                return {
                    client_id: "Your Oauth CLient ID that you specifie din Identity Server",
                    scope: "The scope of your RP",
                    response_type: "token",
                    redirect_uri: "https://..YourAngularAppUrl/AuthCallback.html"
                };
}

You then open the login window:

var url = authService.getIdpOauthEndpointUrl() + "?" + $.param(authService.getOAuthConfig());
                    window.open(url, "Login", "height=500,width=350");

In your OAuth client inIdsrv you need to specify a redirect URL, in our case:

https://YourAngularAppUrl/AuthCallback.html

that is what you pass in to the the login request to identity server along with you OAuth client details. The AuthCallback.html page does nothing but extract the access token returned by idsrv to that page in a query string, and passes that into your angular app, how you do that is up to you, but that access token needs to be put into your $http headers.

The access token can be extracted in your AuthCallback.html page like this:

<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="/Scripts/jquery.ba-bbq.min.js"></script>

<script type="text/javascript">
    var params = $.deparam.fragment(location.hash.substring(1));

    window.opener.oAuthCallback(params);
    window.close();
</script>

the OAuthCallback function is defined in my shell page, my index.html and is responsible for passing the token it's given into my angular app and putting it into the $http headers.

function oAuthCallback(OAUTHTOKEN) {
  angular.element(window.document).scope().setHttpAuthHeaderAndAuthenticate(OAUTHTOKEN);
}

The setHttpAuthHeaderAndAuthenticate() function is defined on my $rootScope, and it puts the token into the $http authorizaiton headers:

$http.defaults.headers.common.Authorization = 'Bearer ' + OAUTHTOKEN["access_token"];

Have a look at this post by Christian Weyer It does exactly what we're doing, but it's a knockout/web-api app, same concept still.

The next step is to tell your web api to accept the the access token from idsrv, this is simple;

public static void Configure(HttpConfiguration config)
        {
            var authConfig = new AuthenticationConfiguration();

            authConfig.AddJsonWebToken(
    YourIdsrvSiteId, YourRpsScope/Relam,YourRpsSymmetricSigningKey
);

            config.MessageHandlers.Add(new AuthenticationHandler(authNConfig));
        }

You could also define a ClaimsAuthenticationManager and a ClaimsAuthorizationManager here to allow you to transform claims and Grant/Deny acces sto the web api resources. Again this is all covered in Christian Weyer's post. Hope this helps.