Authentication via IdentityServer3 in angular2 and access to webapi from asp.net mvc4

477 Views Asked by At

I try to setup all this frameworks (from title) together. So far I setup IdentitySever3 and managed to get login screen on login button in my angular 2 app.

After successful login I receive token from authentication server and now I want to ask for some data from ASP.Net WebApi (.Net 4.6.2).

And there I have a problem. How I should configure this server app, that it be able to understand data from sent token from angular app. Most of tutorials describes .Net core. Any one can show me some example, or say what I missing.

1

There are 1 best solutions below

0
On

You are asking a very general question, however maybe the following pointers will help:

Have a look at the https://github.com/IdentityServer/IdentityServer3.Samples You should write normal .Net WebApi and you need basiclly two changes: 1. Implement "Startup" class on the server like one of the examples (https://github.com/IdentityServer/IdentityServer3.Samples/blob/master/source/WebHost%20(Windows%20Auth)/WebHost/Startup.cs). 2. Add [Authentication] attribute added on each controller/web method that you want.

And on the angular app (the examples are from angular1, but should be clear), you'll need to send the token int the Authorization header on each request:

This code you put after the module declaration

.config(($httpProvider: ng.IHttpProvider) => {
        $httpProvider.interceptors.push("authInterceptorService");
    })

and you make the function

export function authInterceptorService($q, $rootScope, $location) {
    return {
        request,
        responseError
    };

    function request(config) {
        config.headers = config.headers || {};

        if (!_.startsWith(config.url, **URLtoYourApi**)) {
            return config;
        }
        config.headers.authorization = "Bearer " + **access token**;
        return config;
    }

    function responseError(rejection) {
        if (rejection.status === 401) {
            // do some rejection logic
            $location.path("/");
        }
        return $q.reject(rejection);
    }
}

In this way on each request you'll send the token => access token (which can be store in in local storage). Obviously the markers ..... means you need to replace with something :)