问题
I have an MVC client of .Net core which uses identityserver 4.
Methods which returns view is protected by authorize attribute.
But how to call web API (which is separate project running on different URL) with same authenticated data which MVC client has?
Or will I have to authenticate again using oidc javascript client?
Is there any way I can get bearer token from already authenticated MVC client to authorize my javascript client to access web API?
回答1:
Get your access token in a MVC controller action and pass it to the action's view in ViewBag or anything, or even get it directly in the razor view.
Here is an example: https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Clients/src/MvcHybrid
Pay attention to the Startup class, the HomeController, and this view.
Startup:
services.AddAuthentication(options => {...})
.AddOpenIdConnect("oidc", options => {
...
options.SaveTokens = true;
...
}
Controller/view:
var token = await HttpContext.GetTokenAsync("access_token");
// use token
来源:https://stackoverflow.com/questions/50296791/re-use-already-authenticated-mvc-client-in-javascript