'Get current authentication scheme in ASP.NET core 2
I am currently struggling with an Asp.net core 2 application which uses two openid providers for authentication, mapped to two different Authentication Schemes (with different names).
The problem I am facing is trying to logout of the specific scheme that is currently being used. For example, if I support both Google and Facebook authentication, I need to understand which scheme is currently being used, and call the SignOut method indicating the correct scheme. This allows me to clear the local cookies and also redirect the user to the external identity provider and logout.
The thing is that I am not able to find a GetCurrentScheme() sort of function so that I can use to then specify the scheme in the SignOut method. I am sure I am missing something basic...
Solution 1:[1]
There does not seem be any direct way to find current scheme. Here is a crude way:
private readonly IAuthenticationSchemeProvider authenticationSchemeProvider;
...
foreach(var scheme in authenticationSchemeProvider.GetRequestHandlerSchemesAsync()){
var authResult = await context.AuthenticateAsync(scheme.Name);
if(authResult.Succeeded)
// this is the scheme that was used for authentication
}
Solution 2:[2]
I had the same question, but I finally put the authentication scheme in the claims collection in my SignIn method :
claims.Add(new Claim(ClaimTypes.AuthenticationMethod, authenticationScheme));
So, in the SignOut method, I can retrieve the authentication scheme :
var authenticationScheme = HttpContext.User.FindFirstValue(ClaimTypes.AuthenticationMethod);
Solution 3:[3]
IAuthenticationHandler has also Task InitializeAsync(AuthenticationScheme scheme, HttpContext context). It is called before AuthenticateAsync scheme name is here in first parameter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zendu |
| Solution 2 | Kakone |
| Solution 3 | PacificGoal |
