1
0
mirror of https://github.com/bitwarden/server.git synced 2025-03-02 04:11:04 +01:00
bitwarden-server/bitwarden_license/src/Sso/Utilities/OpenIdConnectOptionsExtensions.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

63 lines
2.3 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
2020-09-04 19:56:08 +02:00
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Bit.Sso.Utilities;
2022-08-29 22:06:55 +02:00
2020-09-04 19:56:08 +02:00
public static class OpenIdConnectOptionsExtensions
{
public static async Task<bool> CouldHandleAsync(this OpenIdConnectOptions options, string scheme, HttpContext context)
{
// Determine this is a valid request for our handler
if (options.CallbackPath != context.Request.Path &&
options.RemoteSignOutPath != context.Request.Path &&
options.SignedOutCallbackPath != context.Request.Path)
2022-08-29 20:53:16 +02:00
{
2020-09-04 19:56:08 +02:00
return false;
}
2020-09-04 19:56:08 +02:00
if (context.Request.Query["scheme"].FirstOrDefault() == scheme)
2022-08-29 22:06:55 +02:00
{
2020-09-04 19:56:08 +02:00
return true;
2022-08-29 22:06:55 +02:00
}
try
{
2020-09-04 19:56:08 +02:00
// Parse out the message
OpenIdConnectMessage message = null;
if (string.Equals(context.Request.Method, "GET", StringComparison.OrdinalIgnoreCase))
{
message = new OpenIdConnectMessage(context.Request.Query.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value)));
}
else if (string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrEmpty(context.Request.ContentType) &&
context.Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) &&
context.Request.Body.CanRead)
{
var form = await context.Request.ReadFormAsync();
message = new OpenIdConnectMessage(form.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value)));
}
2022-08-29 22:06:55 +02:00
var state = message?.State;
2020-09-04 19:56:08 +02:00
if (string.IsNullOrWhiteSpace(state))
2022-08-29 20:53:16 +02:00
{
2020-09-04 19:56:08 +02:00
// State is required, it will fail later on for this reason.
return false;
2022-08-29 20:53:16 +02:00
}
2022-08-29 20:53:16 +02:00
// Handle State if we've gotten that back
var decodedState = options.StateDataFormat.Unprotect(state);
if (decodedState != null && decodedState.Items.ContainsKey("scheme"))
2022-08-29 22:06:55 +02:00
{
2020-09-04 19:56:08 +02:00
return decodedState.Items["scheme"] == scheme;
2022-08-29 22:06:55 +02:00
}
}
catch
{
2020-09-04 19:56:08 +02:00
return false;
}
2022-08-29 22:06:55 +02:00
2020-09-04 19:56:08 +02:00
// This is likely not an appropriate handler
return false;
}
}