willie willie - 6 months ago 28
Ajax Question

How to use AJAX to get the DB data in ASP.NET WebAPI Server with a Token Key

I've got a serious problems with WebAPI and Token Key in ASP.NET IIS Server, I can acquire data very easy without security issue.

However I cannot obtain anymore from sever when I set up the [Authorize] in the any Controllers , because I didn't put the Authorization messages in the HTTP head, so how to put it in that ???

Answer

There had dealt with my question about how to use Ajax to get a Token key from Asp.net WebAPI. Hopefully this example can help someone who has the same question like me.
The client code will like as following ,it can get Token key from server ,however you have to add the user profile data in DB table first and then using client code to send user/pwd to server ,if user/pwd is correct it will be sent token key back by server

 <script>
 var token;
    $("#getToken1").click(function () {
        var user = {
            grant_type: 'password',
            username: '***@gmail.com',
            password: '!aA1234'
        };
        $.ajax({
            type: 'POST',
            url: 'http://localhost:65370/Token',
            data: user,
            success: function (data) {
                var parsedResponseBody = JSON.parse(JSON.stringify(data));
                token = parsedResponseBody.access_token;
            }
        });
    });
</script>

when you get token key,you will be passing Authorization checking and then you can get data from server site, like as following code

<script>
    $("#read1").click(function () {
        $.support.cors = true;
        $.ajax({
            crossDomain: true,
            url: 'http://localhost:65370/api/travels',
            headers: {
                'Authorization': 'Bearer ' + token
            },
            type: 'GET',
            success: function (data) {
                alert(JSON.stringify(data));
            }
        });
    });
</script>

Reference from https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi