1

I have an ASP .Net core razor pages application which is configured to use IdentityServer 4 for authentication with windows provider. This razor pages web app is allowed to contact a .Net core Web API ( separate project ) which manage all business logic.

Razor pages contain Javascript that execute AJAX request to this Web API. Currently i'm using razor page controller as proxy so the javascript call the razor page controller which call the Web API. Everything is working fine but I would like to call the Web API directly from the javascript and to secure this part.

Inside of my razor pages web app, I haves access to user claims and can manage authorizations to check if user is allowed to contact Web API for an update for example. How can I secure my Web API and allow direct Javascript call ?

Thank you.

1
  • Welcome to Stack Overflow. I haven't looked at IS4 directy but calling a API controller should be the same as a calling a Razor Page (with changing the path). Are you setting the validation token? Commented Sep 26, 2019 at 14:39

1 Answer 1

0

As you have mentioned in question you are using IdentityServer4 as authorization provider

you can use the following way.

Adding a javascript client

Template for Javascript files oidc-client JavaScript files

Html

 <html> <head>
     <meta charset="utf-8" />
     <title></title> </head> <body>
     <button id="login">Login</button>
     <button id="api">Call API</button>
     <button id="logout">Logout</button>

     <pre id="results"></pre>

     <script src="oidc-client.js"></script>
     <script src="app.js"></script> </body> </html>

JavaScript:

function log() {
    document.getElementById('results').innerText = '';

    Array.prototype.forEach.call(arguments, function (msg) {
        if (msg instanceof Error) {
            msg = "Error: " + msg.message;
        }
        else if (typeof msg !== 'string') {
            msg = JSON.stringify(msg, null, 2);
        }
        document.getElementById('results').innerHTML += msg + '\r\n';
    });
}

use UserManagerClass to connect to IdentityServer4

 var config = {
        authority: "http://localhost:5000",
        client_id: "js",
        redirect_uri: "http://localhost:5003/callback.html",
        response_type: "code",
        scope:"openid profile api1",
        post_logout_redirect_uri : "http://localhost:5003/index.html",
    };
   var mgr = new Oidc.UserManager(config);

At WebApi Part: add a new client for javascript client.

// JavaScript Client
new Client
{
    ClientId = "js",
    ClientName = "JavaScript Client",
    AllowedGrantTypes = GrantTypes.Code,
    RequirePkce = true,
    RequireClientSecret = false,

    RedirectUris =           { "http://localhost:5003/callback.html" },
    PostLogoutRedirectUris = { "http://localhost:5003/index.html" },
    AllowedCorsOrigins =     { "http://localhost:5003" },

    AllowedScopes =
    {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
        "api1"
    }
}

for more reference about how to add new client

Update for: Ajax call to Identity Server and get Token

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:5000/connect/token",
  "method": "POST",
  "headers": {
    "content-type": "application/x-www-form-urlencoded",
    "cache-control": "no-cache",
    "postman-token": "a19f4ba3-b5aa-c61a-8078-c1a6ee39d5df"
  },
  "data": {
    "grant_type": "password",
    "username": "[email protected]",
    "password": "123456",
    "client_id": "client",
    "client_secret": "client123",
    "scope": "scope1"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
Sign up to request clarification or add additional context in comments.

8 Comments

Problem with this approach is the redirection, when user goes to the application there is a razor page that is rendered from the server only if the user is authenticated ( this is the Index.cshtml ). In this page, I have an AJAX call to web api when document is ready and other javascript call depending of users actions. Is there a way to authenticate the user via javascript call without redirection ? I want to stay on main page as it is just a part of it that the javascript is rendering.
Do you mean to say your user is authenticated at index.cshtml? you can take authorization token at javascript and pass it to your Ajax call. no need to redirection
Yes exactly, when the page is rendered it means that the user is authenticated. How can I pass the authorization token from Ajax call?
from a server-side variable, you can take the token to javascript variable var cleintSideTokenVariable= @Html.Raw(tokenvariableServerSide); // declare a javascript variable for reference stackoverflow.com/a/53446977/7262120
Ok, but how do I pass this token to the web API ? In ajax request header ? Can you please me an example ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.