This example demonstrates the use of OAuth2 authentication in a web application. Users can sign in to the application via Google, Facebook or Microsoft authentication providers.
![]()
You can try this demo "as is" to overview its capabilities, and then try the demonstrated functionality in your own XAF applications according to the instructions below.
How to Run this Demo
Before running this demo, register developer accounts at the services you are going to use
•
https://console.developers.google.com/ (Make sure that 'Google+ API' is enabled. Read more here:
Creating a Google app for OAuth 2 and connecting the app to the project)
•
https://developers.facebook.com/
•
https://portal.azure.com/
• Open the
Web.config file and specify your own client IDs and client secrets for each provider.
[XML]
<appSettings><addkey="GoogleClientID"value="YourGoogleClientID"/><addkey="GoogleClientSecret"value="YourGoogleClientSecret"/><addkey="FacebookClientID"value="YourFacebookClientID"/><addkey="FacebookClientSecret"value="YourFacebookClientSecret"/><addkey="MicrosoftClientID"value="YourMicrosoftClientID"/><addkey="MicrosoftClientSecret"value="YourMicrosoftClientSecret"/>
You can remove keys corresponding to providers that you do not want to use.
Note that you may need to update nuget packages to work correctly.
Now you can run the application.
Overview of this Demo Capabilities
In the logon window, there are buttons for each provider specified in Web.config:
![]()
Standard XAF authentication with built-in username/password is also supported. When you log in via OAuth authentication, the email is used as a user name. By default, a user object is autocreated for each logon. You can disable autocreation, or specify the auto-assigned role for new users in the InitializeComponent method (see AuthenticationOwin.Web/WebApplication.cs(vb)):
C#
[C#]
OAuthProviderauthProvider=newOAuthProvider(typeof(OAuthUser),securityStrategyComplex1);authProvider.CreateUserAutomatically=true;
VB.NET
[VB.NET]
Dim authProvider AsNew OAuthProvider(GetType(OAuthUser), securityStrategyComplex1)
authProvider.CreateUserAutomatically = True
When CreateUserAutomatically is false, the logon is allowed if a user with the email returned by the external service exists in the application database. To grant access to a user with a specific e-mail, use the built-in Admin account, create a user object and set the UserName to this e-mail.
![]()
If you set the EnableStandardAuthentication property to true for an auto-created user, this user will be able to login directly, with a user name and password. Note that the password is empty by default, so do not forget to specify it when enabling standard authentication.
![]()
Each user can have several associated email addresses. To add or remove email addresses, use the OAuth Authorization Emails list in the user's Detail View.
![]()
How to Implement the Demonstrated Functionality in your XAF Application
1. In your solution, open
Package Manager Console.
1.1. Choose the YourSolutionName.Web project in the Default project combo box, and execute the following commands to add Owin packages:
Install-Package Microsoft.Owin -Version 4.1.0
Install-Package Microsoft.Owin.Cors -Version 4.1.0
Install-Package Microsoft.Owin.Security -Version 4.1.0
Install-Package Microsoft.Owin.Security.Cookies -Version 4.1.0
Install-Package Microsoft.Owin.Host.SystemWeb -Version 4.1.0
Install-Package Microsoft.Owin.Security.Google -Version 4.1.0
Install-Package Microsoft.Owin.Security.Facebook -Version 4.1.0
Install-Package Microsoft.Owin.Security.MicrosoftAccount -Version 4.1.0
1.2. Switch to the YourSolutionName.Module.Web project and install these two packages:
Install-Package Microsoft.AspNet.Cors -Version 5.2.7
Install-Package Microsoft.Owin -Version 4.1.0
Install-Package Microsoft.Owin.Host.SystemWeb -Version 4.1.0
Install-Package Microsoft.Owin.Security -Version 4.1.0
2. Open the
YourSolutionName.Module.Web/Web.config file and specify your own client IDs and client secrets for each provider you are going to use. Refer to the
AuthenticationOwin.Web\Web.config file in the demo solution to see the example. Then, set the authentication mode to "None" and comment or remove settings related to the default XAF authentication:
[XML]
<authenticationmode="None"/></authentication>
3. Copy the following files from the demo solution to the corresponding locations within your solution:
AuthenticationOwin.Module\IAuthenticationOAuthUser.cs(vb)AuthenticationOwin.Module\BusinessObjects\OAuthUser.cs(vb)AuthenticationOwin.Module.Web\Controllers\LogonAuthController.cs(vb)AuthenticationOwin.Module.Web\Security\CustomSecurityStrategyComplex.cs(vb)AuthenticationOwin.Module.Web\Images\Facebook.svgAuthenticationOwin.Module.Web\Images\Google.svgAuthenticationOwin.Module.Web\Images\Microsoft.pngAuthenticationOwin.Web\Startup.cs(vb)AuthenticationOwin.Web\LogonTemplateContent1.ascxAuthenticationOwin.Web\LogonTemplateContent1.ascx.cs(vb)AuthenticationOwin.Web\LogonTemplateContent1.ascx.designer.cs(vb)AuthenticationOwin.Web\Login.aspxAuthenticationOwin.Web\Login.aspx.designer.csAuthenticationOwin.Web\Security\CustomAuthenticationStandardProvider.cs(vb)AuthenticationOwin.Web\Security\OAuthProvider.cs(vb)Include the copied files to your solution (Add|Existing Item... ). Update the namespace names in the copied code files to match namespaces you use in your solution. For image files, set the Build Action property to Embedded Resource.
4.
Edit the
YourSolutionName.Module.Web\WebModule.cs(vb) file. In the overridden
Setup method, handle the
XafApplication.CreateCustomLogonWindowControllers event and add the
LogonAuthController to the
e.Controllers collection passed to this event. Refer to the
AuthenticationOwin.Module.Web\Module.cs(vb) file to see an example.
5.
Edit the
YourSolutionName.Web\WebApplication.cs(vb) code:
Register CustomSecurityStrategyComplex:
C#
[C#]
this.securityStrategyComplex1=newAuthenticationOwin.Module.Web.Security.CustomSecurityStrategyComplex();
VB.NET
[VB.NET]
Me.securityStrategyComplex1 = New AuthenticationOwin.Module.Web.Security.CustomSecurityStrategyComplex()
Use AuthenticationMixed instead of your authentication:
C#
[C#]
publicYourApplicationNameAspNetApplication(){InitializeComponent();AuthenticationMixedauthenticationMixed=newAuthenticationMixed();authenticationMixed.LogonParametersType=typeof(AuthenticationStandardLogonParameters);authenticationMixed.AuthenticationProviders.Add(typeof(CustomAuthenticationStandardProvider).Name,newCustomAuthenticationStandardProvider(typeof(OAuthUser)));OAuthProviderauthProvider=newOAuthProvider(typeof(OAuthUser),securityStrategyComplex1);authProvider.CreateUserAutomatically=true;authenticationMixed.AuthenticationProviders.Add(typeof(OAuthProvider).Name,authProvider);securityStrategyComplex1.Authentication=authenticationMixed;
VB.NET
[VB.NET]
PublicSubNew()
InitializeComponent() Dim authenticationMixed AsNew AuthenticationMixed()
authenticationMixed.LogonParametersType = GetType(AuthenticationStandardLogonParameters)
authenticationMixed.AuthenticationProviders.Add(GetType(CustomAuthenticationStandardProvider).Name, New CustomAuthenticationStandardProvider(GetType(OAuthUser))) Dim authProvider AsNew OAuthProvider(GetType(OAuthUser), securityStrategyComplex1)
authProvider.CreateUserAutomatically = True
authenticationMixed.AuthenticationProviders.Add(GetType(OAuthProvider).Name, authProvider)
securityStrategyComplex1.Authentication = authenticationMixed
6.
Implement the
IAuthenticationOAuthUser interface in your custom user class. You can see an example in the
AuthenticationOwin.Module\BusinessObjects\OAuthUser.cs file. If you use the built-in user, you can use the
OAuthUser class and set the
SecurityStrategy.UserType property to
OAuthUser in the
Application Designer.
7.
Change the code that creates your predefined users in
YourSolutionName.Module\DatabaseUpdate\Updater.cs. Set
EnableStandardAuthentication to
true for users who can login with standard authentication (username and password). See the example in the
AuthenticationOwin.Module\DatabaseUpdate\Updater.cs file.
8.
Register the
LogonTemplateContent1.ascx template in the
Session_Start method in the
YourSolutionName.Web\Global.asax.cs(vb) file:
C#
[C#]
WebApplication.Instance.Settings.LogonTemplateContentPath="LogonTemplateContent1.ascx";
VB.NET
[VB.NET]
WebApplication.Instance.Settings.LogonTemplateContentPath = "LogonTemplateContent1.ascx"
9.
Copy the
LoginWith* actions customizations and the
AuthenticationStandardLogonParameters_DetailView layout settings from the
AuthenticationOwin.Web\Model.xafml file to the same file in the
YourSolutionName.Web project. If you have no model customizations in
Model.xafml, you can just overwrite it with the file from demo. Ensure that the
IsPostBackRequired property of each
LoginWith* action is set to true.
10.
Configure OAuth2 provider services according to their documentation.
This example shows how XAF can get a user's email from OAuth2 services and create (or authenticate) a user based on this data (the OAuthProvider.Authenticate method).
Note that a third-party API and settings of OAuth2 services (Google, Facebook, and Microsoft) that we use in this example often change and we cannot control this at the level of our components. While we try to keep this example up-to-date with these changes, it is always better to refer to the official OAuth2 provider documentation. Please leave comments or create merge requests to this example if you find any inconsistencies.
Known OAuth2 services specificities:
• Microsoft
requires the '/signin-microsoft' string to the Redirect URI (validated on March 13th 2020);
•
![chrome_2020-03-13_11-58-18w]()
• "The Microsoft.Owin.Security.MicrosoftAccount assembly supports authenticating to both: Microsoft user accounts and Azure AD (School/Orgnizational) user accounts. To successfully authenticate an Azure AD user account in this demo project, ensure that you configure the Azure AD registered application as 'multi-tenanted = yes'. (The manifest entry: "availableToOtherTenants": true)" - added by
nrpieper:
• Google requires to enable the Google+ API.
Tip: You can refer to the OWIN OAuth 2.0 Authorization Server documentation to learn how to add more authentication providers.
For an example of integrating OAuth2 authentication in a WinForms XAF application, refer to the XAF - OAuth2 Authentication for WinForms ticket.
Files to look at:
•
LogonAuthController.cs (VB:
LogonAuthController.vb)
•
CustomSecurityStrategyComplex.cs (VB:
CustomSecurityStrategyComplex.vb)
•
OAuthUser.cs (VB:
OAuthUser.vb)
•
IAuthenticationOAuthUser.cs (VB:
IAuthenticationOAuthUser.vb)
•
CustomAuthenticationStandardProvider.cs (VB:
CustomAuthenticationStandardProvider.vb)
•
OAuthProvider.cs (VB:
OAuthProvider.vb)
•
Startup.cs (VB:
Startup.vb)
•
WebApplication.cs (VB:
WebApplication.vb)
See Also
Office.Cloud.Microsoft Module in eXpand Framework by Apostolis Bekiaris - authenticates against Azure Active Directory and contains API for querying the Microsoft Graph endpoints.