Notify all components that authentication has been changed in Blazor

nAviD

I have a Blazor (version net5.0) component with a lot of html markups and here is some part of it :

<a class="@(IsAuthenticated?"":"hide")" href="#">My link for logged in users</a>

and here is my c# code (MyComponent.Razor):

    [CascadingParameter] private Task<AuthenticationState> authenticationState { get; set; }
    private AuthenticationState auth;
    public bool IsAuthenticated { get; set; }

    protected async override Task OnInitializedAsync()
    {
        auth = await authenticationState;
        var user = auth.User.Identity.IsAuthenticated;
        await base.OnInitializedAsync();
    }

and in my Login component after successful login I call StateHasChanged();

  void Login()
  {
    ...
    StateHasChanged();
  }

But after login no changes to MyComponent will be applied unless I refresh the page so the component rerender itself.

Note: I don't want to use AuthorizeView because as I mentioned there are lots of markups and components in the MyComponent and I don't want to have an AuthorizeView for every style or element that I want to change their behaviors based on user's authentication.

Update: I have the following code in my App.razor component:

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(Layout)" >
            <Authorizing>
                <text> my Custom Authotizing in app.razor ...</text>
            </Authorizing> 
            <NotAuthorized>
                <text> my Custom NOT Authotized in app.razor ...</text>
            </NotAuthorized>
        </AuthorizeRouteView>
    </Found>
    <NotFound>
        <CascadingAuthenticationState>
            <LayoutView Layout="@typeof(Layout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </CascadingAuthenticationState>
    </NotFound>
</Router>
nAviD

Looking at AuthorizedView source code I finally figured out that I should use OnParametersSetAsync and a property :

<a class="@MyClassProp" href="#">My link for logged in users</a>

code:

public string MyClassProp { get; set; } = "hide";
public async Task<string> GetClassAsync()=> (await authenticationState).User.Identity.IsAuthenticated ? "" : "hide";
    
protected async override Task OnParametersSetAsync()
{
    MyClassProp = await GetClassAsync(); // also call GetClass in OnInitializedAsync
    StateHasChanged();
    await base.OnParametersSetAsync();
}

The IsAuthenticated property that I have been created in the question is always equals to its initial state and does not change with AuthenticationState being changed even if I reset its value in OnParametersSetAsync. Calling StateHasChanged() in Login and Logout methods is not necessary. If instead of using MyClassProp property, I call GetClassAsync from the markup, it does not work either.

Warning: The whole approach of hiding an element by setting a css class for unauthorized user have security issues, because the content still can be exposed or modified by user even by just using their browser.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Check if a file has been changed

분류에서Dev

Notify Qt Window when its visibility status has changed

분류에서Dev

eclipse.ini has been changed, but eclipse wont updated in Ubuntu 14.04

분류에서Dev

/var/log/syslog 'systemd[1]: Time has been changed' message every 5 seconds

분류에서Dev

Notify about changed variable in socket thread

분류에서Dev

tomcat has been stopped

분류에서Dev

Blazor Wasm Hosted Prerender with Authentication AuthenticationStateProvider not registered

분류에서Dev

No message serializer has been configured

분류에서Dev

Has my password been compromised?

분류에서Dev

How do i use Blazor components in the code?

분류에서Dev

User_Notify on Phpbb Notifies ALL Members

분류에서Dev

Why has changed both sides of equation in java?

분류에서Dev

What has changed my mouse selection behaviour?

분류에서Dev

Has SQL changed very much from 2011

분류에서Dev

On which disk device Ubuntu has been installed?

분류에서Dev

How to check if ethereum transaction has been mined

분류에서Dev

How to use gzip if it has not been enabled

분류에서Dev

Determining when a socket has been closed on Android

분류에서Dev

Editing CSS of WordPress theme that has been embedded

분류에서Dev

CentOS got hacked in, crontab has been modified

분류에서Dev

Possible to determine if app has been repurchased?

분류에서Dev

Android: Gallery View has been deprecated?

분류에서Dev

How to know what Linklabel has been clicked?

분류에서Dev

Check whether node in tree has been deleted

분류에서Dev

winforms, form has been shown, event handler

분류에서Dev

Remove button after it has been clicked?

분류에서Dev

Trigger an action when an URL has been visited

분류에서Dev

Is there a way to delete something that has been shelved?

분류에서Dev

Testing that 404 page has been rendered

Related 관련 기사

뜨겁다태그

보관