Delete a user in Web-Form - asp.net

i am using the default template of the ASP.net identity framework for registering users. the problem is i can't remove any users. i got an error "Default Membership Provider must be specified.". i know that i must specify the default membership provider and then use Membership.Delete(..);to simply delete the user. but the problem is that i can't config the membership default provider . i searched a lot but all of the link recommend to use " ASP.NET Configuration" wizard which i can't find in Web-Form project ! here is the code for creating a user:
var manager = new UserManager();
var user = new ApplicationUser() { UserName = UserName.Text };
IdentityResult result = manager.Create(user, Password.Text);

Use
userManager.Delete(user)
MembershipProvider is depricated; wherever you use calls to this class - remove them - they are not going to work as Identity framework and MembershipProvider are incompatible

Related

Authenticating with Azure Active Directory: RoleProvider for ClaimsIdentity?

Fellow developers, I'm updating an IIS web application from using Windows Authentication to using Azure Active Directory instead. The setup looks fine: I can successfully authenticate, and I get the user's identity as a ClaimsIdentity.
However, this does not mesh well with my current use of System.Web.Security.WindowsTokenRoleProvider. When doing an IsInRole() check, the role provider detects that the current identity is not a WindowsIdentity and throws a ProviderException:
Method is only supported if the user name parameter matches the user name in the current Windows Identity.
I believe I need to configure the application's role manager to use a ClaimsIdentity-friendly provider. Is there a standard role provider class that plays well with the ClaimsIdentity, or will I need to build a custom role provider?
Edit: I've built my own custom role manager that appears to only need an implementation of GetRolesForUser(string username) method. It solves my problem, but doesn't answer my question :)
The base class of Claims Identity is the System.Security.Claims namespace. Hence it needs to be used in the project.
using System.Security.Claims;
To achieve this, we need to use customize the ClaimsIdentity based on our requirement as shown below.
Below is the code snippet:
string Default_IdentityProvider_ClaimValue = "Some_ClaimsIdentity";
var id = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, users.UserId.ToString(), ClaimValueTypes.String));
id.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, users.UserName, ClaimValueTypes.String));
id.AddClaim(new Claim(Identity_Provider_ClaimType, Default_IdentityProvider_ClaimValue, ClaimValueTypes.String));
id.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, users.UserName, ClaimValueTypes.String));```

Faking authentication during development

In my current asp.net MVC core application we use OpenId Connect to authenticate with our corporation's identity provider.
However during local development we cannot reach the the provider.
Also we would like to easily change claim values for development and unit testing purposes.
I tried swapping my service binding for IHttpContextAccessor to a DevelopmentHttpContextAccessor that fills up the HttpContext's Identity with the desired claims.
This is a bit of a roundabout way and it also doesn't work as the claims are emptied when I check them in my Service.
What is the standard way of handling this during development and unit testing? What am I missing?
The answer was not faking IHttpContextAccessor, but setting a custom ClaimsPrincipal to the identity property.
In your Startup.Configure you can add a middleware step:
app.Use((httpContext, nextMiddleware) => {
var claims = new[] {
// Your claims here
};
var claimsIdentity = new ClaimsIdentity(claims);
var user = new ClaimsPrincipal(claimsIdentity);
httpContext.User = user;
return nextMiddleware();
});

Using ASP.NET Core MVC cookie based authentication with custom user tables in database

I have my own tables for Authentication:
Users
Roles
UserRoles
I am am trying to figure out what the best way to implement custom authentication with ASP.NET Core MVC would be. I do not want to use the built in UserManager, RoleManager, etc. I prefer creating my own. Can I somehow still tap into the cookie based authentication and use all of the ASP.NET Authorization helper tags without using asp.net identity?
Correct me if I am wrong, but I believe I want something like this:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie
I have been trying to figure out ASP.NET Identity for years and I am
sick of not understanding every single part of it. I would rather
implement my own auth just like the good old days. It is most likely
my problem for not being able to read the documentation and pick up on
it, but I cant stand Entity Framework / ASP.NET Identity. I am aware
that ASP.NET Identity can be used without EF but just seems like a
pain.
Well, if you decided to go that route, you can use Cookie Authentication Middleware.
There are too many moving pieces, so I created a sample project in GitHub.
You can replace this LDAP Authentication with your own Authentication mechanism. Here is actual implementation.
The main reason I did not use ASP.NET Identity in some of my projects is we already have Active Directory in our organization.
Startup.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
Events = new CookieAuthenticationEvents
{
OnRedirectToAccessDenied = context =>
{
context.Response.StatusCode = (int) HttpStatusCode.Forbidden;
return TaskCache.CompletedTask;
}
},
ExpireTimeSpan = TimeSpan.FromMinutes(Int32.Parse(Configuration.GetSection(
"AppSettings:CookieAuthentication:ExpireMinutes").Value)),
AuthenticationScheme = Constants.AuthenticationScheme,
LoginPath = new PathString("/Account/Login"),
AccessDeniedPath = new PathString("/Common/AccessDenied"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});

how to use UserId instead of user name in authentication ( Web Forms asp.net)?

I have Visual Studio 2013 Ultimate. I have created ASP.NET Web Forms Application (not MVC) with .Net Framework 4.
Users Primary Key is uniqueidentifier (GUID),
I found in dafault Login.aspx, Register.aspx and other forms. There are codes using User.Identity.Name instead of Primary Key UserId :
Dim hasLocalPassword = OpenAuth.HasLocalPassword(User.Identity.Name)
Dim accounts As IEnumerable(Of OpenAuthAccountData) = OpenAuth.GetAccountsForUser(User.Identity.Name)
Dim result As SetPasswordResult = OpenAuth.AddLocalPassword(User.Identity.Name, password.Text)
How to change this 'User.Identity.Name' to Primary Key GUID of users, because more than two users can have same name?
If you are using AspNet membership providers :
MembershipUser user = Membership.GetUser(User.Identity.Name);
Guid guid = (Guid)user.ProviderUserKey;
In case of Oauth you have do do this.
You should add `[InitializeSimpleMembership]` on top of controller class if you use another controller than AccountController.
WebSecurity.GetUserId(User.Identity.Name);
Also check this answer:
MVC Simplemembership I cannot get the userID after logging a user in via OAuth

ASP.NET and Identity 2.0 roles with VB

I'm trying to build webpage with Microsoft Passport authentication. That works fine but how to use roles for authenticated users?
I have problems to understand how roles is working with 2.0.
I am able to create new role with Roles.CreateRole("TestRole") but if I have understand right it using Identity 1.0? at least it creates record to Roles table in database not AspNetRoles.
I think that I need to use RoleManager and UserManager?
Any examples how to do that with VB.
For creating role use RoleManager and for assigning role to user Use UserManager.
RoleManager = New RoleManager(Of IdentityRole)(New RoleStore(Of IdentityRole)(New MyDbContext()))
Dim roleresult = RoleManager.Create(New IdentityRole(roleName))
UserManager.AddToRole(currentUser.Id, roleName)

Resources