Skip to content

xavehoo/XAF_how-to-use-google-facebook-and-microsoft-accounts-in-aspnet-xaf-applications-oauth2-demo-t535280

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

69 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Files to look at:

How to: Use Google, Facebook and Microsoft accounts in ASP.NET XAF applications (OAuth2 demo)

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

<appSettings>
    <add key="GoogleClientID" value="YourGoogleClientID" />
    <add key="GoogleClientSecret" value="YourGoogleClientSecret" />
    <add key="FacebookClientID" value="YourFacebookClientID" />
    <add key="FacebookClientSecret" value="YourFacebookClientSecret" />
    <add key="MicrosoftClientID" value="YourMicrosoftClientID" />
    <add key="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#

OAuthProvider authProvider = new OAuthProvider(typeof(OAuthUser), securityStrategyComplex1);
authProvider.CreateUserAutomatically = true;

VB.NET

Dim authProvider As New 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 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:

<authentication mode="None" /> 
  <!--<forms name="Login" loginUrl="Login.aspx" path="/" timeout="10" />--> 
</authentication> 
    <!--<authorization> 
      <deny users="?" /> 
      <allow users="*" /> 
    </authorization>-->


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.svg
AuthenticationOwin.Module.Web\Images\Google.svg
AuthenticationOwin.Module.Web\Images\Microsoft.png
AuthenticationOwin.Web\Startup.cs(vb)
AuthenticationOwin.Web\LogonTemplateContent1.ascx
AuthenticationOwin.Web\LogonTemplateContent1.ascx.cs(vb)
AuthenticationOwin.Web\LogonTemplateContent1.ascx.designer.cs(vb)
AuthenticationOwin.Web\Login.aspx
AuthenticationOwin.Web\Login.aspx.designer.cs
AuthenticationOwin.Module/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#

this.securityStrategyComplex1 = new AuthenticationOwin.Module.Web.Security.CustomSecurityStrategyComplex();

VB.NET

Me.securityStrategyComplex1 = New AuthenticationOwin.Module.Web.Security.CustomSecurityStrategyComplex()

Use AuthenticationMixed instead of your authentication:

C#

public YourApplicationNameAspNetApplication() {
  InitializeComponent();
  //...
  AuthenticationMixed authenticationMixed = new AuthenticationMixed();
  authenticationMixed.LogonParametersType = typeof(AuthenticationStandardLogonParameters);
  authenticationMixed.AuthenticationProviders.Add(typeof(CustomAuthenticationStandardProvider).Name, new CustomAuthenticationStandardProvider(typeof(OAuthUser)));
  OAuthProvider authProvider = new OAuthProvider(typeof(OAuthUser), securityStrategyComplex1);
  authProvider.CreateUserAutomatically = true;
  authenticationMixed.AuthenticationProviders.Add(typeof(OAuthProvider).Name, authProvider);
  securityStrategyComplex1.Authentication = authenticationMixed;

VB.NET

Public Sub New()
  InitializeComponent()
  '...
  Dim authenticationMixed As New AuthenticationMixed()
  authenticationMixed.LogonParametersType = GetType(AuthenticationStandardLogonParameters)
  authenticationMixed.AuthenticationProviders.Add(GetType(CustomAuthenticationStandardProvider).Name, New CustomAuthenticationStandardProvider(GetType(OAuthUser)))
  Dim authProvider As New 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#

WebApplication.Instance.Settings.LogonTemplateContentPath = "LogonTemplateContent1.ascx"; 

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.


About

.NET, Frameworks (XAF & XPO), eXpressApp Framework

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 63.2%
  • ASP.NET 28.0%
  • HTML 8.8%