Giter Site home page Giter Site logo

blazor-server-aad-sample's Introduction

Passing tokens to a server-side Blazor application

  • Authenticate your application as you would do with a regular mvc/razor pages application.
  • Provision and save the tokens to the authentication cookie
  • Define a class to pass in the initial settings for the application:
namespace BlazorServerAuthWithAzureActiveDirectory.Data
{
    public class InitialApplicationState
    {
        public string AccessToken { get; set; }

        public string RefreshToken { get; set; }
    }
}

Define a scoped service that can be used within the Blazor application to resolve the settings from DI

using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace BlazorServerAuthWithAzureActiveDirectory
{
    public class TokenProvider
    {
        public string AccessToken { get; set; }
        public string RefreshToken { get; set; }
    }
}

On startup

services.AddScoped<TokenProvider>();

On the _Host cshtml, create and instance of InitialApplicationState and pass that as a parameter to the app:

    @{
        var tokens = new InitialApplicationState
        {
            AccessToken = await HttpContext.GetTokenAsync("access_token"),
            RefreshToken = await HttpContext.GetTokenAsync("refresh_token")
        };
    }


    <app>
        <component type="typeof(App)" param-InitialState="tokens" render-mode="ServerPrerendered" />
    </app>

On the app component resolve the service and initialize it with the data from the parameter

@using BlazorServerAuthWithAzureActiveDirectory.Data
@inject TokenProvider TokensProvider
...
@code{
    [Parameter] public InitialApplicationState InitialState { get; set; }


    protected override Task OnInitializedAsync()
    {
        TokensProvider.AccessToken = InitialState.AccessToken;
        TokensProvider.RefreshToken = InitialState.RefreshToken;


        return base.OnInitializedAsync();
    }
}

On your service, inject the token provider and retrieve the token to call the API:

public class WeatherForecastService
{
    private readonly TokenProvider _store;


    public WeatherForecastService(IHttpClientFactory clientFactory, TokenProvider tokenProvider)
    {
        Client = clientFactory.CreateClient();
        _store = tokenProvider;
    }


    public HttpClient Client { get; }


    public async Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
    {
        var token = _store.AccessToken;
        var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:5003/WeatherForecast");
        request.Headers.Add("Authorization", $"Bearer {token}");
        var response = await Client.SendAsync(request);
        response.EnsureSuccessStatusCode();


        return await response.Content.ReadAsAsync<WeatherForecast[]>();
    }
}

blazor-server-aad-sample's People

Contributors

javiercn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

blazor-server-aad-sample's Issues

Use with OnBehalfOfProvider

HttpContext.GetTokenAnsync("access_token") does not return a valid JWT token (as it does for "refresh_token" and "id_token"). So, how can it be used in a Microsoft Graph call using the OnBehalfOfProvider, like the code below?

var users = await GraphServiceClient.Users.Request.Filter("[some filter]").WithUserAssertion(new UserAssertion(accessToken)).GetAsync()

Note: UserAssertion(id_token) works.

Obsolete AzureAd References

Hi

I have successfully implemented the sample code on a local project and am able to retrieve the bearer token via the WeatherForecast service class.

The references to AzureAd authentication schemes in startup.cs are flagged as obsolete by Visual Studio. I have attempted to update these references by searching for and applying code changes. Any changes from using AzureAd to OpenId or similar results in the token being returned as null,

What changes do I need to make to fix the obsolete warnings and keep this functionality working?

The attached screenshot shows the lines VS has flagged

Thanks

Mark

BlazorServerTokensObsolete

What is resource meant to be set to?

In this demo what is the resource (in the settings, scope, resource) to be set to?

Would that be the https://.onmicrosoft.com/{guid}? (API App registration in Azure)?

Would this example also work for AzureB2C?

Handling expiration and refresh

Can this example be expanded to include recommended logic for using the refresh token upon access token expiration? Because a Blazor server http request is long-lived, expired tokens is likely to be a constant problem.

Initialize TokenProvider in _Host.cshtml?

Why can we not just inject and initialize the TokenProvider in _Host.cshtml directly?
What is the reason for doing all the extra work with the InitialApplicationState class?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.