forked from Sustainsys/Saml2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommandResultExtensions.cs
93 lines (80 loc) · 3.02 KB
/
CommandResultExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using Sustainsys.Saml2.WebSso;
using Microsoft.Owin;
using Microsoft.Owin.Security.DataProtection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Sustainsys.Saml2.Owin
{
static class CommandResultExtensions
{
public static void Apply(this CommandResult commandResult,
IOwinContext context,
IDataProtector dataProtector)
{
if (commandResult == null)
{
throw new ArgumentNullException(nameof(commandResult));
}
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
context.Response.ContentType = commandResult.ContentType;
context.Response.StatusCode = (int)commandResult.HttpStatusCode;
if (commandResult.Location != null)
{
context.Response.Headers["Location"] = commandResult.Location.OriginalString;
}
if (commandResult.TerminateLocalSession)
{
context.Authentication.SignOut();
}
foreach(var h in commandResult.Headers)
{
context.Response.Headers[h.Key] = h.Value;
}
ApplyCookies(commandResult, context, dataProtector);
// Write the content last, it causes the headers to be flushed
// on some hosts.
if (commandResult.Content != null)
{
// Remove value set by other middleware and let the host calculate
// a new value. See issue #295 for discussion on this.
context.Response.ContentLength = null;
context.Response.Write(commandResult.Content);
}
}
private static void ApplyCookies(CommandResult commandResult, IOwinContext context, IDataProtector dataProtector)
{
var serializedCookieData = commandResult.GetSerializedRequestState();
if (serializedCookieData != null && !string.IsNullOrEmpty(commandResult.SetCookieName))
{
var protectedData = HttpRequestData.ConvertBinaryData(
dataProtector.Protect(serializedCookieData));
context.Response.Cookies.Append(
commandResult.SetCookieName,
protectedData,
new CookieOptions()
{
HttpOnly = true,
});
}
commandResult.ApplyClearCookie(context);
}
public static void ApplyClearCookie(this CommandResult commandResult, IOwinContext context)
{
if (!string.IsNullOrEmpty(commandResult.ClearCookieName))
{
context.Response.Cookies.Delete(
commandResult.ClearCookieName,
new CookieOptions
{
HttpOnly = true
});
}
}
}
}