I use IdentityServer3. My startup class is bellow.
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/identity", idsrvApp =>
{
var corsPolicyService = new DefaultCorsPolicyService()
{
AllowAll = true
};
var idServerServiceFactory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get());
//.UseInMemoryUsers(Users.Get());
idServerServiceFactory.CorsPolicyService = new Registration<IdentityServer3.Core.Services.ICorsPolicyService>(corsPolicyService);
idServerServiceFactory.ViewService = new Registration<IViewService, CustomViewService>();
idServerServiceFactory.UserService = new Registration<IUserService>(resolver => new CustomUserService());
var options = new IdentityServerOptions
{
EnableWelcomePage = false,
Factory = idServerServiceFactory,
SiteName = "Justice Identity Server",
IssuerUri = IdentityConstants.ecabinetIssuerUri,
PublicOrigin = IdentityConstants.ecabinetSTSOrigin,
AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions() {
CookieOptions = {
AllowRememberMe=false,
Prefix="IC"
},
EnablePostSignOutAutoRedirect = true,
},
SigningCertificate = LoadSertificate(),
CspOptions = new CspOptions()
{
Enabled = true,
ScriptSrc = "'unsafe-inline'",
ConnectSrc = "*",
FrameSrc = "*"
},
};
idsrvApp.UseIdentityServer(options);
});
}
X509Certificate2 LoadSertificate()
{
return new X509Certificate2(string.Format(#"{0}\certificates\cert.pfx", AppDomain.CurrentDomain.BaseDirectory), "123", X509KeyStorageFlags.MachineKeySet);
}
}
After sometimes I have got "bad request-request too long" ,when I clear cookie it works. I have seen in console a lot of nonce cookies.
Anyone could help me?
thanks you
This is a known issue.
There is more info there: https://github.com/IdentityServer/IdentityServer3/issues/1124
Related
Well.. I'm trying this code to create an Event
CalendarService service;
GoogleCredential credential;
try
{
string[] scopes = new string[] { CalendarService.Scope.Calendar };
using (var stream = new FileStream(#"C:\Prueba\meet.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
Event calendarEvent = new Event();
DateTime start = DateTime.Now;
calendarEvent.Kind = "";
calendarEvent.Summary = "prueba";
calendarEvent.Status = "confirmed";
calendarEvent.Visibility = "public";
calendarEvent.Description = "prueba";
calendarEvent.Creator = new Event.CreatorData
{
Email = "email#example.com", //email#example.com
Self = true
};
calendarEvent.Organizer = new Event.OrganizerData
{
Email = "email#example.com",
Self = true
};
calendarEvent.Start = new EventDateTime
{
DateTime = start,
TimeZone = "America/Mexico_City"
};
calendarEvent.End = new EventDateTime
{
DateTime = start.AddHours(1),
TimeZone = "America/Mexico_City"
};
calendarEvent.Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=1" };
calendarEvent.Sequence = 0;
calendarEvent.HangoutLink = "";
calendarEvent.ConferenceData = new ConferenceData
{
CreateRequest = new CreateConferenceRequest
{
RequestId = "1234abcdef",
ConferenceSolutionKey = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
},
Status = new ConferenceRequestStatus
{
StatusCode = "success"
}
},
EntryPoints = new List<EntryPoint>
{
new EntryPoint
{
EntryPointType = "video",
Uri = "",
Label = ""
}
},
ConferenceSolution = new ConferenceSolution
{
Key = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
},
Name = "Google Meet",
IconUri = ""
},
ConferenceId = ""
};
//calendarEvent.EventType = "default";
EventsResource.InsertRequest request = service.Events.Insert(calendarEvent, "email#example.com");
request.ConferenceDataVersion = 0;
Event createEvent = request.Execute();
string url = createEvent.HangoutLink;
}
catch (Exception ex)
{
}
The source code is here
When I execute the line 116: Event createEvent = request.Execute();
I get this error: Google.Apis.Requests.RequestError Invalid conference type value. [400] Errors [Message[Invalid conference type value.] Location[ - ] Reason[invalid] Domain[global]
I don't know what means this error o with line I wrong
Could anyone help me with an example to create an event using classes C# from Google API Calendar?
As described in the C# library documentation for createRequest:
Either conferenceSolution and at least one entryPoint, or createRequest is required.
This means that you should use only CreateConferenceRequest as this conference is brand new (if it already existed then you would be wanting to use ConferenceSolution along with EntryPoints ). Therefore, simply remove ConferenceSolution and EntryPoints to leave just CreateConferenceRequest which as specified in the documentation is used for generating a new conference and attach it to the event.
I'm using the Saucelabs Selenium implementation to automate my testing across multiple devices and platforms.
Using the demo code from SauceLabs (below) doesn't work behind a proxy.
I've tried adding the proxy details to the DesiredCapibilities but this doesn't seem to do anything
[TestMethod]
public void TestSauceLabs()
{
DesiredCapabilities caps = new DesiredCapabilities();
caps.SetCapability("browserName", "Safari");
caps.SetCapability("platform", "macOS 10.13");
caps.SetCapability("version", "11.1");
caps.SetCapability("username", _sauceUserName);
caps.SetCapability("accessKey", _sauceAccessKey);
caps.SetCapability("name", _name);
var tags = new List<string> {"demoTest", "sauceDemo"};
caps.SetCapability("tags", tags);
caps.SetCapability("maxDuration", 3600);
caps.SetCapability("commandTimeout", 600);
caps.SetCapability("idleTimeout", 1000);
caps.SetCapability("build", "SauceDemo");
/****************************************
* Edited demo code here
* Added proxy config to DesiredCapabilities **
*/
var proxy = new Proxy
{
IsAutoDetect = false,
HttpProxy = $"{_proxyScheme}://{_proxyHost}:{_proxyPort}",
SslProxy = $"{_proxyScheme}://{_proxyHost}:{_proxyPort}",
FtpProxy = $"{_proxyScheme}://{_proxyHost}:{_proxyPort}"
};
caps.SetCapability(CapabilityType.Proxy, proxy);
/*
*****************************************/
var uri = new Uri("https://ondemand.eu-central-1.saucelabs.com/wd/hub");
_driver = new RemoteWebDriver(uri,
caps, TimeSpan.FromSeconds(600));
_javascriptExecutor = ((IJavaScriptExecutor) _driver);
_javascriptExecutor.ExecuteScript("sauce:context=Open SauceDemo.com");
_driver.Navigate().GoToUrl(_url);
_javascriptExecutor.ExecuteScript("sauce:context=Sleep for 10000ms");
Thread.Sleep(10000);
Assert.IsTrue(true);
var passed = true;
_javascriptExecutor.ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}
Found the solution was to use the HttpCommandExecutor when using the RemoteWebDriver behind a proxy.
Here is my example code:
[TestMethod]
public void TestSauceLabs_Chrome()
{
var remoteOptions = new Dictionary<string, object>
{
{ "username", _sauceUserName },
{ "accessKey", _sauceAccessKey },
{ "name", _name },
{ "maxDuration", 3600 },
{ "commandTimeout", 600 },
{ "idleTimeout", 1000 }
};
var options = new ChromeOptions()
{
PlatformName = "Windows 10",
BrowserVersion = "latest"
};
//Remote options need to be global
options.AddAdditionalCapability("sauce:options", remoteOptions, true);
var caps = options.ToCapabilities();
/*
Using the HttpCommandExecutor persists the proxy details
and allows you to pass in credentials if required
*/
var executor = new HttpCommandExecutor(
new Uri("https://ondemand.eu-central-1.saucelabs.com/wd/hub"),
TimeSpan.FromSeconds(600))
{
Proxy = GenerateProxy()
};
_driver = new RemoteWebDriver(executor, caps);
_javascriptExecutor = ((IJavaScriptExecutor)_driver);
_javascriptExecutor.ExecuteScript($"sauce:context=Open {_url}");
_driver.Navigate().GoToUrl(_url);
_javascriptExecutor.ExecuteScript("sauce:context=Sleep for 10000ms");
Thread.Sleep(10000);
Assert.IsTrue(true);
var passed = true;
_javascriptExecutor.ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
_driver?.Quit();
}
public WebProxy GenerateProxy()
{
var proxy = new WebProxy
{
Address = new Uri($"{_proxyScheme}://{_proxyHost}:{_proxyPort}"),
BypassProxyOnLocal = false,
UseDefaultCredentials = _networkCredential != null,
Credentials = _networkCredential
};
return proxy;
}
I'm getting Microsoft.Rest.HttpOperationException: 'Operation returned an invalid status code 'BadRequest'' on this line.
var result = client.CreateNamespacedDeployment(deployment, namespace);
Kubernetes-client has a small number of good resources and most of them is written in other language such as java and python. So i'm referring to these documentations.
this is my implementation so far.
V1Deployment deployment = new V1Deployment()
{
ApiVersion = "extensions/v1beta1",
Kind = "Deployment",
Metadata = new V1ObjectMeta()
{
Name = "...",
NamespaceProperty = env,
Labels = new Dictionary<string, string>()
{
{ "app", "..." }
}
},
Spec = new V1DeploymentSpec
{
Replicas = 1,
Selector = new V1LabelSelector()
{
MatchLabels = new Dictionary<string, string>
{
{ "app", "..." }
}
},
Template = new V1PodTemplateSpec()
{
Metadata = new V1ObjectMeta()
{
CreationTimestamp = null,
Labels = new Dictionary<string, string>
{
{ "app", "..." }
}
},
Spec = new V1PodSpec
{
Containers = new List<V1Container>()
{
new V1Container()
{
Name = "...",
Image = "...",
ImagePullPolicy = "Always",
Ports = new List<V1ContainerPort> { new V1ContainerPort(80) }
}
}
}
}
},
Status = new V1DeploymentStatus()
{
Replicas = 1
}
};
var result = client.CreateNamespacedDeployment(deployment, namespace);
I want to know the proper way on how to create kubernetes deployment using kubernetes-client, and also i want to know the cause of this issue.
For the full clarity and future visitors, it's worth to mention, what is exactly behind this bad request error (code: 400) returned from API server, when using your code sample:
"the API version in the data (extensions/v1beta1) does not match the expected API version (apps/v1)"
Solution:
ApiVersion = "extensions/v1beta1" -> ApiVersion = "apps/v1"
Full code sample:
private static void Main(string[] args)
{
var k8SClientConfig = new KubernetesClientConfiguration { Host = "http://127.0.0.1:8080" };
IKubernetes client = new Kubernetes(k8SClientConfig);
ListDeployments(client);
V1Deployment deployment = new V1Deployment()
{
ApiVersion = "apps/v1",
Kind = "Deployment",
Metadata = new V1ObjectMeta()
{
Name = "nepomucen",
NamespaceProperty = null,
Labels = new Dictionary<string, string>()
{
{ "app", "nepomucen" }
}
},
Spec = new V1DeploymentSpec
{
Replicas = 1,
Selector = new V1LabelSelector()
{
MatchLabels = new Dictionary<string, string>
{
{ "app", "nepomucen" }
}
},
Template = new V1PodTemplateSpec()
{
Metadata = new V1ObjectMeta()
{
CreationTimestamp = null,
Labels = new Dictionary<string, string>
{
{ "app", "nepomucen" }
}
},
Spec = new V1PodSpec
{
Containers = new List<V1Container>()
{
new V1Container()
{
Name = "nginx",
Image = "nginx:1.7.9",
ImagePullPolicy = "Always",
Ports = new List<V1ContainerPort> { new V1ContainerPort(80) }
}
}
}
}
},
Status = new V1DeploymentStatus()
{
Replicas = 1
}
};
Closing this issue (Resolved)
Reference: https://github.com/Azure/autorest/issues/931
Cause of issue: incorrect version of Kubernetes ApiVersion.
Solution: get and replace ApiVersion from kubernetes api.
Can also handle the exception using:
try
{
var result = client.CreateNamespacedDeployment(deployment, namespace);
}
catch (Microsoft.Rest.HttpOperationException httpOperationException)
{
var phase = httpOperationException.Response.ReasonPhrase;
var content = httpOperationException.Response.Content;
}
I am using Identity Server 3 with Entity Framework. My ASP.NET MVC app logs in to the SSO/IdentityServer app using below configuration and then that access token is saved in a cookie which is used by javascript to call our API.
Problem is when I login to my ASP.NET MVC app then I go to database and delete that token from the database table, then my API says invalid bearer token as expected, but when I the refresh page in the ASP.NET MVC app, it still shows as logged in and I think it's because of cookie configuration.
How can I ask MVC app to always validate token from server?
AuthConfig.cs of ASP.NET MVC application:
public static class AuthConfig
{
public static void RegisterAuth(IAppBuilder app)
{
ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
SlidingExpiration = true,
ExpireTimeSpan = SellutionConstants.Globals.AccessTokenExpirationTimeSpan
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = "sellutionapp",
Authority = SsoConfigHelper.SellutionSts,
ResponseType = "code id_token",
Scope = "openid profile roles all_claims " + SsoConfigHelper.SellutionApiScope,
UseTokenLifetime = false,
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role",
},
SignInAsAuthenticationType = "Cookies",
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async n =>
{
// use the code to get the access and refresh token
var tokenClient = new TokenClient(
SsoConfigHelper.SellutionStsTokenEndpoint,
"sellutionapp",
"secret");
if (String.IsNullOrEmpty(n.RedirectUri))
{
n.RedirectUri = n.Request.Scheme + "://" + n.Request.Host + n.Request.PathBase;
}
var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);
if (tokenResponse.IsError)
{
throw new Exception(tokenResponse.Error);
}
// use the access token to retrieve claims from userinfo
var userInfoClient = new UserInfoClient(
new Uri(SsoConfigHelper.SellutionStsUserInfoEndpoint),
tokenResponse.AccessToken);
var userInfoResponse = await userInfoClient.GetAsync();
// create new identity
var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
id.AddClaims(userInfoResponse.GetClaimsIdentity().Claims);
id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));
//id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value));
LoginCookieHelper.SetUserData(tokenResponse.AccessToken);
n.AuthenticationTicket = new AuthenticationTicket(
new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
n.AuthenticationTicket.Properties);
},
RedirectToIdentityProvider = n =>
{
// This ensures that the address used for sign in and sign out is picked up dynamically from the request
// this allows you to deploy the app (to Azure Web Sites, for example) without having to change settings.
var appBaseUrl = n.Request.Scheme + "://" + n.Request.Host + n.Request.PathBase;
n.ProtocolMessage.RedirectUri = appBaseUrl;
n.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
// if signing out, add the id_token_hint
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
{
var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");
if (idTokenHint != null)
{
n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
}
}
return Task.FromResult(0);
}
}
});
}
}
Identity server configuration:
class Factory
{
public static IdentityServerServiceFactory Configure()
{
var efConfig = new EntityFrameworkServiceOptions
{
ConnectionString = "DefaultConnection",
};
// these two calls just pre-populate the test DB from the in-memory config
ConfigureClients(Clients.Get(), efConfig);
ConfigureScopes(Scopes.Get(), efConfig);
var factory = new IdentityServerServiceFactory();
//var scopeStore = new InMemoryScopeStore(Scopes.Get());
//factory.ScopeStore = new Registration<IScopeStore>(scopeStore);
//var clientStore = new InMemoryClientStore(Clients.Get());
//factory.ClientStore = new Registration<IClientStore>(clientStore);
factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true });
factory.RegisterOperationalServices(efConfig);
factory.RegisterConfigurationServices(efConfig);
return factory;
}
public static void ConfigureClients(IEnumerable<Client> clients, EntityFrameworkServiceOptions options)
{
using (var db = new ClientConfigurationDbContext(options.ConnectionString, options.Schema))
{
if (!db.Clients.Any())
{
foreach (var c in clients)
{
var e = c.ToEntity();
db.Clients.Add(e);
}
db.SaveChanges();
}
}
}
public static void ConfigureScopes(IEnumerable<Scope> scopes, EntityFrameworkServiceOptions options)
{
using (var db = new ScopeConfigurationDbContext(options.ConnectionString, options.Schema))
{
if (!db.Scopes.Any())
{
foreach (var s in scopes)
{
var e = s.ToEntity();
db.Scopes.Add(e);
}
db.SaveChanges();
}
}
}
}
IdentityServer client configuration
public class Clients
{
public static List<Client> Get()
{
return new List<Client>
{
new Client
{
ClientName = "Resource Owner Flow",
ClientId = "resourceowner",
ClientSecrets = new List<Secret> {new Secret("vkgk8M4pj".Sha256())},
Flow = Flows.ResourceOwner , //Password authentication
PrefixClientClaims = false,
AccessTokenType = AccessTokenType.Jwt,
AllowedScopes = new List<string>
{
Constants.StandardScopes.OpenId,
Constants.StandardScopes.Profile,
Constants.StandardScopes.Email,
Constants.StandardScopes.Roles,
Constants.StandardScopes.Address,
Constants.StandardScopes.AllClaims,
Constants.StandardScopes.OfflineAccess,
SsoConfigHelper.SellutionApiScope
},
RequireConsent = false,
AllowRememberConsent = true,
LogoutSessionRequired = true,
RefreshTokenExpiration = TokenExpiration.Absolute,
RefreshTokenUsage = TokenUsage.OneTimeOnly,
UpdateAccessTokenClaimsOnRefresh = true,
AbsoluteRefreshTokenLifetime =(int)TimeSpan.FromDays(1).TotalSeconds
},
/////////////////////////////////////////////////////////////
// MVC OWIN Implicit Client
/////////////////////////////////////////////////////////////
new Client
{
ClientName = "Sellution Application",
ClientId = "sellutionapp",
Flow = Flows.Hybrid,
AllowAccessTokensViaBrowser = false,
AllowedScopes = new List<string>
{
Constants.StandardScopes.OpenId,
Constants.StandardScopes.Profile,
Constants.StandardScopes.Email,
Constants.StandardScopes.Roles,
Constants.StandardScopes.Address,
Constants.StandardScopes.AllClaims,
SsoConfigHelper.SellutionApiScope
},
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
AccessTokenType = AccessTokenType.Reference,
RequireConsent = false,
AllowRememberConsent = true,
LogoutSessionRequired = true,
},
};
}
}
You need to sign the user out of the MVC application as well because according to your code you are using Cookie Authentication named Cookies you also have to do a sign out on that authentication scheme when they log out (not deleteing the token in the store).
AuthenticationManager.SignOut("Cookies"); is what your controller action will require for logout.
What Do I have:
var subscriptionId = "xxx";
var thumbprint = "xxx";
var certificate = GetCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint);
var autoscaleClient = new AutoscaleClient(new CertificateCloudCredentials(subscriptionId, certificate));
var createParams = new AutoscaleSettingCreateOrUpdateParameters
{
Setting = new AutoscaleSetting
{
Enabled = true,
Profiles = new List<AutoscaleProfile>
{
new AutoscaleProfile
{
Capacity = new ScaleCapacity
{
Default ="1",
Maximum="10",
Minimum="1"
},
Name = "anurag",
Recurrence= new Recurrence
{
Frequency=RecurrenceFrequency.Week,
Schedule = new RecurrentSchedule
{
Days = new List<string>{"Monday", "Thursday", "Friday"},
Hours = {7, 19},
Minutes=new List<int>{0},
TimeZone = "Pacific Standard Time"
}
},
Rules=new List<ScaleRule>
{
new ScaleRule
{
MetricTrigger =new MetricTrigger
{
MetricName="Test Metric",
MetricNamespace="",
MetricSource=
AutoscaleMetricSourceBuilder.BuildWebSiteMetricSource("???", "???"),
Operator=ComparisonOperationType.GreaterThan,
Threshold=2000,
Statistic=MetricStatisticType.Average,
TimeGrain=TimeSpan.FromMinutes(5),
TimeAggregation=TimeAggregationType.Average,
TimeWindow=TimeSpan.FromMinutes(30)
},
ScaleAction = new ScaleAction
{
Direction = ScaleDirection.Increase,
Cooldown = TimeSpan.FromMinutes(20),
Type=ScaleType.ChangeCount,
Value = "4"
}
}
}
}
}
}
};
var resourceId = AutoscaleResourceIdBuilder.BuildWebSiteResourceId("???", "???");
var autoscaleResponse = autoscaleClient.Settings.CreateOrUpdate(resourceId, createParams);
I am confused about two API calls:
AutoscaleResourceIdBuilder.BuildWebSiteResourceId(string webspace, string serverFarmName)
AutoscaleMetricSourceBuilder.BuildWebSiteMetricSource(string webspaceName, string websiteName)
What is a webspace, server farm name, webspace name and web site name? Where Do I get them?