ASP.NET Universal Providers - Roleprovider does not cache roles in cookie - cookies

Ironically my role provider does not cache the roles in a cookie anymore. That was working earlier. Unfortunately i have noticed that only now, so i cannot say what causes the problem. But i think it has to do with the update to the new version 1.2 of the universal providers (released on 16th august).
My config for the roleprovider looks like:
<roleManager enabled="true" cacheRolesInCookie="true" cookieName="X_Roles"
cookiePath="/" cookieProtection="All" cookieRequireSSL="true" cookieSlidingExpiration="true" cookieTimeout="1440"
createPersistentCookie="false" domain="" maxCachedResults="25" defaultProvider="XManager_RoleProvider">
<providers>
<clear/>
<add name="XManager_RoleProvider" type="ManagersX.XManager_RoleProvider, AssemblyX"
connectionStringName="XEntities" applicationName="/" rolesTableName="Roles" roleMembershipsTableName="Users_Roles"/>
</providers>
</roleManager>
Everything is working fine with the rolemanager (loginviews, menu with sitemaptrimming etc.), but it is only not caching the roles anymore. The membership provider, sessionstate etc. are also working fine and the cookies of them are set correctly.
All properties of the static Roles-class are correctly set and everything in Httpcontext (IsSecureConnection etc.) is also correct.
The roles cookie was set earlier, but not anymore. I hope anybody can help me with my problem.
Thanks in advance.
Best Regards,
HeManNew
UPDATE:
Has nobody got the same problem or a tip for me, please?

Below are the details of the Custom Role Provider I wrote that uses proper caching and doesn't hit the database on each page load.
============= My Code-Behind file ===============
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
namespace MyProject.Providers
{
public class CustomRoleProvider : RoleProvider
{
#region Properties
private static readonly object LockObject = new object();
private int _cacheTimeoutInMinutes = 0;
#endregion
#region Overrides of RoleProvider
public override void Initialize(string name, NameValueCollection config)
{
// Set Properties
ApplicationName = config["applicationName"];
_cacheTimeoutInMinutes = Convert.ToInt32(config["cacheTimeoutInMinutes"]);
// Call base method
base.Initialize(name, config);
}
/// <summary>
/// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
/// </summary>
/// <returns>
/// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
/// </returns>
/// <param name="username">The user name to search for.</param><param name="roleName">The role to search in.</param>
public override bool IsUserInRole(string username, string roleName)
{
// Get Roles
var userRoles = GetRolesForUser(username);
// Return if exists
return userRoles.Contains(roleName);
}
/// <summary>
/// Gets a list of the roles that a specified user is in for the configured applicationName.
/// </summary>
/// <returns>
/// A string array containing the names of all the roles that the specified user is in for the configured applicationName.
/// </returns>
/// <param name="username">The user to return a list of roles for.</param>
public override string[] GetRolesForUser(string username)
{
// Return if User is not authenticated
if (!HttpContext.Current.User.Identity.IsAuthenticated) return null;
// Return if present in Cache
var cacheKey = string.format("UserRoles_{0}", username);
if (HttpRuntime.Cache[cacheKey] != null) return (string[]) HttpRuntime.Cache[cacheKey];
// Vars
var userRoles = new List<string>();
var sqlParams = new List<SqlParameter>
{
new SqlParameter("#ApplicationName", ApplicationName),
new SqlParameter("#UserName", username)
};
lock (LockObject)
{
// Run Stored Proc << Replace this block with your own Database Call Methods >>
using (IDataReader dr =
BaseDatabase.ExecuteDataReader("aspnet_UsersInRoles_GetRolesForUser", sqlParams.ToArray(),
Constants.DatabaseConnectionName) as SqlDataReader)
{
while (dr.Read())
{
userRoles.Add(dr["RoleName"].ToString());
}
}
}
// Store in Cache and expire after set minutes
HttpRuntime.Cache.Insert(cacheKey, userRoles.ToArray(), null,
DateTime.Now.AddMinutes(_cacheTimeoutInMinutes), Cache.NoSlidingExpiration);
// Return
return userRoles.ToArray();
}
/// <summary>
/// Gets or sets the name of the application to store and retrieve role information for.
/// </summary>
/// <returns>
/// The name of the application to store and retrieve role information for.
/// </returns>
public override sealed string ApplicationName { get; set; }
// I skipped the other methods as they do not apply to this scenario
#endregion
}
}
============= End of My Code-Behind file ===============
============= My Web.Config file =======================
<roleManager enabled="true" defaultProvider="CustomRoleManager">
<providers>
<clear />
<add name="SqlRoleManager" type="System.Web.Security.SqlRoleProvider" connectionStringName="AspnetDbConnection" applicationName="MyApplication"/>
<add name="CustomRoleManager" type="MyProject.Providers.CustomRoleProvider" connectionStringName="AspnetDbConnection" applicationName="MyApplication" cacheTimeoutInMinutes="30" />
</providers>
</roleManager>
============= End of My Web.Config file ================
The cache is set to expire automatically after every 30 minutes. You can modify this as you deem fit.
Cheers.

I was having the same issue, but I was able to find a MS KB article that seems to have fixed it. I installed the patch and the cookie reappeared.
http://support.microsoft.com/kb/2750147
See the section: ASP.Net Issue 4.
Hopefully that helps someone else!

Related

How do I remove this Artifact

I am using swashbuckle to document my API. When I open the swagger page, I get this item highlighted in the image. How do I get rid of it or replace it? Using v5 of the swashbuckle tooling
Here are the section.
Startup.cs - Services
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v0", new OpenApiInfo
{
Version = "v0",
Title = "LTK Manager",
Description = "Sample Description",
TermsOfService = new Uri("https://example.com/terms"),
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.IgnoreObsoleteActions();
c.IgnoreObsoleteProperties();
});
Startup.cs - Configuration
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v0/swagger.json", "LTK Manager V0 (alpha)");
c.DisplayOperationId();
});
Route Decoration
/// <summary>
/// Retrieves a parameter store value from an account/region
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Returns an Object Containing the response from the API.</response>
[HttpPost]
[Route("getParamStoreValue")]
[ProducesResponseType(200)]
public IActionResult getKey([FromBody] ParamStoreRequest req)

InvalidOperationException: Scheme already exists: Bearer

I recently resumed work on a project that had lain dormant for a year. It was using Angular on AspNet Core 1.1 and using an early version of OpenIddict 1.0. It was developed using VS2017.
I updated VS2017 to the latest release (15.7.5) but the project would not compile and when I fixed the compilation errors it wouldn't run. So eventually I bit the bullet and decided to update the project to Asp Net Core 2.1 and to use the latest version of OpenIddict. I have the project so it compiles but when it starts it gives the error in the title, namely "InvalidOperationException: Scheme already exists: Bearer"
I can't see what is wrong. I understand that somewhere a second scheme named 'Bearer' is being added, but I can't figure out where. I am enclosing below my Startup.cs in its entirety.
using AspNet.Security.OpenIdConnect.Primitives;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SIAngular.DBContexts;
using SIAngular.Models;
using SIAngular.Services;
using OpenIddict.Abstractions;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
namespace SIAngular
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
services.AddDbContext<ApplicationDbContext>(options =>
{
// Configure the context to use Microsoft SQL Server.
options.UseSqlServer(Configuration.GetConnectionString("SqlConnection"));
// Register the entity sets needed by OpenIddict.
// Note: use the generic overload if you need
// to replace the default OpenIddict entities.
options.UseOpenIddict();
});
// Register the Identity services.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
//.AddDefaultTokenProviders();
// Configure Identity to use the same JWT claims as OpenIddict instead
// of the legacy WS-Federation claims it uses by default (ClaimTypes),
// which saves you from doing the mapping in your authorization controller.
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});
services.AddOpenIddict()
// Register the OpenIddict core services.
.AddCore(options =>
{
// Configure OpenIddict to use the Entity Framework Core stores and models.
options.UseEntityFrameworkCore()
.UseDbContext<ApplicationDbContext>();
})
// Register the OpenIddict server services.
.AddServer(options =>
{
// Register the ASP.NET Core MVC services used by OpenIddict.
// Note: if you don't call this method, you won't be able to
// bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
options.UseMvc();
// Enable the token endpoint.
options .EnableTokenEndpoint("/connect/token");
options.AcceptAnonymousClients();
options.DisableScopeValidation();
// Note: the Mvc.Client sample only uses the code flow and the password flow, but you
// can enable the other flows if you need to support implicit or client credentials.
options.AllowPasswordFlow();
// Mark the "email", "profile" and "roles" scopes as supported scopes.
options.RegisterScopes(OpenIdConnectConstants.Scopes.Email,
OpenIdConnectConstants.Scopes.Profile,
OpenIddictConstants.Scopes.Roles);
// During development, you can disable the HTTPS requirement.
options.DisableHttpsRequirement();
// Note: to use JWT access tokens instead of the default
// encrypted format, the following lines are required:
//
options.UseJsonWebTokens();
options.AddEphemeralSigningKey();
})
// Register the OpenIddict validation services.
.AddValidation();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = "http://localhost:53244/";
options.Audience = "resource_server";
options.RequireHttpsMetadata = false;
//options.IncludeErrorDetails = true;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = OpenIdConnectConstants.Claims.Subject,
RoleClaimType = OpenIdConnectConstants.Claims.Role
};
});
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
Can someone please exp-lain what I am doing wrong. My intent was to follow the OpenIddict examples but clearly I went wrong somewhere.
The full stacktrace follows:
System.InvalidOperationException: Scheme already exists: Bearer
at Microsoft.AspNetCore.Authentication.AuthenticationOptions.AddScheme(String name, Action`1 configureBuilder)
at Microsoft.AspNetCore.Authentication.AuthenticationBuilder.<>c__DisplayClass4_0`2.<AddSchemeHelper>b__0(AuthenticationOptions o)
at Microsoft.Extensions.Options.ConfigureNamedOptions`1.Configure(String name, TOptions options)
at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
at Microsoft.Extensions.Options.OptionsManager`1.<>c__DisplayClass5_0.<Get>b__0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
at Microsoft.Extensions.Options.OptionsManager`1.Get(String name)
at Microsoft.Extensions.Options.OptionsManager`1.get_Value()
at Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions`1 options, IDictionary`2 schemes)
at Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider..ctor(IOptions`1 options)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_0.<UseMiddleware>b__0(RequestDelegate next)
at Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String shutdownMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
at SIAngular.Program.Main(String[] args) in C:\Users\username\Documents\Visual Studio 2017\Projects\SIAngular\Program.cs:line 20
I finally found the answer which is probably obvious to OpenIddict experts, but not to casual users.
Since I am using JWT the.AddValidation() after the registration of the OpenIddict server options is not needed. This is obvious in hindsight but I hope this helps someone else with this problem. I am sure I am not thbe only person dumb enough to have been caught by this and when I look at OpenIddict samples now I understand, but I think the comment "For JWT tokens, use the Microsoft JWT bearer handler." could be amended to "For JWT tokens, use the Microsoft JWT bearer handler and remove the call to AddValidation below.
I have tried the below code and worked for me.
public void ConfigureServices(IServiceCollection services)
{
// Code omitted for brevity
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Audience = "https://localhost:5000/";
options.Authority = "https://localhost:5000/identity/";
})
.AddJwtBearer("AzureAD", options =>
{
options.Audience = "https://localhost:5000/";
options.Authority = "https://login.microsoftonline.com/eb971100-6f99-4bdc-8611-
1bc8edd7f436/";
});
}
You can read this complete document on the below URL:
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-6.0
I have tried other solution as well.
Please check if you have multiple startup.cs files and you are using any authentication schemes in that files.
and also check to publish folder/deployment folder, need to delete App_Data Folder before deploying fresh/ latest changes.

Azure Webjobs - Use INameResolver with TimerTrigger Function

I've tried to configure a job with a simple function with a TimerTrigger.
public class Processor
{
/// <summary>
/// Initializes a new instance of the <see cref="Processor"/> class.
/// </summary>
public Processor()
{
}
/// <summary>
/// Process the Leads to Marketo.
/// </summary>
[Disable("Processor.Disable")]
public async Task ProcessMessages([TimerTrigger("%Processor.TimerTrigger%")] TimerInfo timerInfo, TextWriter log)
{
// TODO : remove
await Task.FromResult(0);
}
}
My settings are defined in my app.config file:
<add key="Processor.TimerTrigger" value="00:01:00" />
<add key="Processor.Disable" value="false" />
When Starting my webjob, I've configure the job to use INameResolver and timertrigger:
static void Main()
{
// Configure the job host
var config = new JobHostConfiguration
{
NameResolver = new ConfigNameResolver() // Resolve name from the config file.
};
config.UseTimers();
var host = new JobHost(config);
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
When executing the line host.RunAndBlock(), I've got this exception :
Microsoft.Azure.WebJobs.Host.Indexers.FunctionIndexingException: Error indexing method 'ProcessMessages' ---> System.FormatException: String was not recognized as a valid TimeSpan.
I've put a break point in the class that implements the INameResolver interface but never hit.
Is there any way to configure a NameResolver with TimerTrigger ?
Thanks.
TimerTrigger does not currently support INameResolver. Please open an issue in the public repo here and we'll add that support. The other extension bindings support INameResolver. If it's important to you, we can get out a pre-release build for you to use/verify ahead of the actual next release.
Confirmation that INameResolver is now supported in Timer Triggers using the technique in the original question and a resolver that looks like this:
public class ConfigNameResolver : INameResolver
{
public string Resolve(string name)
{
return ConfigurationManager.AppSettings.Get(name);
}
}

ServiceStack web services security

Hi I am new to working with Servicestack and have downloaded their very comprehensive bootstrapapi example and am working with it, but am still having some issues. The issue is with security, what is happening is I am getting 405 errors when trying to access the protected services. Using the authenticate service it appears that I am authenticating correctly. Please help and explain. Here is the code:
public class Hello
{
public string Name { get; set; }
}
public class AuthHello
{
public string Name { get; set; }
}
public class RoleHello
{
public string Name { get; set; }
}
public class HelloResponse
{
public string Result { get; set; }
}
The Services:
public class HelloService : ServiceBase<Hello>
{
//Get's called by all HTTP Verbs (GET,POST,PUT,DELETE,etc) and endpoints JSON,XMl,JSV,etc
protected override object Run(Hello request)
{
return new HelloResponse { Result = "Hello, Olle är en ÖL ål " + request.Name };
}
}
[Authenticate()]
public class AuthHelloService : RestServiceBase<AuthHello>
{
public object Execute(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
[RequiredRole("Test")]
public class RoleHelloService : RestServiceBase<RoleHello>
{
public object Execute(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
Here is the AppHost:
public class HelloAppHost : AppHostBase
{
//Tell Service Stack the name of your application and where to find your web services
public HelloAppHost() : base("Hello Web Services", typeof(HelloService).Assembly) { }
public override void Configure(Container container)
{
//Register all Authentication methods you want to enable for this web app.
Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {new CustomCredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
}));
container.Register<ICacheClient>(new MemoryCacheClient() { FlushOnDispose = false });
//register user-defined REST-ful urls
Routes
.Add<Hello>("/hello")
.Add<Hello>("/hello/{Name}")
.Add<AuthHello>("/AuthHello")
.Add<RoleHello>("/RoleHello");
}
}
UPDATE
Everything works as expect if you replace : RestServiceBase with : ISevice so now the question is why.
Check the wiki documentation first
I would first go through the documentation in ServiceStack's Authentication Wiki to get a better idea about how ServiceStack's Authentication works. There's a lot of documentation in the wiki, so if you're unsure of something you should refer to that first. It's a community wiki so feel free to expand whats there if you think it can help others.
Refer to the implementation in the source code if behavior is not clear
If you're unsure of what something does you should refer to the RequiredRole source code as the master authority as how it works. RequiredRole is just a Request Filter Attribute which gets run before every service that has the attribute.
The RequiredRole attribute just calls your session.HasRole() method as seen here:
public bool HasAllRoles(IAuthSession session)
{
return this.RequiredRoles
.All(requiredRole => session != null
&& session.HasRole(requiredRole));
}
Because it just calls your session you can override the implementation of session.HasRole() if you have a custom session.
Registering and Implementing a CustomUserSession
The Social BootstrapApi project does implement its own CustomSession that it registers here but does not override the HasRole() implementation so it uses the built-in implementation in the base AuthUserSession.HasRole() which simply looks like the Roles collection to see if the user has the specified role in their Session POCO:
public virtual bool HasRole(string role)
{
return this.Roles != null && this.Roles.Contains(role);
}
Session properties populated by AuthUserRepository
The Roles property (as well as most other properties on a users Session) is populated by the AuthUserRepository that you have specified e.g. if you're using the OrmLiteAuthRepository like SocialBootstrapApi does here than the Roles attribute is persisted in the Roles column in the UserAuth RDBMS table. Depending on the AuthUserRepository you use the UserAuth / UserOAuthProvider POCOs get stored as RDBMS tables in OrmLite or as text blobs in Redis, etc.
Manage roles and permissions with AssignRoles / UnAssignRoles services
So for a user to have the required role (and authorization to pass), it should have this Role added to its UserAuth db row entry. ServiceStack's AuthFeature includes 2 services for managing users permissions and roles:
/assignroles
/unassignroles
How to initially give someone the Admin Role
These services does require a user with the Admin Role to be already authenticated.
You can do this by manually changing a specific users UserAuth.Role column to include the value "Admin". The Social Bootstrap API project instead does this by handling the OnAuthenticated() event on its CustomUserSession that simply checks to see if the authenticated username is declared in the Web.Config and if it is, calls the AssignRoles service giving that authenticated user the Admin Role:
if (AppHost.Config.AdminUserNames.Contains(session.UserAuthName)
&& !session.HasRole(RoleNames.Admin))
{
var assignRoles = authService.ResolveService<AssignRolesService>();
assignRoles.Execute(new AssignRoles {
UserName = session.UserAuthName,
Roles = { RoleNames.Admin }
});
}

What are the implications of using a single MembershipProvider to authenticate against multiple web service backends?

In this hypothetical scenario there is an ASP.NET 4 web application that simultaneously aggregates data from multiple web services. The web services are all of the same implementation, but are separate instances and are not aware of each other.
In the web application a user provides credentials for each web service he wants access to, and the authentication process iterates through all of his user name/password combos coupled with the URL for each web service. (The clunky UI is for illustration only....)
Assume the web application uses the ValidateUser method in a custom MembershipProvider class for authentication, and the MembershipProvider is configured in web.config as per usual.
Assume also that the custom MembershipProvider class has a Url property that changes with each authentication call to the different web services.
Assuming all of that, how do you handle the scenario where User 1 and User 2 are authenticating at the same time, but User 1 has access to Web Service A, B, and C, and User 2 has access to Web Service X, Y, and Z?
Will the credentials and URLs potentially get mixed up and User 1 might see User 2's data and vice-versa?
If you are going to implement a custom membership provider you will see lots of headaches down the road. The reason is that in your app model, the authorization scheme is based on whatever membership the user has (for a specific service).
I would advise to have your own membership (for your own site) and extend the profile model so that you can retrieve credentials for each service that the user has access to straight out of the user's profile.
The profile information can be used in conjunction with your own authorization based on your own membership and role providers (specific for your site). In that case you can assign each user a role specific to each service.
To successfully achieve that, for each service, write a wrapper, encapsulating service calls with your own methods (which call the service). This will allow you to mark your own methods with the [PrincipalPermissison] attribute... and achieve seemless authorization.
So if your user has access to the Amazon web service and there are credentials for that service stored in his/her profile you can have the following:
User Role: "AmazonAccessor"
public AmazonServiceWrapper
{
[PrincipalPermission(SecurityAction.Demand, Role = "AmazonAccessor")]
public void DoSomething()
{
UserProfile profile = UserProfile.Get();
ServiceCredential credential = (ServiceCredential)(from c in profile.ServiceCredentials where c.ServiceName = "Amazon" select c).Take(1);
if( credential == null )
return;
AmazonService amazon = new AmazonService();
amazon.ClientCredentials.UserName.UserName = credential.Username; //coming from profile
amazon.ClientCredentials.UserName.Password = credential.Password; //coming from profile
try{
amazon.DoSomething(); //wrap the amazon call.
}
catch(Exception ex)
{
}
}
}
This will prevent you from having to juggle membership and all sorts of other headaches.
Now to create your own profile you can do something like this:
[Serializable]
public class ServiceCredential
{
public string ServiceName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string ServiceUrl { get; set; }
}
public class UserProfile : ProfileBase
{
public static UserProfile Get(string username)
{
return (UserProfile)Create(username);
}
public static UserProfile Get()
{
return (UserProfile)Create(Membership.GetUser().UserName);
}
[SettingsAllowAnonymous(false)]
public List<ServiceCredential> ServiceCredentials
{
get
{
try
{
return base.GetPropertyValue("ServiceCredentials") as List<ServiceCredential>;
}
catch
{
return new List<ServiceCredential>();
}
}
set
{
base.SetPropertyValue("ServiceCredentials", value);
}
}
}
And of course the Web config:
<system.Web>
<profile
inherits="MyApplication.UserProfile"
defaultProvider="AspNetSqlProfileProvider">
<providers>
<add
name="MyProfileProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="MyConnectionString"
applicationName="MyApplication" />
</providers>
</profile>
<system.Web>