Re-use already authenticated mvc client in javascript

你。 提交于 2019-12-23 04:50:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!