To me best approach to answer this is to go back to definition of Authorization Code flow.Authorization code grant is a redirection-based flow used to obtain both access tokens and refresh tokens, the client initiates the flow by directing the resource owner's.
And pkce is just is an extension to the Authorization Code flow to prevent certain attacks.
Then the answer is no, we can not use Authorization Code flow with PKCE to secure a public API without user login.
There is some other ways to secure public APIs or at least make it less/harder accessible. CORS is an option, read more here, as its out of context for this question I wouldn't go further.
For scenario with login, Authorization code flow is supported on IdentityServer4. here is what we need to do to implement it:
- On
IdentityServer add the configuration entry for js client like:
new Client
{
ClientId = "jsclient",
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 = {"openid", "profile", "offline_access", "api1", "api2" },
}
- On SPA app use oidc-client library, and also add the OIDC config to be like
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);
Find full sample code here. I strongly suggest to read the quickstart doc to get a better understanding of implementation details.