Get current authentication scheme in ASP.NET core 2

余生长醉 提交于 2021-01-26 10:35:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!