简体   繁体   中英

.Net Core Azure AD single tenant Authentication

I have a .net core blazor server application that I am implementing with Azure AD Authentication. I registered the application and done all the setup on the azure side. Now, I would like to retrieve the name or email of the user and display a welcome,"user" msg upon login. The application successfully authenticates but I am not sure how to retrieve the user's name.

My code: Startup.cs

  services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
.AddOpenIdConnect(options =>
{
    options.Authority = "https://login.microsoftonline.com/;
    options.ClientId = ClientId";
    options.ResponseType = OpenIdConnectResponseType.IdToken;
    options.CallbackPath = "/Myrequest";
    options.SignedOutRedirectUri = "https://fftest.azurewebsites.net/";
    options.TokenValidationParameters.NameClaimType = "name";
})

.AddCookie();

        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        services.AddScoped(sp =>
        {
            var provider = sp.GetService<AuthenticationStateProvider>();
            var state = provider.GetAuthenticationStateAsync().Result;
            return state.User.Identity.IsAuthenticated ?
                state.User : null;
        });

    }

Index.razor:

<h3>Welcome @Name ,</h3>



@code {
    public string Name { get; set; }
    //tring email = .FindFirstValue(ClaimTypes.Email);


    protected override async Task OnInitializedAsync()
    {

        var authstate = await Authentication_.GetAuthenticationStateAsync();
        var user = authstate.User.Identity.Name ;
        if (user != null)
        {
            Name = user.ToString();
        }
        else
        {
            Name = "";
        }

This is my first attempt at doing azure ad authentication, do I need to implement the Graph API? Any answers are greatly appreciated!

If you generate a Blazor server-side project from the template and enable authentication, you can see what I'm about to share in the Shared/LoginDisplay.razor page, but it demonstrates exactly what you're asking.

You'll see that it's going to read out the user identity from the AuthenticationState injected into the AuthorizeView to the page with @contexdt.User.Identity.Name

If you'd like to access the same, you can use the following in any of your pages/components to inject the AuthenticationState and read out the properties.

@page "/"
@inject AuthenticationState AuthState

<h1>Hello @AuthState.User.Identity.Name!</h1>

To answer your last question, there's no need to use the Graph API since the name property is available by default from the claims passed back upon logging in. Were this not the case, you might very well need to request it from the Graph API.

After spending a couple days on this; I've come to find that I did everything correctly in regards to setting up authentication. The cascading authentication state was missing in app.razor file.

  <CascadingAuthenticationState>
            <Router AppAssembly="@typeof(Program).Assembly">
                <Found Context="routeData">
                    <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
                </Found>
                <NotFound>
                    <LayoutView Layout="@typeof(MainLayout)">
                        <p>Sorry, there's nothing at this address.</p>
                    </LayoutView>
                </NotFound>
            </Router>
        </CascadingAuthenticationState>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM