ASP.NET and Identity 2.0 roles with VB - asp.net

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)

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));```

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
});

Delete a user in Web-Form

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

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

Session maintenance in cloud application ASP.Net MVC

I am developing a web application on ASP.Net MVC 4 with razor syntax. I have to deploy it on cloud, probably on Azure.
I am quiet confused about the login scheme of MVC. We have to work on multiple schemas so thats why we aren't using the membership provided by ASP.Net.
I know session maintenance and i used it in web forms but session have some serious issues with cloud.
What would be the best method to save usernames and session data?
I would avoid using the Session State to store user information or even session data, because this makes your application less scalable.
If you want to store a username, displayname, email address, ... I would suggest Claims Based authentication. Brock Allen wrote a great introduction article to get you started: Replacing forms authentication with WIF’s session authentication module (SAM) to enable claims aware identity.
The main idea is that you hand out a cookie (just like with Forms Authentication):
Claim[] claims = LoadClaimsForUser(username);
var id = new ClaimsIdentity(claims, "Forms");
var cp = new ClaimsPrincipal(id);
var token = new SessionSecurityToken(cp);
var sam = FederatedAuthentication.SessionAuthenticationModule;
sam.WriteSessionTokenToCookie(token);
And this cookie represents a ClaimIdentity which can contain one or more claims like email address etc...
private Claim[] LoadClaimsForUser(string username) {
var claims = new Claim[]
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Email, "username#company.com"),
new Claim(ClaimTypes.Role, "RoleA"),
new Claim(ClaimTypes.Role, "RoleB"),
new Claim(OfficeLocationClaimType, "5W-A1"),
};
return claims; }
In terms of session data you might want to consider Windows Azure In-Role Caching or the Windows Azure Caching Service. There's even a Session State Provider which can store the session state in cache: http://msdn.microsoft.com/en-us/library/windowsazure/gg185668.aspx.
But you can easily do this yourself without using the session state by playing with the cache keys, like this:
myCache.Put(user.Id + "_Friends", friendsList);

Resources