简体   繁体   中英

Accessing RouteData in Blazor Client Side AuthorizationHandler

I am currently learning about Blazor Client Side (WebAssembly) and while looking at Authorization I was trying to validate that a user has access to a path in the URI.

Given a URI like http://localhost:1234/ {route}/resource

On a page I can map route to a property but how can I get access to this value within an AuthorizationHandler to validate that the JWT has a claim with this value?

I have tried to inject RouteData and I have tried to access the HttpContext via IHttpContextAccessor but that is null.

This is the class I am trying to get working

public class RouteDataAccessor : IRouteDataAccessor
{
    private readonly RouteData _routeData;
    public RouteDataAccessor(IHttpContextAccessor httpContextAccessor)
    {
        httpContextAccessor.NullCheck(nameof(httpContextAccessor));
        httpContextAccessor.HttpContext.NullCheck(nameof(httpContextAccessor.HttpContext));

        _routeData = httpContextAccessor.HttpContext.GetRouteData();
    }

    public bool TryGetData(string key, out string value)
    {
        value = null;
        if (_routeData == null || !_routeData.Values.TryGetValue(key, out value))
        {
            return false;
        }

        return true;
    }
}

First off, you can't use HttpContext in WebAssembly Blazor app or Server Blazor app. The following link to my answer will teach you how
pass a value to your AuthorizationHandler. Additionally it illustrate the use of the AuthorizeView component to secure your content, and allow access to authorized users only.

Then see this answer to get some idea how you can save your Jwt token on the local storage, how to retrieve it, and how to use it to perform HTTP calls.

Note: What is missing here a way to extract a claim from your Jwt token and pass it to your AuthorizationHandler. This merits a new question...

You also need to implement the StateAuthenticationProvider which may be combined with the Jwt token mechanism which is shown in my answer ( I call it TokenProvider)

From what you describe in your question I get the impression that every thing is new to you, so I'd suggest you start here...

hope this helps...

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