Apigility Zend: Get Authentication Service Using Key Name - zend-framework2

I have setup database adapter in config and I can get database service in Factory using key name like:
$connectDb = $services->get('connectDb');
and then I have setup authentication adapter with key name: 'connectoauth2'
It is working fine and authenticate my rest api.
The problem is I want to inject this 'connectoauth2' to my UserEducation Service to getIdentity in So I did in Factory as
$connectDb = $services->get('connectDb');
$connectOAuth2 = $services->get('connectoauth2'); // --> service is not found
$service = new \ConnectApp\Service\UserEducation($connectDb, $connectOAuth2);
return new UserEducationResource($service);
ERROR: Unable to resolve service "connectoauth2" to a factory; are you certain you provided it during configuration?
Even authentication is working fine but Still I can't get Service as i did for database.
Please help!
Thanks!

Are you sure that $services is the service manager? If it is another service locator instance (for example a ControllerManager or ViewHelperManager and not the service manager) you will first have to get the service manager from that service locator:
$serviceManager = $services->getServiceLocator();
and then your service from the service manager:
$service = $serviceManager->get('connectoauth2');
Check for an overview of all the other service locators also here

That is just Authentication Adapter not Authentication Service. So if you need to retrieve identity from Authentication, you should using Authentication Service. In Zend Framework, you can call Authentication Service like this
$authentication = $serviceManager->get('authentication');
And retrieve the identity like this.
$authentication->getIdentity()

Related

Azure Cloud Service - Configure Session from RoleEnvironment

Our application is hosted as a Cloud Service in Azure and we have all our connection strings and other connection-like settings defined in the ServiceConfiguration files. We are also using a Redis Cache as the session state store. We are trying to specify the Redis Cache host and access key in the ServiceConfig and then use those values for the deployment depending on where the bits land. The problem is session is defined in the web.config and we can't pull RoleEnvironment settings into the web.config.
We tried altering the web.config in the Application_Startup method but get errors that access is denied to the web.config on startup, which makes sense.
We don't really want to write deployment scripts to give the Network Service user access to the web.config.
Is there a way to setup session to use a different Redis Cache at runtime of the application?
The error that we are getting is "Access to the path 'E:\sitesroot\0\web.config' is denied'. I read an article that gave some examples on how to give the Network Service user access to the web.config as part of the role starting process and did that and then now we have access to the file but now get the following error "Unable to save config to file 'E:\sitesroot\0\web.config'."
We ended up being able to solve this using the ServerManager API in the WebRole.OnStart method. We did something like this:
using (var server = new ServerManager())
{
try
{
Site site = server.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_Web"];
string physicalPath = site.Applications["/"].VirtualDirectories["/"].PhysicalPath;
string webConfigPath = Path.Combine(physicalPath, "web.config");
var doc = System.Xml.Linq.XDocument.Load(webConfigPath);
var redisCacheProviderSettings = doc.Descendants("sessionState").Single().Descendants("providers").Single().Descendants("add").Single();
redisCacheProviderSettings.SetAttributeValue("host", RoleEnvironment.GetConfigurationSettingValue("SessionRedisCacheHost"));
redisCacheProviderSettings.SetAttributeValue("accessKey", RoleEnvironment.GetConfigurationSettingValue("SessionRedisCacheAccessKey"));
redisCacheProviderSettings.SetAttributeValue("ssl", "true");
redisCacheProviderSettings.SetAttributeValue("throwOnError", "false");
doc.Save(webConfigPath);
}
catch (Exception ex)
{
// Log error
}
}

RemoteTokenService for multiple client application

How can I use RemoteTokenService for more than one client application (with different client_id and secret )?
UPDATE
public ResourceServerTokenServices tokenService() {
RemoteTokenServices tokenServices = new RemoteTokenServices();
tokenServices.setClientId("sample_test_client_app_auth_code");
tokenServices.setClientSecret("secret");
tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
return tokenServices;
}
That's how we configure instance of RemoteTokenService. and inject it to the OAuth2AuthenticationManager for separate Resource server and auth server. Is it correct?
so when some other client has to access this resource how can I configure RemoteTokenService for both of this client.can you provide some light on this. and tell me if I am wrong on something.
The client id in the RemoteTokenServices is not the client that is consuming the resource, it's the client associated with the resource itself (solely for the purpose of authentication of the /check_token endpoint). So once you have it working you can hit that resource from as many clients as you like.

Adding a service reference to a breeze odata service

Is it possible to consume an OData service (implemented using .Net MVC) with Breeze controllers?
I tried adding a Service Reference from a client aplication, but it simply cannot find a service endpoint when I use Breeze controller on the service.
Any help will be appreciated.
Yes, on the server you will need to create a WCF DataService, something like this:
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class ODataService : DataService<Your_EF_DbContext> {
// Add your Entity Set names here ... for example
config.SetEntitySetAccessRule("Customers", EntitySetRights.All);
config.SetEntitySetAccessRule("Orders", EntitySetRights.All);
config.SetEntitySetAccessRule("Employees", EntitySetRights.All);
// V3 supported in our next release as well.
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
config.UseVerboseErrors = true;
}
Then from the Breeze client you will need to call
breeze.config.initializeAdapterInstance("dataService", "OData");
to initialize Breeze's OData handling. Then you create an EntityManager and connect to your service. Something like this:
var myEntityManager = new breeze.EntityManager("http://localhost:9009/ODataService.svc");
You can now query and save from your data service via the EntityManager.

Web Service client generated by wsdl not working with Deployed web service

I have generated a WSDL from a java class using axis2 java2wsdl utility as follows;
java2wsdl -o C:\temp -cn com.temenos.webservices.customer.CustomerServiceWS
Then I have deployed the same web service within an Application Server (say jBoss) in axis2 and I can browse the wsdl on http:// 127.0.0.1:8080/axis2/services/CustomerServiceWS?wsdl and call the methods on this service via standard client like SoapUI etc.
The problem is now that when I generated a client using standard java tooling 'wsimport' by providing a WSDL location as C:\temp (Generated WSDL from java2wsdl utility), my client is unable to communicate with the Deployed Web Service. I am using following code to access the web service;
// Initialise WS
CustomerServiceWS service = null;
CustomerServiceWSPortType servicePort = null;
try {
URL wsdlLocation = new URL("http://127.0.0.1:8080/axis2/services/CustomerServiceWS?wsdl");
QName serviceName = new QName("http://customer.webservices.temenos.com", "CustomerServiceWS");
service = new CustomerServiceWS(wsdlLocation, serviceName);
servicePort = service.getCustomerServiceWSHttpSoap12Endpoint();
} catch (MalformedURLException murle) {
murle.printStackTrace();
return;
}
But while creating an (service Port) Endpoint I am getting following error;
Exception in thread "main" javax.xml.ws.WebServiceException: An attempt was made to construct the ServiceDelegate object with an service name that is not valid: {http://customer.webservices.temenos.com}CustomerServiceWS.
at org.apache.axis2.jaxws.ExceptionFactory.createWebServiceException(ExceptionFactory.java:173)
at org.apache.axis2.jaxws.ExceptionFactory.makeWebServiceException(ExceptionFactory.java:70)
at org.apache.axis2.jaxws.ExceptionFactory.makeWebServiceException(ExceptionFactory.java:118)
at org.apache.axis2.jaxws.spi.ServiceDelegate.<init>(ServiceDelegate.java:218)
at org.apache.axis2.jaxws.spi.Provider.createServiceDelegate(Provider.java:59)
at javax.xml.ws.Service.<init>(Service.java:56)
at com.temenos.webservices.customer.CustomerServiceWS.<init>(CustomerServiceWS.java:42)
at com.temenos.services.customer.client.Client.testGetLanguage(Client.java:32)
at com.temenos.services.customer.client.Client.main(Client.java:21)
I have tried many things but it does not seems to like anything. Am I missing anything?
Thanks,
--
SJunejo
The problem was that I had axis2 in lib path because of that the call happend to org.apache.axis2.jaxws.spi.Provider.createServiceDelegate (Axi2 Provider) instead of Java WS Provider. I removed the axis2 libs from classpath and it seems to be working ok now. (though I am still unable to call my web service via client)
See the description of WSDL file and check the targetNamespace for the url to be given in QName(). Also import necessary packages.

Need to pass additional value to UserNameSecurityToken in STS from client application

I have incorporate security into my wcf service using wif. Below my high level design.
Wif sts application - Here i have used custom username security token handler for validate the usename & passsword
Wcf service - list of services
Web application -> where i consumed the wcf service.
STS custom username security token handler as follows:
public class CustomUserNameSecurityTokenHandler : UserNameSecurityTokenHandler
{
public override Microsoft.IdentityModel.Claims.ClaimsIdentityCollection ValidateToken(System.IdentityModel.Tokens.SecurityToken token)
{
UserNameSecurityToken userNameToken = token as UserNameSecurityToken;
CredentialStore.AuthenticateUser(userNameToken.username, userNameToken.Password);
// ...
}
}
Code to consume the wcf service from web application
ClientCredentials oldCredentials = client.Endpoint.Behaviors.Remove<ClientCredentials>();
CachedClientCredentials newCredentials = new CachedClientCredentials(_tokenCache, oldCredentials);
client.Endpoint.Behaviors.Add(newCredentials);
client.ClientCredentials.UserName.UserName = "Admin"
client.ClientCredentials.UserName.Password = "password";
client.Authenticate();
While consume the wcf service i am able to send the username and password to STS validateToken method for authenticate and my scenario is like i want to send one more value (current web site address) to validatetoken method from consume part. i have workaround to send the additional value part of username but that is not the good idea to do that.
So could you please help me to resolve my issue?
An STS service that I have implemented requires a ClientID in addition to the username and password. I've solved this problem by adding custom elements into the security token request when initialising the service client. The STS service then reads out these values whilst authorizing the token and also passes back the ClientID in the claims.
// init client..
_serviceClient.ClientCredentials.UserName.UserName = Username;
_serviceClient.ClientCredentials.UserName.Password = Password;
var doc = new XmlDocument();
XmlElement customElement = doc.CreateElement("ExtraAuthData", Name, "http://localhost/STS/identity");
customElement.InnerText = Value;
(_serviceClient.Endpoint.Binding as WS2007FederationHttpBinding).Security.Message.TokenRequestParameters.Add(customElement);
Not sure if this is a recommended approach or not, I couldn't find any other way of doing this.

Resources