Token based authentication for both Web App and Web API using Azure AD B2C

萝らか妹 提交于 2019-12-06 08:15:12

Our ASP.NET OpenID Connect middleware which supports AAD B2C is built to rely on cookie authentication from a browser. It doesn't accept tokens in a header or anything like that for securing web pages. So I'd say if you want to serve HTML from your web app in the classic way, you need to use cookies to authenticate requests to the web app.

You can definitely get & store tokens within the browser and use those to access your web API, even if you use cookies to authenticate to the web app. There's two patterns I'd recommend:

  • Perform the initial login using the OpenID Connect Middleware, initiating the flow from the server side as described in the samples. Once the flow completes, the middleware will validate the resulting id_token and drop cookies in the browser for future requests. You can instruct the middleware to save the id_token for later use by using the line of code written here. You can then somehow pass that id_token down to your browser, cache it, and use it to make requests to the API.
  • The other pattern is the inverse. Start by initiating the login from javascript, using the single page app pattern from the B2C documentation. Cache the resulting id_tokens in the browser, and use them to make API calls. But when the login completes, you can send a request to your web app with the id_token in the body, triggering the OpenID Connect middleware to process the request and issue a session cookie. If you want to know the format of that request, I'd recommend inspecting a regular server side OpenID Connect flow.

Found the answer to my own question and adding here for the future reference.

After a successful validation, id_token can be accessed by invoking the SecurityTokenValidated notification. Code sample is below.

private Task OnSecurityTokenValidated(
       SecurityTokenValidatedNotification<OpenIdConnectMessage,
                       OpenIdConnectAuthenticationOptions> arg)
{
    //Id Token can be retrieved as below.
    //**************************************
    var token = arg.ProtocolMessage.IdToken;

    return Task.FromResult(0);
}

However, saving this directly into a browser cookie may not be secure.

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