OpenIddict 4 WebProviders does not configure external authentication schemes - asp.net-core

I am just wondering if anyone has some experience with this. I am trying out OpenIddict 4.0.0 to put together a real-life solution with the new Identity UI and razor pages approach. However when I register an external auth provider using the suggested unified OpenIddict.Client.WebIntegration package, I cannot see the providers on the default login page external section.
I also tried to use the openiddict-core sandbox aspnet.core server app but that as well does not show the configured GitHub external login option.
I could explicitly create links for the providers, however I do not see that as a convenient solution. The default code segment that calls SignInManager.GetExternalAuthenticationSchemesAsync() does not seem to collect the external providers registered using
options.UseWebProviders().UseGitHub() ...
What am I missing here? Thanks

It's a deliberate design choice, explained in this post comparing the aspnet-contrib providers with the OpenIddict providers:
The aspnet-contrib providers use an authentication scheme per
provider, which means you can do [Authorize(AuthenticationSchemes = "Facebook")] to trigger an authentication dance. In contrast, the
OpenIddict client uses a single authentication scheme and requires
setting the issuer as an AuthenticationProperties item if multiple
providers are registered.
For the same reason, the providers registered via the OpenIddict
client are not listed by Identity's
SignInManager.GetExternalAuthenticationSchemesAsync() and so don't
appear in the "external providers" list returned by the default
Identity UI. In practice, many users will prefer customizing this part
to be more user-friendly, for instance by using localized provider
names or logos, which is not something you can natively do with
SignInManager.GetExternalAuthenticationSchemesAsync() anyway.

Related

Open ID Connect for authentication - why require packages if it is a standard?

I have a need to implement Open ID Connect in an ASP.NET Core 5 web app for authentication at an organization. I cannot test against the identity provider as this org has their own internal one.
I thought Open ID Connect (oidc) was a standard - yet when I look at docs and sample code for the various providers around, they all either have something provided with ASP.NET or I have to install their package.
For example, to use Google, the ASP.NET Core docs say to use services.AddAuthentication().AddGoogle(). For Facebook, it says to use .AddFacebook().
For Auth0, it wants me to install the package Auth0.AspNetCore.Authentication.
Is it not possible to just add OIDC authentication to my app and have it work with any OIDC provider and just change a configuration file to specify the authority URL, Client ID, Client Secret?
I'm confused about why I need these provider-specific calls and packages.
Architecturally, tieing an app to a single form of authentication is entirely wrong, as you suggest. These packages have limited use, perhaps for very simple use cases.
The original OAuth 2.0 spec from RFC6749, from 2012, describes how the OAuth framework is designed, to externalize difficult security from your apps:
The client only implements a code flow
It redirects to an authorization server (AS)
The AS can authenticate users in a myriad of potential ways, including many identity providers
After authentication (and possibly consent) the AS issues tokens to your apps
Tokens enable authorization in your APIs in a myriad of potential ways
Once you've implemented a code flow in your app, your set of users can potentially login in many ways, with zero code changes in the app:
Password sign in (a default option)
Multi-factor authentication (in a dynamic way potentially)
Cloud platform identity providers (for engineering staff)
CRM identity provider (for client focused staff)
SAML identity providet (for users from business partners)
Webauthn, Passkeys and Digital wallets (for some of your customers)
Unless you have a very good reason, stick to OpenID Connect standards based code flows in clients. You can do all of the above using the Microsoft libraries. Auth0 have good libraries also - just make sure you use the standards based ones.
OpenID Connect is an open standard that organisations use to
authenticate users. IdPs use this so that users can sign in to the IdP
From this blog.
And about the OIDC protocol, it allows you to authenticate users, and is designed for users to sign in many websites with only one account, usually it's a social/work account. This is only a protocol and you have to use an implement such as Google/Azure authentication to allow your users to sign in with their specific account.
By the way, since the implements are from different companies, so the configuration in our codes are different and they required different nuget packages like Microsoft.Identity.Web. For example, when using Azure, we need to set such as client id, client secret, tenant id, domain, redirect url... in appsettings.json.

What is the difference between MicrosoftAccount, AzureAD and OpenIdConnect authentication?

I got absolutely confused when trying to understand the differences between MicrosoftAccount, AzureAD and OpenIDConnect authentications.
I am trying to build a .Net Core MVC app that allows some users to authenticate with local accounts, but some with Microsoft accounts. I do need to have a local user in DB for both types of authentications as I have some custom authorization mechanisms built on that.
I started with creating the app from template and selected "local accounts" authentication. Then I added the MicrosoftAccount authentication according to this tutorial (https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins?view=aspnetcore-3.1). This is using Microsoft.AspNetCore.Authentication.MicrosoftAccount and seems to be working fine.
However, when I create a new app from template and select "work or school account" authentication I can see it uses a different library - Microsoft.AspNetCore.Authentication.AzureAD.UI. It seems to do the same thing. I can see there are events I could hook into to connect the AAD user with my local DB.
Looking through the web I found some other tutorials that were using OpenIDConnect for the same purpose.
How are those methods different? Which one should I use and why?
In future I would like to be able to query the user's directory for a list of other users. Would that requirement be easier met with either of those three methods?
MicrosoftAccount: This is the login with a general Microsoft account, using OAuth2. This is also what Microsoft will refer to as “private account” and useful when you want to authenticate someone just using their Microsoft login as an external authentication provider. This is similar to how you would sign in to sites with your Google account.
AzureAD: This is the sign in to a specific Azure tenant. This is often understood as a “work or school account” because it doesn’t sign people in using a public account but rather some account bound to some organization. Usually, you would have an Azure tenant where you have direct users (or configure it to allow external users) but you want to control access through that Azure AD.
OpenIdConnect: This is the general OpenID Connect protocol which you can use to sign in with many different authentication providers because it is a protocol that many of them will support. You can use OIDC to sign in to either of the above (and many other services) but that will require you to do some more configuration as you will need to figure out specific addresses for example.
You can always use the OpenIdConnect or the OAuth authentication scheme to authenticate with most authentication providers but those are the “manual” schemes which will require you to configure additional things. All the other authentication schemes, including MicrosoftAccount and AzureAD but also the other ones like Google or Twitter build on top of those protocols and come preconfigured so that you do not need to set up much else. So those are mostly for convenience and for more specialized support.
So when you want to authentication through Microsoft or Azure, then you should choose MicrosoftAccount or AzureAD. Which of those depends on where you want to authenticate with. If you have an Azure AD, then you should use that.

Using Openiddict for user identity management and application access

I have a .NET Core web API that uses openiddict for identity management that is tied to ASP.NET identity in a SQL server backend. Many applications can leverage this API with a subscription. I have the following requirements.
Only authorized applications can use the API
Each application can optionally use the identity features of the API to manage their application specific users as implemented by Openiddict within the API (currently the authorization, password, and refresh token flows are enabled).
All endpoints should require that an application be in the Oppenidict application table and this application ID should be available on every request due to multi-tenant support in the API.
Endpoints that have an [Authorize] attribute must be have a user that is authenticated via the Openiddict identity model.
To implement requirement (1), would I need to implement a custom authorization function that checks for an application secret or should another flow be enabled in openiddict that takes care of ensuring only authorized applications are allowed access to the API (regardless of authorize attributes)? In this case, a user may not be authenticated, but the application must still have rights to access the non-authorized endpoints of the API.
To implement requirement (2) for external identity providers, is it possible to configure multiple secrets for each application registered within openiddict to allow their users to leverage facebook or twitter for authentication? This is important, because the API would need call AddFacebook() during configuration for each application that can access the API (not the clientID and secret of the API itself). Because multiple applications each have their own facebookID and secret, I would assume this would only work if openiddict could allow the registration of multiple Ids and secrets for the same provider type via AddFacebook() for example.
To implement requirement (3), is there a built in way to get the application ID of the calling application from openiddict like there is if the user was authenticated?
To implement requirement (1), would I need to implement a custom authorization function that checks for an application secret or should another flow be enabled in openiddict that takes care of ensuring only authorized applications are allowed access to the API (regardless of authorize attributes)?
Starting with RC3, client identification was made mandatory by default: if you don't send a client_id corresponding to an entry in the applications table, your request will be rejected by OpenIddict itself. In previous versions, you could opt for this feature by calling options.RequireClientIdentification() (it's now opt-out).
To implement requirement (2) for external identity providers, is it possible to configure multiple secrets for each application registered within openiddict to allow their users to leverage facebook or twitter for authentication? This is important, because the API would need call AddFacebook() during configuration for each application that can access the API (not the clientID and secret of the API itself). Because multiple applications each have their own facebookID and secret, I would assume this would only work if openiddict could allow the registration of multiple Ids and secrets for the same provider type via AddFacebook() for example.
There's no direct relationship between OpenIddict and the authentication schemes you use, so no, you can't configure multiple Facebook credentials "via" OpenIddict as the two are unrelated.
Assuming you need that for multitenancy purposes, you may want to read https://stackoverflow.com/a/49682427/542757 to learn how you can override ASP.NET Core's default options monitor so you can provide tenant-specific options for authentication handlers like OpenIddict, Facebook, Google and anything else.
To implement requirement (3), is there a built in way to get the application ID of the calling application from openiddict like there is if the user was authenticated?
Assuming it's known (i.e you didn't explicitly make client identification optional in the OpenIddict options), yes. E.g from a MVC controller:
var result = await HttpContext.AuthenticateAsync(OpenIddictValidationDefaults.AuthenticationScheme);
Debug.Assert(result.Ticket != null, "The authentication ticket shouldn't be null.");
// The presenters list contains the authorized parties allowed to
// use the access token with your APIs. Usually, it contains a single value.
// Note: this extension requires a using for AspNet.Security.OpenIdConnect.Extensions.
var client = result.Ticket.GetPresenters().FirstOrDefault();

Difference between UseCookieAuthentication and UseIdentity?

In ASP.NET Core Startup in Configure method when you are configuring piplelines you can use UseIdentity from ASP.NET Core Identity or you can use UseCookieAuthentication. Both of them provide cookie based authentication.
I want to know what is their difference. Is UseIdentity uses UseCookieAuthentication internally? What are advantages and disadvantages of one over another?
Thanks for your explanations.
From the docs which can be found here and here.
Cookie Authentication Middleware:
ASP.NET Core provides cookie middleware which serializes a user principal into an encrypted cookie and then, on subsequent requests, validates the cookie, recreates the principal and assigns it to the User property on HttpContext. If you want to provide your own login screens and user databases you can use the cookie middleware as a standalone feature.
Identity:
ASP.NET Core Identity is a membership system which allows you to add login functionality to your application. Users can create an account and login with a user name and password or they can use an external login providers such as Facebook, Google, Microsoft Account, Twitter and more.
In short Identity builds on just local authentication and provides the ability to perform external authentication as well as baked in solutions for provisioning user accounts.
The pros and cons of each differ depending on your business and both have their own place which I find is usually determine on a case by case basis.
The inner workings for Identity can be found on the github page here.
Is UseIdentity uses UseCookieAuthentication internally?
Yes.
However, both UseIdentity and UseCookieAuthentication will be deprecated in Auth 2.0.
UseIdentity
UseCookieAuthentication
services.AddCookieAuthentication() and app.UseAuthentication() will be used instead.
Important note: Don't use UseCookieAuthentication, if you have UseIdentity. I mixed them together in a project. Claim-based authorization redirected user to LoginPage instead of AccessDenied page.

Multiple Authentication / Authorization support for Web API via OWIN

I have a Web API project of ours that needs to be secured. I am planning to allow the user's that registered with my app to use the API [Forms Authentication], users with their own organizational accounts [ADFS] and Social Sign-In.
I have all the middleware available to plug-in and make available to the user's. However, in my application I do have custom roles and privileges that are to be provided so that my application authorizes the service calls based on the existing privileges. What is the best way to accomplish this.
I think that I will be required to provide my own custom implementation of the UserStore and UserManager with my own IUser Implementation.
Kindly suggest the best practice for this scenario.
With multiple authentication middleware registered, you can get multiple claimidentity's.
register each type of authentication you want to support.
I would be sure to add a claims transformation module at the end of the pipeline. Thinktecture has an example. ThinkTecture Owin Claims Transformer
This would give you one place to look up and add all the application type claims for an authenticated user in one spot.
Simple pseudo example (geared to webapi, but concept the same). Authenticate with bearer or basic or both then transform.
//identity 2.0 user manager stuff used in your modules
app.CreatePerOwinContext(ApplicationSession.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Token Authentication -> get a principle
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
// Basic Authentication. -> get a principle
app.UseBasicAuthentication(app.CreateLogger<BasicAuthenticationMiddleware>(),
"Realm", ValidateUser);
// transform claims to application identity. Add additional claims if needed
app.UseClaimsTransformation(TransformClaims);
It sounds like you are looking for externalized authorization. Externalized authorization is the act of:
decoupling business logic from authorization logic
expressing authorization logic as centrally managed, centralized authorization policies
protecting your APIs through a common layer
enabling fine-grained & dynamic access control through the use of attribute-based access control (ABAC) which extends what's possible with RBAC (role-based access control).
Have a look at XACML, the eXtensible Access Control Markup Language. You can find some more information on OASIS's website.
Also check out NIST's project on ABAC.
Once you defined your authorization logic, you can decide how to enforce it. This can be done either via direct enforcement at the entry of your apps or can be done in a provisioning way whereby the permissions derived from the authorization policies are fed into an authentication token e.g. SAML as attribute assignments.
HTH
This is what I ended up designing for a system with similar requirements. The key is to separate the authentication and authorization logic.
Build Owin authentication middleware components that take care of establishing user identity based on various login methods you mentioned. Looks like you have this accomplished. Set ASP.NET identity based on the user.
Retrieve the roles/permissions for the logged in user from your store. This can be done as a separate Owin middleware or a part of your authentication. Add the permissions as Claims to your Principal.
Extend your roles/permissions store to map API service operations to the application permissions.
Implement a custom API Authorize attribute and apply it to every API operation. In this attribute you will have access to the operation name and the user Claims (permissions). Match the Claims with the permissions you mapped in the step above. If there is a match, return IsAuthorized=true, otherwise, return false.
Here is a similar issue at a simpler level.
How do you setup mixed authorizations for different authentications in .net (web api 2 + owin)