问题
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...
回答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
}
回答2:
I had a similar problem when I needed to use different authentication types - JWT and Cookies. You can get the current scheme using IAuthenticationSchemeProvider which also provides other information about the authentication.
private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider;
public AuthController(IAuthenticationSchemeProvider authenticationSchemeProvider)
{
_authenticationSchemeProvider = authenticationSchemeProvider;
}
-
public async Task<bool> Logout()
{
// Default AuthenticationScheme
AuthenticationScheme defaultScheme = await _authenticationSchemeProvider.GetDefaultAuthenticateSchemeAsync();
// The scheme that will be used by default
AuthenticationScheme defaultSignoutScheme = await _authenticationSchemeProvider.GetDefaultSignOutSchemeAsync();
// Returns all schemes currently registered
IEnumerable<AuthenticationScheme> listAuthenticationSchemeProvider = await _authenticationSchemeProvider.GetAllSchemesAsync();
await HttpContext.SignOutAsync(defaultScheme.Name);
return true;
}
Docs
来源:https://stackoverflow.com/questions/54832713/get-current-authentication-scheme-in-asp-net-core-2