Blazor: Redirect to Login page when there is no session / JWT token?

前端 未结 4 1045
失恋的感觉
失恋的感觉 2021-01-28 09:14

I am trying to create a new application in Blazor and am working on authentication. I am using a JWT tokens that is stored in Local storage. When the application loads i need to

4条回答
  •  不要未来只要你来
    2021-01-28 09:39

    What I did was to write my own http service to do this.

    It is called Backend and has a property for the token like this:

        public string ApiToken
        {
            get
            {
                if (!string.IsNullOrEmpty(apitoken))
                    return apitoken;
    
                apitoken = Browser.ReadStorage("apitoken");
                return apitoken;
            }
    
            set
            {
                Browser.WriteStorage("apitoken", value);
            }
        }
    

    And then in this class implement all the methods that the http class has, while injecting your token. for instance:

        public async Task GetJsonAsync(string uri)
        {
                this.InProgress = true;
                var result = await http.GetJsonAsync>(uri, this.ApiToken);
                this.InProgress = false;
    
                if (!result.Success)
                {
                    BlazorExtensions.Browser.Alert($"Error: {result.ErrorMessage}");
                    return default(T);
                }
    
                return result.ValueObject;
    
        }
    

    And everywhere use the backend service to do your requests. Also handy for your api url.

    EDIT For the redirection part: For brevity I left out this part, but this is the full method:

        public async Task GetJsonAsync(string uri)
        {
            try
            {
                this.InProgress = true;
                var result = await http.GetJsonAsync>(uri, this.ApiToken);
                this.InProgress = false;
    
                if (!result.Success)
                {
                    BlazorExtensions.Browser.Alert($"Error: {result.ErrorMessage}");
                    return default(T);
                }
    
                return result.ValueObject;
            }
            catch (UnauthorizedAccessException)
            {
                this.InProgress = false;
                uriHelper.NavigateTo("/bzr/Logon");
                return default(T);
            }
            catch (Exception e)
            {
                BlazorExtensions.Browser.Alert($"Fout bij http fetch: {e.Message}");
                this.InProgress = false;
                return default(T);
            }
        }
    

    The uriHelper is simply injected in the constructor:

        public IUriHelper uriHelper { get; private set; }
    
        public Backend(HttpClient httpInstance, IUriHelper uriHelper)
        {
            http = httpInstance;
            this.uriHelper = uriHelper;
    

    Guess that's what you need?

提交回复
热议问题