Code Monkey home page Code Monkey logo

blazor.auth0's Introduction

Blazor.Auth0

Blazor Auth0 Library

Blazor.Auth0 Is a library for using the Authorization Code Grant with Proof Key for Code Exchange (PKCE) with Auth0's Universal Login in Blazor SPAs.

The idea behind this is to have an easy way of using Auth0's services with Blazor (especially the client side) without relaying on javascript libraries.

Nuget Nuget Github Actions Codacy Badge GitHub license

About Auth0

Auth0 is a platform that provides authentication and authorization as a service. Giving developers and companies the building blocks they need to secure their applications without having to become security experts.

You can connect any application (written in any language or on any stack) to Auth0 and define the identity providers you want to use (how you want your users to log in).

Learn more at:

JWT Auth for open source projects

Prerequisites

Blazor

You'll want to follow the Getting Started instructions in Blazor website

Auth0

Basic knowledge of Auth0 IDaaS platform is assumed, otherwise, visiting Auth0 docs is highly recommended.

Installation

Install via Nuget.

Server Side

Install-Package Blazor-Auth0-ServerSide -Version 2.0.0-Preview5

Client Side

Install-Package Blazor-Auth0-ClientSide -Version 2.0.0-Preview5

Usage

Note: Following example is for a client-side with require-authenticated-user implementation, for server-side and core-hosted example implementations please refer to the examples

Program.cs

using Blazor.Auth0;

// ...


public static async Task Main(string[] args)
{
	var builder = WebAssemblyHostBuilder.CreateDefault(args);

	builder.Services.AddBlazorAuth0(options =>
	{
		// Required
		options.Domain = "[Auth0_Domain]";

		// Required
		options.ClientId = "[Auth0_Client_Id]";

		//// Required if you want to make use of Auth0's RBAC
		options.Audience = "[Auth0_Audience]";

		//// Uncomment the following line if you don't want your users to be automatically logged-off on token expiration
		// options.SlidingExpiration = true;

		//// Uncomment the following two lines if you want your users to log in via a pop-up window instead of being redirected
		// options.LoginMode = LoginModes.Popup;

		//// Uncomment the following line if you don't want your unauthenticated users to be automatically redirected to Auth0's Universal Login page 
		// options.RequireAuthenticatedUser = false;
	});
	
	builder.Services.AddAuthorizationCore();

	builder.RootComponents.Add<App>("app");

	await builder.Build().RunAsync();
}

Add a reference to Microsoft.AspNetCore.Components.Authorization

_Imports.razor

@using Microsoft.AspNetCore.Components.Authorization
//...

Replace App.razor content with the following code

App.razor

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <Authorizing>
                <p>>Determining session state, please wait...</p>
            </Authorizing>
            <NotAuthorized>
                <h1>Sorry</h1>
                <p>You're not authorized to reach this page. You may need to log in as a different user.</p>
            </NotAuthorized>
        </AuthorizeRouteView>
    </Found>
    <NotFound>        
        <p>Sorry, there's nothing at this address.</p>        
    </NotFound>
</Router>

Support

If you found a bug, have a consultation or a feature request please feel free to open an issue.

When opening issues please take in account to:

  • Avoid duplication: Please search for similar issues before.
  • Be specific: Please don't put several problems/ideas in the same issue.
  • Use short descriptive titles: You'll have the description box to explain yourself.
  • Include images whenever possible: A picture is worth a thousand words.
  • Include reproduction steps for bugs: Will be appreciated

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork it (https://github.com/henalbrod/Blazor.Auth0/fork)
  2. Create your feature branch (git checkout -b feature/fooBar)
  3. Commit your changes (git commit -am 'Add some fooBar')
  4. Push to the branch (git push origin feature/fooBar)
  5. Create a new Pull Request

Authors

Henry Alberto Rodriguez - Initial work - GitHub - Twitter - Linkedin

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

Release History

v2.0.0-Preview5

  • Fixed issue #41
  • Upgraded to .Net Core v3.1.102

v2.0.0-Preview4

  • Upgraded to .Net Core v3.1.0-preview3

v2.0.0-Preview3

  • Upgraded to .Net core 3.1.0-preview2

v2.0.0-Preview2

This relase comes with Client Side changes primarly

  • New LoginMode parameter in ClientOptions

    Redirect = Classic behavior (default) PopUp = Loads Universal Login inside a popup window

    The new PopUp behavior comes in handy to avoid the full client side app reloading

  • New AuthorizePopup method in Blazor.Auth0.Authentication for client side

v2.0.0-Preview1

BREAKING CHANGES:

  • Upgraded to .Net Core 3.1.0-preview1
  • Server side projects upgraded to netcoreapp3.1
  • Auth0 permissions are now accesible as an any other array claim:
policy.RequireClaim("permissions", "permission_name")

v1.0.0-Preview3

  • Overall upgrade to .Net Core 3.0

v1.0.0-Preview2

  • Overall upgrade to .Net Core 3.0 RC1
  • Removed Shell.razor in Example projects
  • Simplified App.razor in Example projects
  • Removed local _imports.razor in Example projects

v0.1.0.0-Preview1

  • Upgraded to .Net Core 3.0.0-preview8
  • Removed AuthComponent
  • New One-Liner instantiation
  • Server Side full rewrite
    • Better server-side Blazor Authentication compatibility/integration
    • Cookie-based session (No more silent login iframe in server-side)
    • Refresh token support (Refreshing and Revoking)
    • Client secret
    • Server-side sliding expiration

blazor.auth0's People

Contributors

davidallyoung avatar henalbrod avatar indcoder avatar jbomhold3 avatar lbalmaceda avatar snowpipe avatar topswagcode avatar

Stargazers

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

Watchers

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

blazor.auth0's Issues

Clientside | Claims based

In the previous version we had permissions appended before the claim. While following Example.Clientside, I have been testing the claims based fetch data. But I cannot see the permissions in the claims of the User Identity and hence the page is displayed the UnAuthorized message..

So while the example has @Attribute [Authorize("read:weather_forecast")] , on the MS doc
@Attribute [Authorize( Policy = "read:weather_forecast")]

This was working for preview 8 codebase
On the Auth0 dashboard , the relevant API had the RBAC enabled and the User has the Permission ["read:weather_forecast] set .

Endpoints

Will do a PR but want to make sure our goals align before.
Endpoints should be gathered from the .well-known/openid-configuration file not hardcoded in. This causes incompatibility with auth servers.

Unnecesary StateHasChanged event fired on silent login

Reportedly, the AuthComponent is firing an unnecessary StateHasChanged event when running a silent login even if the session state hasn't change.

This is causing animated elements re-renders its animations sequences, causing the app to not act naturally.

Code challenge not properly encoded in Auth request

A very minimal client only app authenticating against an Identity Server 4 instance on local host generated this auth request:

https://localhost:44373/connect/authorize?&response_type=code&code_challenge_method=S256code_challenge=fXsiI0JPtBectyE0/rYp6FqujManyFWfwauxq7YljHI=&state=+j3IlMJ2SIVM6z+KZoRZyJiOoErq1yWLOREznqr4ntQ=&nonce=q7TLYSCLQyiAwqXve7VU12XMPKFYESnjZZRCiB+rk8Y=&client_id=debugClientID&scope=openid%20profile%20email&redirect_uri=https://localhost:44391/

Note the missing ampersand between the code_challenge_method and code_challenge parameters.

Less important: the query string has an unnecessary & before the first parameter name.

Going to Weather page when not logging results in delay before redirect to login

Hi. Love the project. I have a problem with CoreHosted Client:
https://github.com/Pegazux/Blazor.Auth0/blob/master/examples/Blazor.Auth0.Examples.CoreHosted.Client/Pages/FetchData.razor
When I browse to this page I get a delay for 30 seconds.
My guess is it is because of " System.Threading.Thread.Sleep(30000); " in:
https://github.com/Pegazux/Blazor.Auth0/blob/master/src/Blazor.Auth0.ServerSide/Components/AuthComponent.razor
Is there a reason for the 30seconds delay? Or just some debug code left behind?

Best regards Joshua Ryder AKA TopSwagCode :)

Feature: Call API

Hi, Im calling an asp.net core webapi with auth0 authentication enabled from my blazor serverside app, in order to make this plugin more useful it would be great if you can enable access to Retrieved Access Token
"To call your API from a SPA, the application must pass the retrieved Access Token as a Bearer token in the Authorization header of your HTTP request."

Compile failing for dotnet core RC 1

Just downloaded the lastest dotnet core release candidate , it errors out with the linker error code
-532462766.

I'm aware that Readme mention that its tested with Preview 8....just wanted to take it for a spin.

Silent Login interval is too short

Reportedly, the Auth0 iframe for running the silent login is injected too often (every 35 to 40 seconds) ignoring the TTL of the JWT.

Type could not be found

HI trying to setup on a Blazor (server side) project, when I replace de Index code with yours as your instructions it marks AuthenticationService, of @Inject AuthenticationService _authService, as:
The type or namespace name 'AuthenticationService' could not be found (are you missing a using directive or an assembly reference?)
Also with SessionState in @if (_authService.SessionState == SessionStates.Active)

I dont know if this is normal, because it compiles but it stays on

Determining session state, please wait...

Authorizing route never gets hit

When a user hits the site, the first thing they see is the unauthorized view, then after a few seconds the authorized content comes into view.

For some reason the Authorizing view/route never gets hit.

Any ideas as to what we can do to fix this?

SignalR HubContext User Is Null

I added a new SignalR hub to my project but the hub context user is coming through as null. Do I need to do something specific with my app configuration or hub connection to pass things around correctly?

Refresh Tokens

Are you considering adding support for refresh tokens? One thing that our users frequently request is to stay logged in for longer and Auth0 restricts us a bit on how long the tokens last.

Permissions not setting on Identity (webasm project)

Hi!
Possibly the thing is in my Auth0 misconfiguration, but I cannot make this policies work at the end. After authentication is completed and navigating to /fetchdata page I see You're not authorized to reach this page.

Tried to expose identity's claims and they do not contain anything like
'permissions' => 'read:weather_forecast', but contains only basics claims such as nickname, email, sub, phone, updated_at...

How should I add this permissions in Auth0 settings to my users: on the user base, role, rule or api?

Google Social Connection: Login not successful

Hi,

I am just playing around with this awesome library for Blazor. Thanks for your efforts. But I am currently stuck with the handling of the returning code from Auth0. I completely can login using Auth0 and my Google Account, but when I am redirected back to the Blazor application, I am still recognized as Unauthorized / not logged in.

In my Auth0 Console I see a failing silent login.

Did I miss something?

I also tested your examples (proprietary as well as built-in) with my Auth0 Account but both didn't work.

Any suggestions?

Could not load type 'System.Text.Json.Serialization.JsonSerializer'

Getting this error on startup of the app.

Happened before the core preview 7 update and remains after the preview 7 update

Error: System.TypeLoadException: Could not load type 'System.Text.Json.Serialization.JsonSerializer' from assembly 'System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. at Blazor.Auth0.Shared.Authentication.AuthenticationServiceBase.GetAccessToken(:44325/String code) at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](:44325/TStateMachine& stateMachine) at Blazor.Auth0.Shared.Authentication.AuthenticationServiceBase.GetAccessToken(:44325/String code) at Blazor.Auth0.Shared.Authentication.AuthenticationServiceBase.HandleAuth0Message(:44325/Auth0IframeMessage message) at endInvokeDotNetFromJS (blazor.server.js:8) at blazor.server.js:8 at new Promise (<anonymous>) at e.beginInvokeJSFromDotNet (blazor.server.js:8) at blazor.server.js:1 at Array.forEach (<anonymous>) at e.invokeClientMethod (blazor.server.js:1) at e.processIncomingData (blazor.server.js:1) at e.connection.onreceive (blazor.server.js:1) at WebSocket.i.onmessage (blazor.server.js:1) endInvokeDotNetFromJS @ blazor.server.js:8 (anonymous) @ blazor.server.js:8 beginInvokeJSFromDotNet @ blazor.server.js:8 (anonymous) @ blazor.server.js:1 e.invokeClientMethod @ blazor.server.js:1 e.processIncomingData @ blazor.server.js:1 connection.onreceive @ blazor.server.js:1 i.onmessage @ blazor.server.js:1 Promise.then (async) messageListener @ VM164:34

AuthService.Authorize not redirecting to auth0 in preview5

Hi, upon upgrading to server side preview 5, when I click login (AuthService.Authorize), I'm being redirected to /account/authorize and getting:

Sorry, there's nothing at this address.

Insted of the auth0 login page, this same code was working on preview 4, and does work for client side in preview 5 as it is in a shared library. Looks like the routes for /account are not being registered as before for the server side. If I enable "RequireAuthenticatedUser": true, the login redirect loops infinitely.

I appreciate your help.

No login button on new setup

The getting started instructions from preview <5 had a login/logout button already coded in, but in the new instructions for preview 6 there isnt, is this intentional?

ClientSide: Lose tokens when refresh page

Hello,
I'm just taking a look at the client-side example and have the following problem:

  1. Login
  2. Refresh the page
  3. User is logged out, has to click Login again (albeit they don't have to re-enter their credentials).

Is there a way to stop this step of having to re-click Login?

Many thanks,
Steve

Auth0 Roles/Claims not being exposed to AuthorizeView

This may or may not be something you are working on, but we're attempting to use Blazor's built in Authorization and Authentication with your Auth0 components.

The API is setup correctly and the user has the custom claims, but when trying to see if a user is in a specific role it always acts as if they are not.

Any suggestions on how to fix this or is it even possible?

Periodic view update causes issues

Every 30 to 45 seconds an iframe will be injected (I assume to validate the users session). During this time it triggers a 'StateHasChanged' method call and causes my components to re-render.

This would be okay for text and other static items but I have on page where we're showing a chart and when it re-renders it animates causing the app to not act naturally.

Is there a way to disable this background refresh?

So far that's the only issue/bug we've seen, we really appreciate you putting in the time on this project!

Clientside [Blazor WASM] authentication not working in Preview 5

Hi @henalbrod ,
Decided to experiment with the updated Blazor template
3.2.0-preview1.20073.1 and upgraded Blazor.Auth0 to Preview 5 but it looks like it does not even make a call to Auth0....nothing in the Auth0 dashboard logs.

image

Is there a flag where we can toggle on the logs generated by Blazor.Auth0.Clientside &/or Blazor.Auth0.Shared?

blazor route with encrypted parameter

How can I make my blazor application receive encrypted parameters that contain special characters such as "/" and "+" without it not understanding that the special characters are parameter dividers, please help urgently!

image

Ability to get Authentication Status in Code Behind

Love what you've done so far, we're using this successfully without any issues so far.

I do have a question however. Is it possible to get the authentication state in the code behind? Specifically we'd like to get access to the claims and user details in Hangfire which is able to get the HTTPContext for the request, but the User is unauthenticated although they are actually authenticated.

Our hangfire issue is a one off I'm sure, the real issue is that the HTTPContext is not showing the user as authenticated.

Any thoughts on how to address this?

Thanks in advance :)

Client Side redirect avoid page refresh

Hi,

First of all, your library is fantastic.

I am trying to integrate in the http://playground.nethereum.com as a client side github social authentication to publish gist to github, but when login in / authenticating the user you have to reload the whole blazor application.

I have seen that you use iframes to logout of the applications, is this something you are considering to enable login in?

Any other thoughts / ideas ?

Many thanks in advance

Deploy to storage account

When I deploy to a storage account my Blazor WebAssembly client I always get the following error:

image

Please I need your help because I couldn't make it work

Not compiling Client side

Added the following package
Blazor-Auth0-ClientSide -Version 0.7.2-beta.2

and I'm consistently being faced with the following error on running dotnet run under VS Code.

exited with code -532462766

Please check the Nuget package.

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.