Problems with Oracle Membership Provider and Framework 4 - web-services

I'm having serious problems with creating a Web service in Visual Studio 2010 (Framework 4).
Anyway, I have to use a Oracle membership provider (I have installed "Oracle Providers for ASP.NET 4 11.2.0.2.0', which modifies the framework's machine.config), but I can not connect to the membership.
My code in web.config is as follows:
<configuration>
<connectionStrings>
<remove name="OraAspNetConString"></remove>
<add name="OraAspNetConString" connectionString="User Id=USUARIO;Password=PASSWORD;Data Source=DATABASENAME;" providerName="Oracle.DataAcces.Client"/>
</connectionStrings>
<system.web>
<membership defaultProvider="OracleMembershipProvider" userIsOnlineTimeWindow="30"/>
<roleManager defaultProvider="OracleRoleProvider" enabled="true" cacheRolesInCookie="true" cookieName=".ASPROLES" cookieTimeout="30" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="All"/>
<authentication mode="None"/>
<authorization>
<allow users="*"/>
</authorization>
I also added the reference 'System.Web.ApplicationServices' to my project.
To test the connection to the membership of Oracle I have put this code in one of the OperationContract that has my web service:
MembershipUserCollection userC = Membership.GetAllUsers();
sample.StringValue += " - " + userC.Count;
bool resp = Membership.ValidateUser(id, id2);
The obtained MembershipUserCollection always appears without users. UserC.Count always equals zero.
The parameters 'id' and 'id2', username and password respectively, are used to validate (that is a poor use, I know) but always returns false.
Anybody can help me with this?
Thanks a lot.
PD: Authentication mode is 'None', I've tried with 'Forms' and still not working.

Problem solved.
I needed to put the name of the application (applicationName) on the label of the membership and role manager providers (in the file machine.config).
:-)

Related

Spring 4 REST web-services not working with security

I am using Spring 4, with Spring Security 4 to secure web-services. A normal web-service worked fine without security. My secured web-services also seemed to work great working locally and with unit testing.
We are using the SiteMinder example, which means we have authentication happenind from a remote authority. This delivers a token to the browser when we login. We pass the authentication token with a request header, and this is pulled from customerUserDetailsService. That class and methods pull the token from the header, authenticates the user against that remote authority, and we get a username. From that username, we make a DAO call to our database to get the User Details and their Roles, which in the Spring Security Context uses the roles to grant authority. This is all working fine, and we get an authenticated user and we have thier roles/grantedAuthorities.
So, as previously stated, we are now just securing web-services with spring-security.xml to secure the web-services based on the role of the user. Again, this all seemed to work fine with unit testing. We had a token for a user who did not have access to web-sites and we correctly got back a 403 error. When we used a token for a user who did have the right role, was able to execute the web-service.
Now I am trying to deploy this into a new environment, and I am not having much luck.
So, I have a spring-security.xml that looks like:
<http use-expressions="true" auto-config="false" entry-point-ref="http403EntryPoint">
<!-- Additional http configuration omitted -->
<intercept-url pattern="/records/authorizedRecords" access="hasRole('portalUser')" />
<intercept-url pattern="/records/myCode" access="hasRole('portalUser')" />
<intercept-url pattern="/users/email" access="hasRole('appAdmin')" />
<custom-filter position="PRE_AUTH_FILTER" ref="openAmFilter" />
</http>
<beans:bean id="openAmFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<beans:property name="principalRequestHeader" value="openam_token"/>
<beans:property name="authenticationManager" ref="authenticationManager" />
</beans:bean>
<beans:bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<beans:property name="preAuthenticatedUserDetailsService">
<beans:bean id="userDetailsServiceWrapper" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<beans:property name="userDetailsService" ref="customUserDetailsService"/>
</beans:bean>
</beans:property>
</beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="preauthAuthProvider" />
</authentication-manager>
<beans:bean id="customUserDetailsService" class="com.agmednet.server.security.CustomUserDetailsService"></beans:bean>
<beans:bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint">
When we tried access to:
<intercept-url pattern="/users/email/*" access="hasRole('appAdmin')" />
this did not seem to match:
/rest/users/email/myemail#someemail.com
so I changed it to:
<intercept-url pattern="/rest/users/email/*" access="hasRole('appAdmin')" />
And I get this from the log.
DEBUG: org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/rest/trials/integratedtrials'; against '/rest/users/email/*'
DEBUG: org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Public object - authentication not attempted
DEBUG: org.springframework.security.web.FilterChainProxy - /rest/trials/integratedTrials reached end of additional filter chain; proceeding with original chain
DEBUG: org.springframework.security.web.access.ExceptionTranslationFilter - Chain processed normally
DEBUG: org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
At this point, I know we have an authenticated user, the username, and the roles are listed right there in the logs. We seem to find a matching URL in the spring-security.xml, the URL matches, the roles match, and now I feel we should be executing the logic behind the web-service, but I get an error message:
Apache Tomcat/8.0.30 - Error report
/services/rest/users/email/myemail#someemail.com
The requested resource is not available.
I am absolutely floored here .... unsecured web-services work great. I have to be missing something? Is it with the word "rest" in the URL? Web-services have always worked when they were unsecured. I added security and add unit tests to test this all out, and now I am unsure of what happened?
The problem is that I am an idiot!!!!
In the /WEB-INF/web.xml file I had this defined:
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
I suppose that is why when I call any RESTful web-services with:
/rest/users/email/myemail#someemail.com
it doesn't work.
But when I use:
/api/users/email/myemail#someemail.com
now it works.
Conclusion: I am an idiot!!!

MVC 5 + ASP Identity authorization - sharing cookie in subdomains

I have local website with subdomains like:
localhost:55307
aaa.localhost:55307
bbb.localhost:55307
It works perfectly except authorization - if I log in in localhost:55307 I'm not logged in aaa.localhost:55307 because my subdomains are treated as separate domain. I looking for solution but I can't find any for Asp Identity (Form authentication in MVC 4 it's useless).
Based on some questions and answers in SO I did:
Edit CookieAuthenticationOptions class in Startup.Auth.cs as below:
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
CookieDomain = ".localhost",
ExpireTimeSpan = new TimeSpan(0,12,0,0,0),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
Get MachineKey from IIS Manager and add to web.config:
<system.web>
<authentication mode="None" />
<machineKey validationKey="61D42DE996486DEA64CEA26C0373C547E0D07108789662C2D2E15210A65C475925055009D962FEB3D5D93E9BEA3E3717187F1BCBF63E386EB198F641E6157044" decryptionKey="06CF7C1C31BDBD4E7056D0F3531BE253E98A658B50974155" validation="SHA1" decryption="Auto"/>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" maxRequestLength="1073741824" />
</system.web>
Now i can login but cookies aren't shared - I still logged in one subdomain.
PS. I now that there is a lot of similar questions in StackOberflow but no one of them is about MVC 5 and ASP Identity and no of them got solutions.

JaxWS : Externalize Http Conduit name Attribute

I have the WSDL file for the SOAP webservice that i need to invoke over http. Using cxf wsdl2java plugin i have created the stub methods.
I have created the webservice client using jaxws. The webservice has basic authentication enabled. I am trying to configure http conduit
my application.properties
--------------------------
webservices.http.auth.username=username
webservices.http.auth.password=password
fold.webservices.http.auth.authtype=Basic
webservices.http.conduit.property.name=https://fixed_deposits-test.co.in/fold-webservices/services.*
fold.updateservice.soap.address=https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService
----------------------------
My Spring Context...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"
xmlns:sec="http://cxf.apache.org/configuration/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<bean id="properties" class="org.apache.camel.spring.spi.BridgePropertyPlaceholderConfigurer">
<property name="locations">
<util:list>
<value>file:${config.dir}/application.properties</value>
</util:list>
</property>
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<jaxws:client id="updateServiceClient" serviceClass="com.fold.facade.v1.UpdateService" address="${fold.updateservice.soap.address}" >
<jaxws:inInterceptors>
<bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" >
<property name="prettyLogging" value="true" />
</bean>
</jaxws:inInterceptors>
<jaxws:outInterceptors>
<bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" >
<property name="prettyLogging" value="true" />
</bean>
</jaxws:outInterceptors>
</jaxws:client>
<http-conf:conduit name="***?????????***">
<http-conf:authorization>
<sec:UserName>${fold.webservices.http.auth.username}</sec:UserName>
<sec:Password>${fold.webservices.http.auth.password}</sec:Password>
<sec:AuthorizationType>${fold.webservices.http.auth.authtype}</sec:AuthorizationType>
</http-conf:authorization>
</http-conf:conduit>
I have done a lot of searching online so as to what should be the valid value for name attribute..
accouring to CXF documentation it should be...
{WSDL_endpoint_target_namespace}PortName.http-conduit
my WSDL File has..
...
targetNamespace="http://facade.fold.com/" and
...
<wsdl:port binding="tns:UpdateServiceImplServiceSoapBinding"
name="UpdateServiceImplPort">
<soap:address
location="https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService" />
</wsdl:port>
so i tried with these..
<http-conf:conduit name="{http://facade.fold.com/}UpdateServiceImplPort.http_conduit">
or
<http-conf:conduit name="*UpdateServiceImplPort.http_conduit">
or
<http-conf:conduit name="{http://facade.fold.com/}*.http_conduit">
But none of them work as i get 401 unauthorized exception..
org.apache.cxf.transport.http.HTTPException: HTTP response '401: Unauthorized' when communicating with https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService
THERE ARE COUPLE OF WAYS I GOT IT TO WORK
a) <http-conf:conduit name="*.http_conduit">
but i really don't want to do it this way...
b) <http-conf:conduit name="https://fixed_deposits-test.co.in/fold-webservices/services/UpdateService">
this is hardcoding the SOAP service URL... which i don't want as i am looking for externalizing URL as my SOAP URL's are different for different environment..(dev /test /prod etc)
Below is my best shot at externalization, but it failed with 401 Unauthorized Exception...
properties were replaced in all other instances in my spring context, but not for http-conf:conduit name attribute :(
<http-conf:conduit name="${webservices.http.conduit.property.name}">
As a workaround i am currently using the regex approach which works..
<http-conf:conduit name="*.*/fold-webservices/services/UpdateService">
But i really want to figure out if it possible to externalize it and read from properties file. And i want to do it the Spring
configuration way. Please help me !!!
We had the same issue with JBoss Fuse 6.1 (Camel CXF 2.12.0).
You can see what the http-conf:conduit name is set to by enabling DEBUG log level and looking at your log, there should be a log line such as:
DEBUG 10:40:41,437 [Camel (cnpms-as-mnp-ctx) thread #0 - JmsConsumer[cnpms-queue]] org.apache.cxf.transport.http.HTTPConduit.setTlsClientParameters(HTTPConduit.java:901) - Conduit '{http://acme.com/manageporting/v1}ManageportingPortPort.http-conduit' has been (re)configured for plain http.
So in this case you would set the name as:
<http-conf:conduit name="{http://acme.com/manageporting/v1}ManageportingPortPort.http-conduit"
But the Web Service (WS) Interface Class is defined as:
#WebService(targetNamespace = "http://acme.com/manageporting/v1", name = "ManageportingPort")
#SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface ManageportingPort {
Generated from WSDL:
<wsdl:portType name="ManageportingPort">
Note that by following the CXF documentation you would expect the port name component to be "ManageportingPort" NOT "ManageportingPortPort" i.e. with "Port" appended to it.
However looking at how the portQName is resolved in org.apache.cxf.jaxws.support.JaxWsImplementorInfo.getEndpointName(), if the port name is not set in the WS Interface Class, and the name is not null or blank, it sets the port name to portName = name + "Port" otherwise it sets it to portName = implementorClass.getSimpleName() + "Port".
I had the same problem...
In my case the following 2 changes helped:
1) add "Port" postfix to the port name, despite it is not defined in the wsdl this was
e.g wsdl:
<wsdl:port name="XXXSoap">
will be "XXXSoapPort" in the conduit definition
2) remove the "\" at the end of the target namespace name
==> therefore try
<http-conf:conduit name="{http://facade.fold.com}UpdateServiceImplPort.http_conduit">
or
<http-conf:conduit name="{http://facade.fold.com}UpdateServiceImplPortPort.http_conduit">
I came across the same challenge and found no existing solution. Spring doesn't seem to resolve placeholders in bean names (make lots of sense). However, this is a valid case unless cxf allows conduit matching using another attribute.
There are a few ways to solve this problem:
Define conduit beans programmatically (lose the neat of xml declaration)
Find a way to resolve the bean names which contains placeholders
I prefer option 1 and this is the implementation which I'm happy with. Please note that PropertyPlaceholderResolver is our own utility which uses the same defined resolver bean.
public class NameWithPlaceholderBeanFactoryPostProcessor implements BeanFactoryPostProcessor
{
#Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException
{
if (!(beanFactory instanceof DefaultListableBeanFactory))
return;
DefaultListableBeanFactory bf = (DefaultListableBeanFactory) beanFactory;
String[] names = bf.getBeanDefinitionNames();
for (String name : names)
{
if (name.indexOf('$') < 0)
continue;
BeanDefinition bd = bf.getBeanDefinition(name);
bf.removeBeanDefinition(name);
bf.registerBeanDefinition(PropertyPlaceholderResolver.resolvePlaceHolders(name), bd);
}
}
}
The final step is to define this as a spring bean.

Integrated Windows Security when calling an ASMX service

I have some issues with an ASMX web service running on Win XP with IIS 5.1. The IIS is set up with Integrated Windows Authentication and with anonymous access disabled. (When I have anonymous access enabled, everything works as a charm.)
However, when I turn of anonymous access and run with only Integrated Windows Authentication on my IIS, I get the following exception:
The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'Negotiate,NTLM'.
This exception is generated from my really simple console application that I'm using just to test the concept:
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; // .None;
binding.UseDefaultWebProxy = false;
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("WORKGROUP/VirtualXP-91051");
Uri uri = new Uri("http://169.254.91.91/MyWebSite/MyService.asmx");
EndpointAddress address = new EndpointAddress(uri, spn);
MyServiceSoapClient client = new MyServiceSoapClient(binding, address);
client.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
String req = "( the request string is blanked out.. ;) )";
string resp = client.ReqAddressData(req);
Console.WriteLine(resp);
Console.ReadLine();
The interesting part of App.config:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
This isn't rocket science, so I must be missing something obvious. I've done some searching here on SO, and eve though I can find many similar questions I've found nothing that solved my problem.

Trouble with SOAP request from Flex

SUM: I ended up having to form the XML manually. I also had to create an Operation and use its send(); method rather than just doing something like WebService.MyServiceFunction(); - not sure why that was the case.
I send off the request as follows:
var xm:XML =
<SetPropertiesForCurrentUser xmlns="http://asp.net/ApplicationServices/v200">
<values xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<d4p1:KeyValueOfstringanyType>
<d4p1:Key>{obj.Key}</d4p1:Key>
<d4p1:Value xmlns:d6p1="http://www.w3.org/2001/XMLSchema" i:type="d6p1:string">{obj.Value}</d4p1:Value>
</d4p1:KeyValueOfstringanyType>
</values>
</SetPropertiesForCurrentUser>;
var profileService:WebService = new WebService();
profileService.useProxy = false;
profileService.loadWSDL(url);
var o:Operation = profileService.SetPropertiesForCurrentUser;
o.send(xm);
Here’s my scenario:
I have ASP.NET web services to handle authentication, user roles, and user profiles (default ASP.NET AuthenticationService, RoleService, and ProfileService, to be exact).
So from my Flex web app, I am able to successfully call the ASP.NET service. For example, something like this works fine:
var profileService:WebService = new WebService();
profileService.useProxy = false;
profileService.GetAllPropertiesForCurrentUser.addEventListener("result",getAllPropertiesForCurrentUser_EventHandler);
profileService.addEventListener("fault",getAllPropertiesForCurrentUserFault_EventHandler);
profileService.loadWSDL(url);
profileService.GetAllPropertiesForCurrentUser();
I run into trouble when I need to pass a Dictionary object to another function on the service (SetPropertiesForCurrentUser). The .NET service asks for this type of value:
System.Collections.Generic.IDictionary(Of String, Object)
Here are the two pertinent entries from the web.config entry from my ASP.NET service:
<properties>
<clear/>
<add name="coordinateFormat" />
</properties>
...
<profileService enabled="true"
readAccessProperties="coordinateFormat"
writeAccessProperties="coordinateFormat"/>
So after putting together a SOAP request from a Silverlight app (which works as expected) I’ve narrowed it down to a difference in the XML request sent to the SOAP handler:
From Flex:
<tns:Value>DMS</tns:Value>
From Silverlight:
<d4p1:Value xmlns:d6p1="http://www.w3.org/2001/XMLSchema" i:type="d6p1:string">DMS</d4p1:Value>
If I take the request generated by Flex, catch it with Fiddler, modify that one line to include the “type” namespace – it works.
Anyone have an idea how I can get that namespace onto my variable that is passed to the SOAP handler from Actionscript? Here is my code for sending off that SetPropertiesForCurrentUser function:
var obj:Object = {};
obj["Key"] = "coordinateFormat";
obj["Value"] = DMS;
var profileService:WebService = new WebService();
profileService.useProxy = false;
profileService.SetPropertiesForCurrentUser.addEventListener("result",setPropertiesForCurrentUser_EventHandler);
profileService.addEventListener("fault",setPropertiesForCurrentUserFault_EventHandler);
profileService.loadWSDL(url);
profileService.SetPropertiesForCurrentUser(new ArrayCollection([obj]),false);
Thanks,
Josh
The default SOAPEncoder that is used is some what limited in its capabilities (like not including the type attribute you mentioned above). Luckily, there is a way to control that by writing your own encoder.
see this link at adobe (read part about using custom web service serialization) Link on Adobe's Site