In my WCF service implementation I used username/password for authentication, with ASP.NET Identity 2.0 and with the following codes.
public class IdentityValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
Debug.WriteLine("Validate "+userName);
using (var context = new ApplicationDbContext())
using (var userStore = new UserStore<ApplicationUser>(context))
using (var userManager = new UserManager<ApplicationUser>(userStore))
{
var user = userManager.Find(userName, password);
if (user == null)
{
var msg = String.Format("Unknown Username {0} or incorrect password {1}", userName, password);
Trace.TraceWarning(msg);
throw new FaultException(msg);//the client actually will receive MessageSecurityException. But if I throw MessageSecurityException, the runtime will give FaultException to client without clear message.
}
}
Debug.WriteLine("End validate " + userName);
}
}
and the config is like
<behavior name="authBehavior">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="IdentityValidator,Security" />
</serviceCredentials>
<serviceAuthorization principalPermissionMode="Custom" serviceAuthorizationManagerType="RoleAuthorizationManager,Security"></serviceAuthorization>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
The functionality of authentication is so far so good. And the client is typically a Windows desktop app that will persist the user name and password all the time.
I understand the WCF authentication is per message. That means each call will run though some SQL queries against the database that stores the user name and password hash. So far in my low traffic test, the performance is good enough, say the authentication could be done within 1 second.
However, under heavy traffic, I wonder if it is a good idea to cache the result of querying the database, for example, before running userManager.Find, check if the userName and password pair had been authenticated in MemoryCache with 10 minutes expiry.
Is this something micro performance optimization? or in your experiences, did you need to be concerned by the performance of authentication of WCF services, built-in or custom?
Related
I can't get my values stored in the WCF session when use WS2007FederationHttpBinding. I've seen this topic Session in WCF not consistent, but it didn't help. Moreover, I don't care about reliable session, I just want to store some info in the session and read it at the second request. This scheme works for me with basicHttpsBinding.
Here is my binding. After channel creation I store it to the client Session
var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
binding.Security.Message.EstablishSecurityContext = true;
binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;
binding.MaxReceivedMessageSize = 4000000;
var serviceFactory = new ChannelFactory<T>(binding, new EndpointAddress(serviceUrl));
serviceFactory.Credentials.SupportInteractive = false;
var channel = serviceFactory.CreateChannelWithIssuedToken(token);
Service configuration:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
Session access in the service:
HttpContext.Current.Session["serviceSession"] = "123";
Session retrieval in the service (is always null on the second request but SessionId is the same):
if (HttpContext.Current.Session["serviceSession"] == null) ...
I keep the channel itself in the client session between two requests and reuse it taking from the session for the second request.
Session["clientSession"] = channel;
I beleive HttpContext.Current.Session will only work if you configre asp comptability mode on the service. But even then it will not be correlated with your federation setting. What worked for me is to define the service instance mode as per session:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service : IService
and then you can use local data members of the service class to persist data between different calls of the same session.
I would like to host a REST-full WCF 4.0 service on an already-created IIS 7.5 website based on ASP.NET v4.0 and secured by forms authentication. So, I tried to configure my WCF stack using mixed mode authentication (aspNetCompatibilityEnabled="false") and configured the service host to use no security at all but So long, all my efforts was completely unsuccessful. When I try to call my service from the browser after a while the connection to the host is closed without a response and my browser raises an error indicating the connection to the target webstie is closed without any response.
However, if I write a dummy code in Application_BeginRequest to authenticate a dummy user in forms authentication module using FormsAuthentication.Authenticate or call the service in an authenticated browser session everything works fine and the service is called successfully.
I tried to find the problem causing this strange behavior using WCF tracing. What I have found from the resulting svclog file is this exception:
Message: Object reference not set to an instance of an object.
StackTrace:
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.get_LogonUserIdentity()
System.ServiceModel.Channels.HttpChannelListener.ValidateAuthentication(IHttpAuthenticationContext authenticationContext)
System.ServiceModel.Channels.HttpRequestContext.ProcessAuthentication()
System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceived(HttpRequestContext context, Action callback)
Any idea about the problem?
UPDATE: I even set the authentication mode of the website to "None" and authorized anonymous users. Still the same results. Nothing changed. The question is that can I use unauthenticated WCF RESTfull services with aspNetCompatibilityEnabled="false" on an ASP.NET website at all???
To be more specific, What I have tried to do is:
Implemented my WCF service in the form of a .svc file
Configured WCF in my web.config file as the following (note AspNetCompatibilityEnabled="false"):
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="false" />
</system.serviceModel>
Created and used my own ServiceHostFactory like this:
public class MyServiceHostFactory : ServiceHostFactoryBase
{
#region Methods
public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
{
var type = Type.GetType(constructorString);
var host = new WebServiceHost(type, baseAddresses);
var serviceBehavior = host.Description.Behaviors.OfType<ServiceBehaviorAttribute>().Single();
serviceBehavior.ConcurrencyMode = ConcurrencyMode.Multiple;
serviceBehavior.MaxItemsInObjectGraph = int.MaxValue;
var metadataBehavior = host.Description.Behaviors.OfType<ServiceMetadataBehavior>().SingleOrDefault();
if (metadataBehavior == null)
{
metadataBehavior = new ServiceMetadataBehavior();
host.Description.Behaviors.Add(metadataBehavior);
}
var debugBehavior = host.Description.Behaviors.OfType<ServiceDebugBehavior>().SingleOrDefault();
if (debugBehavior == null)
{
debugBehavior = new ServiceDebugBehavior();
host.Description.Behaviors.Add(debugBehavior);
}
metadataBehavior.HttpGetEnabled = true;
debugBehavior.IncludeExceptionDetailInFaults = true;
var binding = new WebHttpBinding { MaxBufferPoolSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue };
binding.Security.Mode = WebHttpSecurityMode.None;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
WebHttpBehavior webHttpBehavior = new WebHttpBehavior { HelpEnabled = true };
foreach (var contract in type.GetInterfaces().Where(i => i.GetCustomAttributes(typeof(ServiceContractAttribute), true).Length > 0))
{
var endpoint = host.AddServiceEndpoint(contract, binding, "");
endpoint.Behaviors.Add(webHttpBehavior);
}
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
return host;
}
#endregion
}
I am working on a asp.net web application that has is a part of TFS and is used by the development team. Recently as part of the project we setup ADFS and are now attempting to enforce authentication of the project to an ADFS server.
On my development machine I have gone through the steps of adding STS reference which generates the Federation Meta-Data as well as updates the web.config file for the project. Authorization within the web.config uses thumbprint certification which requires me to add to my local machine the ADFS certificate as well as generate a signed certificate for the dev machine and add this to ADFS.
All is setup and working but in looking at the web.config. and FederationMetadata.xml document these "appear" to be machine specific. I suspect that if I check the project/files into TFS the next developer or tester that takes a build will end up with a broken build on their machine.
My question is within TFS what is the process for a scenario like this to check in and still allow my team to check out, build, and test the project with the latest code in their development or test environments?
My work around at this time is to exclude the FederationMetaData.xml and web.config from check in then on each development machine manually setup ADFS authentication as well as for product test. Once done each person can prevent their local copy of the FederationMetatData.xml and web.config from being checked in.(aka have their own local copy) then when checking in/out just ensure that each developer preserves their own copy (or does not check them into TFS)
This seems extremely inefficient, and all but bypasses the essence of source code management as developers are being required to keep local copies of files on their machine. This also seems to introduce the opportunity for accidental check-in of local files or overwriting local files.
Does anyone have any references, documentation or information on how to check-in code for (ADFS) machine specific configurations and not hose up the entire development environment?
Thanks in advance,
I agree that the way that the WIF toolset does configuration is not great for working in teams with multiple developers and test environments. The approach that I've taken to get past this is to change WIF to be configured at runtime.
One approach you can take is to put a dummy /FederationMetadata/2007-06/FederationMetadata.xml in place and check that in to TFS. It must have valid urls and be otherwise a valid file.
Additionally, you will need a valid federationAuthentication section in web.config with dummy (but of valid form) audienceUris, issuer and realm entries.
<microsoft.identityModel>
<service>
<audienceUris>
<add value="https://yourwebsite.com/" />
</audienceUris>
<federatedAuthentication>
<wsFederation passiveRedirectEnabled="true" issuer="https://yourissuer/v2/wsfederation" realm="https://yourwebsite.com/" requireHttps="true" />
<cookieHandler requireSsl="false" />
</federatedAuthentication>
etc...
Then, change your application's ADFS configuration to be completely runtime driven. You can do this by hooking into various events during the ADFS module startup and ASP.NET pipeline.
Take a look at this forums post for more information.
Essentially, you'll want to have something like this in global.asax.cs. This is some code that I've used on a Windows Azure Web Role to read from ServiceConfiguration.cscfg (which is changeable at deploy/runtime in the Azure model). It could easily be adapted to read from web.config or any other configuration system of your choosing (e.g. database).
protected void Application_Start(object sender, EventArgs e)
{
FederatedAuthentication.ServiceConfigurationCreated += OnServiceConfigurationCreated;
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
/// Due to the way the ASP.Net pipeline works, the only way to change
/// configurations inside federatedAuthentication (which are configurations on the http modules)
/// is to catch another event, which is raised everytime a request comes in.
ConfigureWSFederation();
}
/// <summary>
/// Dynamically load WIF configuration so that it can live in ServiceConfiguration.cscfg instead of Web.config
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
void OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs eventArgs)
{
try
{
ServiceConfiguration serviceConfiguration = eventArgs.ServiceConfiguration;
if (!String.IsNullOrEmpty(RoleEnvironment.GetConfigurationSettingValue("FedAuthAudienceUri")))
{
serviceConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(RoleEnvironment.GetConfigurationSettingValue("FedAuthAudienceUri")));
Trace.TraceInformation("ServiceConfiguration: AllowedAudienceUris = {0}", serviceConfiguration.AudienceRestriction.AllowedAudienceUris[0]);
}
serviceConfiguration.CertificateValidationMode = X509CertificateValidationMode.None;
Trace.TraceInformation("ServiceConfiguration: CertificateValidationMode = {0}", serviceConfiguration.CertificateValidationMode);
// Now load the trusted issuers
if (serviceConfiguration.IssuerNameRegistry is ConfigurationBasedIssuerNameRegistry)
{
ConfigurationBasedIssuerNameRegistry issuerNameRegistry = serviceConfiguration.IssuerNameRegistry as ConfigurationBasedIssuerNameRegistry;
// Can have more than one. We don't.
issuerNameRegistry.AddTrustedIssuer(RoleEnvironment.GetConfigurationSettingValue("FedAuthTrustedIssuerThumbprint"), RoleEnvironment.GetConfigurationSettingValue("FedAuthTrustedIssuerName"));
Trace.TraceInformation("ServiceConfiguration: TrustedIssuer = {0} : {1}", RoleEnvironment.GetConfigurationSettingValue("FedAuthTrustedIssuerThumbprint"), RoleEnvironment.GetConfigurationSettingValue("FedAuthTrustedIssuerName"));
}
else
{
Trace.TraceInformation("Custom IssuerNameReistry type configured, ignoring internal settings");
}
// Configures WIF to use the RsaEncryptionCookieTransform if ServiceCertificateThumbprint is specified.
// This is only necessary on Windows Azure because DPAPI is not available.
ConfigureWifToUseRsaEncryption(serviceConfiguration);
}
catch (Exception exception)
{
Trace.TraceError("Unable to initialize the federated authentication configuration. {0}", exception.Message);
}
}
/// <summary>
/// Configures WIF to use the RsaEncryptionCookieTransform, DPAPI is not available on Windows Azure.
/// </summary>
/// <param name="requestContext"></param>
private void ConfigureWifToUseRsaEncryption(ServiceConfiguration serviceConfiguration)
{
String svcCertThumbprint = RoleEnvironment.GetConfigurationSettingValue("FedAuthServiceCertificateThumbprint");
if (!String.IsNullOrEmpty(svcCertThumbprint))
{
X509Store certificateStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
certificateStore.Open(OpenFlags.ReadOnly);
// We have to pass false as last parameter to find self-signed certs.
X509Certificate2Collection certs = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, svcCertThumbprint, false /*validOnly*/);
if (certs.Count != 0)
{
serviceConfiguration.ServiceCertificate = certs[0];
// Use the service certificate to protect the cookies that are sent to the client.
List<CookieTransform> sessionTransforms =
new List<CookieTransform>(new CookieTransform[] { new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(serviceConfiguration.ServiceCertificate)});
SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
serviceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
Trace.TraceInformation("ConfigureWifToUseRsaEncryption: Using RsaEncryptionCookieTransform for cookieTransform");
}
else
{
Trace.TraceError("Could not find service certificate in the My store on LocalMachine");
}
}
finally
{
certificateStore.Close();
}
}
}
private static void ConfigureWSFederation()
{
// Load the federatedAuthentication settings
WSFederationAuthenticationModule federatedModule = FederatedAuthentication.WSFederationAuthenticationModule as WSFederationAuthenticationModule;
if (federatedModule != null)
{
federatedModule.PassiveRedirectEnabled = true;
if (!String.IsNullOrEmpty(RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationRequireHttps")))
{
federatedModule.RequireHttps = bool.Parse(RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationRequireHttps"));
}
if (!String.IsNullOrEmpty(RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationIssuer")))
{
federatedModule.Issuer = RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationIssuer");
}
if (!String.IsNullOrEmpty(RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationRealm")))
{
federatedModule.Realm = RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationRealm");
}
CookieHandler cookieHandler = FederatedAuthentication.SessionAuthenticationModule.CookieHandler;
cookieHandler.RequireSsl = false;
}
else
{
Trace.TraceError("Unable to configure the federated module. The modules weren't loaded.");
}
}
}
This will then allow you to configure the following settings at runtime:
<Setting name="FedAuthAudienceUri" value="-- update with audience url. e.g. https://yourwebsite/ --" />
<Setting name="FedAuthWSFederationIssuer" value="-- update with WSFederation endpoint. e.g. https://yourissuer/v2/wsfederation--" />
<Setting name="FedAuthWSFederationRealm" value="-- update with WSFederation realm. e.g. https://yourwebsite/" />
<Setting name="FedAuthTrustedIssuerThumbprint" value="-- update with certificate thumbprint from ACS configuration. e.g. cb27dd190485afe0f62e470e4e3578de51d52bf4--" />
<Setting name="FedAuthTrustedIssuerName" value="-- update with issuer name. e.g. https://yourissuer/--" />
<Setting name="FedAuthServiceCertificateThumbprint" value="-- update with service certificate thumbprint. e.g. same as HTTPS thumbprint: FE95C43CD4C4F1FC6BC1CA4349C3FF60433648DB --" />
<Setting name="FedAuthWSFederationRequireHttps" value="true" />
I'm building a simple Sring MVC app. And now i'm trying to add Spring security. I've added a customUserDetailsService that uses a DAO to access a MySql database and get users.
#Transactional(readOnly = true)
public class CustomUserDetailService implements UserDetailsService {
#EJB(name = "UserDAOLocal")
UserDAOLocal dao = null;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
System.out.println("Checking if this is invoked")
UserDetails user = null;
DBUsers dbUser = dao.findUserName(username);
user = new User(dbUser.getUserName(), dbUser.getPassword(), true, true, true, true, getAuthorities(dbUser.getAccess()));
return user;
}
private GrantedAuthority[] getAuthorities(Integer access) {
GrantedAuthority[] authList = new GrantedAuthority[2];
authList[0] = new GrantedAuthorityImpl("ROLE_USER");
if (access.compareTo(1) == 0) {
authList[1] = new GrantedAuthorityImpl(("ROLE_ADMIN"));
}
return authList;
}
}
And i've added the UserDetailsService to the Spring-security.xml.
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider user-service-ref="customUserDetailsService"/>
</security:authentication-manager>
<bean id="customUserDetailsService" class="service.CustomUserDetailService"/>
I put j_spring_security_check as the action to the login form on the login.jsp page.
When i enter a valid username and a password the app always tells it's wrong. What's more is i can't find any evidence that the customUserDetailsService is running at anytime. (I used System.out.println("Checking if this is invoked") to check on the server).
What invokes the loadUserByUsername() method of the CustomUserDetailsService? When is it invoked?
How can i configure it?
(All the codes i supplied might be unnecessary :))
EDIT:
Here is the rest of the Spring-Security.xml
<security:http auto-config="true">
<security:intercept-url pattern="/AddEmployee.htm" access="ROLE_ADMIN"/>
<security:intercept-url pattern="/FireEmployee.htm" access="ROLE_ADMIN"/>
<security:intercept-url pattern="/employees.htm" access="ROLE_USER"/>
<security:form-login login-page="/login.htm"
authentication-failure-url="/login.htm?error=true"
login-processing-url="/j_spring_security_check.htm"
default-target-url="/common.htm"/>
<security:logout
invalidate-session="true"
logout-success-url="/login.htm"
logout-url="/logout.htm"/>
</security:http>
I worked around the problem by editing the authentication provider like this. I decided not use DAO, and user database. and used hard coded users inside the xml file
<security:authentication-provider>
<security:user-service>
<security:user name="sam" password="sam123" authorities="ROLE_ADMIN,ROLE_USER" />
<security:user name="pam" password="pam123" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
This works perfectly.
But i would like to know why my customUserDetailService was never used, And learn how to use it correctly.
Sharing more config. from Spring-security.xml would help(if possible)
Spring security is Designed so that your Authentication provider calls loadUserByUsername() method of the UserDetailsService which returns userDetails Object.
Process is as follows:
Task of Authentication Manager is to Authenticate the user. So it sends the user name to Authentication provider.
Authentication Provider calls loadUserByUsername() method and passes user name of type String which returns userDetails Object.
Now this userDetails object contains all necessary information for authentication, such as username, password, isEnabled etc.
Now if you want to customize userDetailsService for using your Dao you can customize it.
This is how your authentication process works.
You can refer this link for broader understanding.
I have a WCF service, hosted in IIS, which I require to impersonate the annon account.
in my Webconfig
<authentication mode="Windows"/>
<identity impersonate ="true"/>
Testing the following, with vs2008
public void ByRuleId(int ruleId)
{
try
{
string user = WindowsIdentity.GetCurrent().Name;
string name = Thread.CurrentPrincipal.Identity.Name;
........
//get the data as a string.
using (FileStream fs = File.Open(location, FileMode.Open))
using (StreamReader reader = new StreamReader(fs))
{
rawData = reader.ReadToEnd();
}
}
catch.....
}
this works. however if I add impersonation attribute
[OperationBehavior(Impersonation=ImpersonationOption.Required)]
public void ByRuleId(int ruleId)
this does not work with the error message
"Either a required impersonation level was not provided, or the provided impersonation level is invalid."
a little poking around I noticed the first way was authenticated by Kerboros and the second way just failed on authentication type
I am using the WCF client tool, to pass my credentials. this seems to be working.
Check the 'TokenImpersonationLevel' of identity of the current thread; you'll need it to be at least 'Impersonation' to perform operations on the machine that the service is running on.
Typically, if you are using a proxy client, you'll need to set the 'TokenImpersonationLevel' of the client:
http://www.devx.com/codemag/Article/33342/1763/page/4
the main goal of this was to get anon access, even tho MattK answer was a great help.
here is what i did to do so.
on the implementation of the WCF contract I added the
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class TransferFile : ITransferFile
and in the web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled ="true" />
after this i was able to impersonate the anon account