Resolve ISitecoreService using SimpleInjector - sitecore

ISitecoreService accepts database name as a string parameter in its constructor (web or master)
ISitecoreService service = new SitecoreService("master"); //or
ISitecoreService service = new SitecoreService("web");
Is it possible I dynamically send database name as parameter to IoC and resolve it? for example I send web/master string parameter and get a new instance of ISitecoreService

Like this?
container.Register<ISitecoreService>(() => new SitecoreService("master"));

Expanding on Stevens answer as I have experience with Sitecore and I love Simpleinjector.
If you like you can get at the Sitecore configuration when your application is bootstrapping using the configuration factory, access the website site configuration and use the database property.
var sites = Sitecore.Configuration.Factory.GetSiteInfoList();
var website = sites.Single(s => s.Name == "website");
ISitecoreService service = new SitecoreService(website.Database);
container.Register<ISitecoreService>(() => service);
This way your SitecoreService will be newed up with the same database that is defined in the website configuration.

Related

How does jetty.security.ConfigurableSpnegoLogin work?

I'm trying to make a jetty server use kerberos. For this, I found that there is a built-in solution, called org.eclipse.jetty.security.ConfigurableSpnegoLoginService.
Unfortunately, I haven't found any useful documentation for this. There is one closed issue in the github jetty project about this, but those comments did not help either.
Can someone point me to an example on how to use it? I only need this for authentication, but no authorization.
The way I'd use it is something like this:
ConfigurableSpnegoLoginService spnegoLoginService = new ConfigurableSpnegoLoginService(....);
//set up the spnegoLoginService
ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
securityHandler.setLoginService(spnegoLoginService);
The SPNEGOAuthenticationTest has a server side component example.
server = new Server();
server.setSessionIdManager(new DefaultSessionIdManager(server));
HashLoginService authorizationService = new HashLoginService(realm,
realmPropsPath.toString());
ConfigurableSpnegoLoginService loginService =
new ConfigurableSpnegoLoginService(realm,
AuthorizationService.from(authorizationService, ""));
loginService.addBean(authorizationService);
loginService.setKeyTabPath(serviceKeyTabPath);
loginService.setServiceName(serviceName);
loginService.setHostName(serviceHost);
server.addBean(loginService);
ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
Constraint constraint = new Constraint();
constraint.setAuthenticate(true);
constraint.setRoles(new String[]{"**"}); //allow any authenticated user
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec("/secure");
mapping.setConstraint(constraint);
securityHandler.addConstraintMapping(mapping);
authenticator = new ConfigurableSpnegoAuthenticator();
securityHandler.setAuthenticator(authenticator);
securityHandler.setLoginService(loginService);
securityHandler.setHandler(handler);
SessionHandler sessionHandler = new SessionHandler();
sessionHandler.setHandler(securityHandler);
To use ConfigurableSpnegoLoginService you require (must have / not optional) ...
A Servlet / HTTP Authentication realm
A Servlet Authentication role
A Servlet Constraint + Constraint Mapping
An AuthorizationService (but you don't want a authorization??)
A ConfigurableSpnegoAuthenticator
Not entirely sure how you will satisfy the "no authorization" part with spnego/kerberos + http authentication + servlet constraint / authentication in the mix. Maybe you have to drop the "no authorization" part and define proper authorization / roles, but put everyone in the same role??

Unable to authenticate in accessing Dynamic CRM Online Web Service

I need to utilize Dynamic CRM Data Service Endpoint exposed to get data from one of the methods.
Service(microsoft) account has access to this service.
I've tried authenticating to Discovery Service and Organization Service using sample code provided here [https://msdn.microsoft.com/en-us/library/hh675404.aspx] and succeed. However am not able to use same authentication to access data Service as I could find anyway to relate Data Service with the other two. Doing basic authentication using Network Credentials does not work.
I have downloaded the CSDL exposed and added that as service reference to my project, which created an class of web service which extends from DataServiceContext. Am trying to retrieve data of one of the methods using LinQ queries. It returs following error:
"The response payload is a not a valid response payload. Please make sure that the top level element is a valid Atom or JSON element or belongs to 'http://schemas.microsoft.com/ado/2007/08/dataservices' namespace." On capturing using fiddle I realized that on hitting data service URL it is redirected to sign in page 'login.microsoftonline.com/'
Can anybody suggest a way to authenticate the user to access Data Serivce?
Adding code:
//<snippetAuthenticateWithNoHelp1>
IServiceManagement<IDiscoveryService> serviceManagement =
ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(
new Uri(_discoveryServiceAddress));
AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;
// Set the credentials.
AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType);
String organizationUri = String.Empty;
// Get the discovery service proxy.
using (DiscoveryServiceProxy discoveryProxy =
GetProxy<IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
{
// Obtain organization information from the Discovery service.
if (discoveryProxy != null)
{
// Obtain information about the organizations that the system user belongs to.
OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy);
// Obtains the Web address (Uri) of the target organization.
organizationUri = FindOrganization(_organizationUniqueName,
orgs.ToArray()).Endpoints[EndpointType.OrganizationService];
}
}
//</snippetAuthenticateWithNoHelp1>
if (!String.IsNullOrWhiteSpace(organizationUri))
{
//<snippetAuthenticateWithNoHelp3>
IServiceManagement<IOrganizationService> orgServiceManagement =
ServiceConfigurationFactory.CreateManagement<IOrganizationService>(
new Uri(organizationUri));
// Set the credentials.
AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType);
// Get the organization service proxy.
using (OrganizationServiceProxy organizationProxy =
GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials))
{
// This statement is required to enable early-bound type support.
organizationProxy.EnableProxyTypes();
// Now make an SDK call with the organization service proxy.
// Display information about the logged on user.
Guid userid = ((WhoAmIResponse)organizationProxy.Execute(
new WhoAmIRequest())).UserId;
SystemUser systemUser = organizationProxy.Retrieve("systemuser", userid,
new ColumnSet(new string[] { "firstname", "lastname" })).ToEntity<SystemUser>();
Console.WriteLine("Logged on user is {0} {1}.",
systemUser.FirstName, systemUser.LastName);
Uri x = new Uri("https://<MyOrgainzationName>.crm.dynamics.com/XRMServices/2011/OrganizationData.svc/");
MyOrgainzationContext saContext = new MyOrgainzationContext(x);
NetworkCredential nc = new NetworkCredential();
nc.UserName = "*****#microsoft.com";
nc.Password = "********";
saContext.Credentials = nc;
var query_where3 = from c in saContext.new_productSet
select new
{
ProductStatus = c.new_ProductStatus,
LineofBusiness = c.new_LineofBusiness
};
var temp = saContext.Entities;
foreach (var c in query_where3)
{
System.Console.WriteLine("ProductStatus: " +
c.ProductStatus +
"\t\t\t" +
"LineofBusiness: " +
c.LineofBusiness);
}
}
//</snippetAuthenticateWithNoHelp3>
}
MyOrganizationContext is the context class created on adding CSDL file exposed at service endpoints
Have a look at the CRM Web Api Preview: https://msdn.microsoft.com/en-us/dynamics/crm/webapipreview.aspx. You can call this endpoint from outside xRM and you can authenticate with OAuth 2.0.

Having Separate Certificates Running Under GlassFish 2

Can anyone please explain how i can have more than one X.509 Certificates in my GlassFish application server?
The main challenge for me is that GlassFish uses just one alias which is 's1as'.
You can pull additional certificates from external key files to create an SSLContext and then SSLSocketFactory, which you can feed into your external HTTPS calls.
E.g.:
KeyStore cKeyStore = KeyStore.getInstance("PKCS12");
try (InputStream clientCertKeyInput = new FileInputStream("my.pfx")) {
cKeyStore.load(clientCertKeyInput, "password".toCharArray());
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(cKeyStore, "password".toCharArray());
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(keyManagerFactory.getKeyManagers(),
null, // default javax.net.ssl.trustStore
new SecureRandom());
SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
You may then configure an HttpsURLConnection with it:
httpsConn.setSSLSocketFactory(sslSocketFactory);
Or if you're using JAXWS set it as a property of the BindingProvider's context:
Map<String, Object> ctxt = ((BindingProvider) port).getRequestContext();
ctxt.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslSocketFactory);
Hope this helps.

New Google Drive Directory APIs error out: Bad request

I am using below piece of code to list all domain users in my simple Console application
var certificate = new X509Certificate2("D:\\3acf2c2008cecd33b43de27e30016a72e1482c41-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable);
var privateKey = certificate.Export(X509ContentType.Cert);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = "877926787679-b7fd15en1sh2oc65e164v90cfcvrfftq#developer.gserviceaccount.com",
Scope = DirectoryService.Scopes.AdminDirectoryUserReadonly.GetStringValue(),
ServiceAccountUser = "user1#05.mygbiz.com"
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
DirectoryService dirService = new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "My APP"
});
Users users = dirService.Users.List().Execute();
Execute() method errors out saying Bad Request.
Questions:
How to overcome this issue?
Does this Admin SDK support trial version of Google APP account?
I have updated service account Client ID in Google Console and also updated in Admin Console with below scopes
https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.user
and also set API access check box. Do I missing something in settings?
Like JoBe said, you should include the domain parameter.
happy_user = service.users().list(domain='mydomain.com').execute()
This has worked for me.

WSO2 Admin services BAMMediatorConfigAdmin

I am trying to add BAM server profile (under ESB server) using Admin Web services. I am not seeing any error thrown while executing as standalone program but profile is not getting added. Please advise if below steps are correct -
Get admin cookie by connecting to "AuthenticationAdmin" URL
Create stubs using wsdl2java from "BAMMediatorConfigAdmin" WSDL
String bamcepServerProfileServiceURL = Constant.SERVICE_URL + "BAMMediatorConfigAdmin";
BAMMediatorConfigAdminStub stub = new BAMMediatorConfigAdminStub(bamcepServerProfileServiceURL);
ServiceClient client = stub._getServiceClient();
Options option = client.getOptions();
option.setManageSession(true);
option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, adminCookie);
BAMMediatorConfigAdminStub.BamServerConfig bamConfig = new BAMMediatorConfigAdminStub.BamServerConfig();
bamConfig.setUsername("admin");
bamConfig.setPassword("admin");
bamConfig.setLoadbalanced(false);
bamConfig.setSecurity(true);
bamConfig.setIp("localhost");
bamConfig.setAuthenticationPort("7611");
BAMMediatorConfigAdminStub.SaveBamServerConfig config = new BAMMediatorConfigAdminStub.SaveBamServerConfig();
config.setBamServerConfig(bamConfig);
stub.saveBamServerConfig(config);
Please check #addResource in[1], which creates the profile and calls ,
stub.saveResourceString(resourceString, bamServerProfileLocation);
through #saveResourceString in[2]
[1]https://svn.wso2.org/repos/wso2/carbon/platform/branches/4.1.0/components/mediators/bam/org.wso2.carbon.mediator.bam.config.ui/4.1.0/src/main/java/org/wso2/carbon/mediator/bam/config/ui/BamServerProfileUtils.java
[2]https://svn.wso2.org/repos/wso2/carbon/platform/branches/4.1.0/components/mediators/bam/org.wso2.carbon.mediator.bam.config.ui/4.1.0/src/main/java/org/wso2/carbon/mediator/bam/config/ui/BamServerProfileConfigAdminClient.java