capesean / openiddict-test

Example ASP.NET V5 project that issues & validates JWT tokens
61 stars 16 forks source link

Angular client #1

Closed leak closed 8 years ago

leak commented 8 years ago

In your corresponding article you wrote that you are planning to use your setup with Angular. Do have any recommandations for a client library that handles the oidc stuff (login, logout, refresh token in particular) or are you planning to implement that yourself?

capesean commented 8 years ago

Hi @leak. I've been implementing the client side code myself. No plans to include it but happy to share snippets below.

Login

function login(loginData) {

    var data = "grant_type=password"
        + "&scope=offline_access"
        + "&resource=" + apiUrlRoot
        + "&username=" + loginData.userName
        + "&password=" + loginData.password;

    var deferred = $q.defer();

    $http.post(apiUrlRoot + "connect/token", data, { headers: { "Content-Type": "application/x-www-form-urlencoded" } })
    .success(function (response) {

        // todo: on 500 error, this function is still being called, hence this check
        if (!response.access_token) {
            deferred.reject("Server response did not include a token");
        }
        // you'll have to replace this with your own data storage function...
        storeData(response.access_token, response.refresh_token);
        deferred.resolve(response);

    }).error(function (data) {
        logout();
        deferred.reject(data);
    });

    return deferred.promise;
}

Logout

function logout() {
    // i simply remove the data from localstorage & clear some variables
    store.remove(storageKey);
    $rootScope.identity = null;
    authenticated = false;
}

Refresh Token

function getRefreshTokenPromise() {

    // getRefreshToken retrieves the token that was stored in the login (response.refresh_token)
    var refreshToken = getRefreshToken();
    var deferred = $q.defer();

    $http({
        url: apiUrlRoot + "token",
        data: "grant_type=refresh_token&refresh_token=" + refreshToken,
        skipAuthorization: true,
        method: "POST"
    }).then(
        function (response) {

            if (!response.data.access_token) { deferred.reject(); }
            storeData(response.data.access_token, response.data.refresh_token);
            deferred.resolve(response.data.access_token);

        }, 
        function () {

            logout();
            deferred.reject();

        });

    return deferred.promise;
}