Set manually System.Security.Claims.ClaimsPrincipal - c#

In a restFul API with Net 6, I must use a company-provided dll to handle authentication. The problem is that this dll is currently not working, so I must manually set this.User from System.Security.Claims.ClaimsPrincipal to simulate that I am getting those claims from the dll.
How could I do this?
I have tried to access this.User from Program.cs but I see that it is not possible.
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, "IdUser"));
claims.Add(new Claim(ClaimTypes.NameIdentifier, "TypeUser"));
claims.Add(new Claim(ClaimTypes.NameIdentifier, "IdRol"));
System.Web.HttpContext.Current.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;

Related

Am I using FIrebaseAuth correctly in Razor/.NET Core?

I have implemented FirebaseAuth in my .NET app, but I'm not sure if I have done so correctly. It feels like I'm using a mix of FirebaseAuth and .NET authentication using cookie based authentication.
I started by generating a firebase token by succesfully signing in the user:
FirebaseAuthProvider firebaseAuthProvider = new FirebaseAuthProvider(new FirebaseConfig("API_KEY"));
FirebaseAuthLink firebaseAuthLink = await firebaseAuthProvider.SignInWithEmailAndPasswordAsync(Input.Email, Input.Password);
var firebaseToken = firebaseAuthLink.FirebaseToken;
I then created custom claims, and called HttpContext.SignInAsync using these claims to be fully signed in according to .NET and use [Authorize] on my Razor pages:
var claims = new List<Claim>()
{
new Claim(ClaimTypes.NameIdentifier, Convert.ToString(user.LocalId)),
new Claim(ClaimTypes.Role, userInfo.Role),
new Claim("Email", user.Email),
new Claim("FirstName", userInfo.FirstName),
new Claim("LastName", userInfo.LastName),
new Claim("Address", userInfo.Address),
new Claim("FirebaseToken", firebaseToken)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties());
I see that you can also add custom claims through FirebaseAuth, so am I doing something wrong by calling HttpContext.SignInAsync? Is there an easier way to be authenticated simply by purely using FirebaseAuth?

Asp.Net Core role system without Identity

How can i add role system without identity? I need to member and admin roles.
Login code:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, loginDTO.StrUserID)
};
var userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(principal);
Startup.cs
services.AddAuthorization(opt =>
{
opt.AddPolicy("Admin", policy => policy.RequireClaim(ClaimTypes.Name));
});
How can i add role system without identity? I need to member and admin roles.
As far as I know, if you used asp.net core cookie authentication , there is no need to build a role system.
We could write the codes in your login logic to check the user role from database.
Then we could add role by adding the ClaimTypes.Role Claim. Then we could use [Authorize(Roles ="Admin")] attribute to let only admin role user access.
More details, you could refer to below codes:
//Here build the logic to get the user role from database, then create a new role claim to add the user role.
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "TestA"),
new Claim(ClaimTypes.Role, "Admin"),
};
var userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
HttpContext.SignInAsync(principal);
On the controller:
[Authorize(Roles ="Admin")]
public class AdminController : Controller

How to C# Core OAuth without external login panel

I'm making an API for Exact Online for a website with a form. The visitor will fill in his information and after that the visitor sends it. It need to be send to the Exact online account from my client. But before that I need a accesstoken. The problem is that I don't want to give the user the login page that Exact gives me. I'm searching already for days to find a way to skip the login or to enter the login information by backend (there is always 1 login, and that is the login from my client).
Now this authorization thing is something new for me. So far I know I can call my authorization settings from the startup with this:
HttpContext.Authentication.GetAuthenticateInfoAsync("ExactOnline");
But then I get that loginscreen that I don't want. The only thing that Exact is telling me to do:
Create an app registration that supports an automated connection wizard (your provisioning process).
Is there a way to send them the login information and the visitor doesn't see a loginpage.
In my Startup.cs
var s = new OAuthOptions{
AuthenticationScheme = "ExactOnline",
ClientId = "CLIENTID",
ClientSecret = "CLIENTSECRET",
CallbackPath = new PathString("/callback"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
AuthorizationEndpoint = new Uri(string.Format("{0}/api/oauth2/auth", "https://start.exactonline.nl")).ToString(),
TokenEndpoint = new Uri(string.Format("{0}/api/oauth2/token", "https://start.exactonline.nl")).ToString(),
//Scope = { "identity", "roles" },
Events = new OAuthEvents
{
OnCreatingTicket = context =>
{
context.Identity.AddClaim(new Claim("urn:token:exactonline", context.AccessToken));
return Task.FromResult(true);
}
}
};
app.UseOAuthAuthentication(s);
First i had this code, but that gives me a null exception when i put the identity in the claimprincipal, probably because my claimsprincipal is null and i don't know why.
HttpContext.Authentication.AuthenticateAsync("ExactOnline");
var identity = new ClaimsIdentity("ExactOnline",ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
identity.Label = "Authentication";
identity.AddClaim(new Claim(ClaimTypes.Name, "USERNAME?"));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "PASSWORD?"));
claimsPrincipal.AddIdentity(identity);
var test = HttpContext.Authentication.SignInAsync("ExactOnline", claimsPrincipal, new AuthenticationProperties() { IsPersistent = false }));
After that i tried following code, but that also didn't work. My code will continue, but the test variable will be filled with this message: The name 'InnerExceptionCount' does not exist in the current context.
var identity = new ClaimsIdentity("ExactOnline", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
identity.Label = "Authentication";
identity.AddClaim(new Claim("username", "USERNAME"));
identity.AddClaim(new Claim("password", "PASSWORD"));
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
var test = HttpContext.Authentication.SignInAsync("ExactOnline", claimsPrincipal, new AuthenticationProperties() { IsPersistent = false });
Someone know how to solve this problem?

Owin claims - Add multiple ClaimTypes.Role

I have an application in which users can be assigned the following roles:
SuperAdmin
Admin
User
One user may have assigned two or more roles, eg. both SuperAdmin and User. My application uses claims, and therefore i want to authenticate user roles through claims too. like:
[Authorize(Roles="Admin")]
Unfortunately, i dont know how i can add multiple roles to my ClaimTypes.Role. I have the following code:
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, name),
new Claim(ClaimTypes.Email, email),
new Claim(ClaimTypes.Role, "User", "Admin", "SuperAdmin")
},
"ApplicationCookie");
As you can see, i tried to add more roles for the sake of illustrating, but obviously its done in a wrong way, and therefore doesn't work.
Any help is therefore much appreciated.
A claims identity can have multiple claims with the same ClaimType. That will make it possible to use the HasClaim method for checking if a specific user role is present.
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, name),
new Claim(ClaimTypes.Email, email),
new Claim(ClaimTypes.Role, "User"),
new Claim(ClaimTypes.Role, "Admin"),
new Claim(ClaimTypes.Role,"SuperAdmin")
},
"ApplicationCookie");
#Parameswar Rao explained well but in case of dynamic roles
For example a user object already has property role of type list like
then using localfunctions
ClaimsIdentity getClaimsIdentity()
{
return new ClaimsIdentity(
getClaims()
);
Claim[] getClaims()
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
foreach (var item in user.Roles)
{
claims.Add(new Claim(ClaimTypes.Role, item));
}
return claims.ToArray();
}
}
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = getClaimsIdentity()
}

Custom RoleProvider in ASP.NET Core with Identity?

In past MVC versions I was able to do
<roleManager enabled="true" defaultProvider="...." ...
in to the web.config to get a custom role provider, but that doesn't seem to be the case anymore.
Essentially what I want to do is:
The user logs in.
On success, get roles for user from external source.
Apply roles to user to be used in code.
Match user roles to roles in custom RoleProvider
How do I do this in ASP.NET Core?
If you're using simple cookie-based authentication instead of the Identity framework, you can add your roles as claims and they will be picked up by User.IsInRole(...), [Authorize(Roles = "...")], etc.
private async Task SignIn(string username)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username)
};
// TODO: get roles from external source
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
claims.Add(new Claim(ClaimTypes.Role, "Moderator"));
var identity = new ClaimsIdentity(
claims,
CookieAuthenticationDefaults.AuthenticationScheme,
ClaimTypes.Name,
ClaimTypes.Role
);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddMonths(1)
}
);
}

Categories