PoshCode Archive  Artifact [7d23767d2c]

Artifact 7d23767d2c95e853396b98ab1a25b8adf4b0ebb229b7ace05cd73e5d29de62c0:

  • File OpenRasta.ps1 — part of check-in [891c1636d3] at 2018-06-10 13:12:00 on branch trunk — Basic authentication class, with really simple dumb cookie set. (user: unknown size: 2064)

# encoding: ascii
# api: powershell
# title: OpenRasta
# description: Basic authentication class, with really simple dumb cookie set.
# version: 0.1
# type: class
# license: CC0
# x-poshcode-id: 2529
# x-archived: 2011-03-02T12:47:40
#
# This is based on the OpenRastaAuth Sample https://github.com/scottlittlewood/OpenRastaAuthSample.git
# a
#
	public class MyBasicAuthenticator : IBasicAuthenticator
	{
		private readonly IUserCredentials _users;

		public ICommunicationContext Context { get; set; }

		public MyBasicAuthenticator(IUserCredentials users)
		{
			_users = users;
		}

		public string Realm
		{
			get { return "Web Service v1"; }
		}

		/// <summary>
		/// Create the cookie if doesnt exist allready, really simmple at moment.
		/// </summary>
		private void SetCookie(string key, string val)
		{
			var response = Context.Response;
			var request = Context.Request;

			if (!request.Headers.ContainsKey("Cookie"))
			{
				if (!response.Headers.ContainsKey("Set-Cookie")) // POINT 1. not sure why this is required.
				{
					response.Headers.Add("Set-Cookie", String.Format("{0}={1};", key, val));
				}
			}
		}

		public AuthenticationResult Authenticate(BasicAuthRequestHeader header)
		{
			var credentials = _users.GetCredentialsFor(header.Username);
			if (credentials != null && credentials.Password == header.Password)
			{
				SetCookie("sessionkey", "moo");
				return new AuthenticationResult.Success(header.Username);
			}
			return new AuthenticationResult.Failed();
		}
	}


// how its registered //
				ResourceSpace.Uses.BasicAuthentication<MyBasicAuthenticator>();

	public static class ExtensionsToIUses
	{
		public static void BasicAuthentication<TBasicAuthenticator>(this IUses uses) where TBasicAuthenticator : class, IBasicAuthenticator
		{
			uses.CustomDependency<IAuthenticationScheme, BasicAuthenticationScheme>(DependencyLifetime.Singleton);
			uses.CustomDependency<IBasicAuthenticator, TBasicAuthenticator>(DependencyLifetime.Transient);
		}
	}