public HttpListenerIdentityService(ChannelAuthenticationContext context) { _context = context; }
private bool AuthenticationFailedIfRequired(HttpListenerContext context, HttpListenerRequest request, HttpListenerResponse response, ChannelConfigurationInfo channelConfig, out bool authenticated) { bool failed = false; bool validCookie = false; authenticated = false; bool authorized = false; if (channelConfig.ChannelAttribute.EnableSessions) { validCookie = ValidSession(request); } if (channelConfig.AuthenticationRequired && !validCookie) { try { ChannelAuthenticationContext authContext = new ChannelAuthenticationContext { Context = context, Scheme = channelConfig.AuthScheme, BasicAuthenticationDelegate = _basicAuthenticationMethod, TokenAuthenticationDelegate = _tokenAuthenticationMethod, AuthenticationSettings = _settings }; KeyValuePair <bool, object> authenticationResult = _authenticationService.CheckAuthenticationAndGetResponseObject(authContext); if (authenticationResult.Key == true) { authenticated = true; } else { _msgService.FailedAuthenticationResponse(channelConfig.AuthScheme, response); failed = true; } LogChannel.Write(LogSeverity.Info, "User Authenticated"); string claimName = channelConfig.AuthorizeAttribute.ClaimName; string claimValue = channelConfig.AuthorizeAttribute.ClaimValue; if (!String.IsNullOrEmpty(claimName) && !String.IsNullOrEmpty(claimValue)) { if (authenticationResult.Value.GetType() == typeof(ClaimsPrincipal)) { authorized = _authenticationService.Authorized(claimName, claimValue, (ClaimsPrincipal)authenticationResult.Value); } else { authorized = _authenticationService.Authorized(claimName, claimValue, (Claim[])authenticationResult.Value); } if (!authorized) { _msgService.FailedAuthorizationResponse(response); LogChannel.Write(LogSeverity.Error, "Failed authorization"); failed = true; } else { LogChannel.Write(LogSeverity.Info, "User Authorized"); } } } catch (Exception ex) { using (StreamWriter writer = new StreamWriter(response.OutputStream)) { _msgService.ExceptionHandler(writer, ex, response); LogChannel.Write(LogSeverity.Error, "Authentication Failed"); failed = true; } } if (!authenticated) { failed = true; } else { if (channelConfig.ChannelAttribute.EnableSessions) { string sessionKey = Guid.NewGuid().ToString(); Cookie sessionCookie = new Cookie() { Expires = DateTime.Now.AddMinutes(30), Name = "channelAuthCookie", Secure = true, Value = sessionKey }; response.SetCookie(sessionCookie); _sessionKeys.Add(sessionCookie); } } } return(failed); }