how to get the group membership? - asp.net-core

I am trying to get the Roles of a logged in user , using using openID connect with "https://login.microsoftonline.com/"
I can hit breakpoints on OnTokenValidated , and OnTicketReceived . in my controller decorated with [Authorize], User.Identity.IsAuthenticated is true ,but User.IsInRole("admin") is false <-- this is a group in my tenant, and my account is a member.
Any suggestions on getting role Info? Do i need to implement OnUserInformationReceived ? Any examples?
I am following the wiki : Quickstart: Add sign-in with Microsoft to an ASP.NET Core web app
Thanks,Peter

Group membership is not included in ID token by default , you can follow below steps to configure your application to receive group claims :
In your application page, click on Manifest to open the inline manifest editor.
Edit the manifest by locating the groupMembershipClaims setting, and setting its value to All (or to SecurityGroup if you are not interested in Distribution Lists).
Save the manifest.
{
...
"createdDateTime": "",
"groupMembershipClaims": "All",
"identifierUris": [],
...
}
To receive the groups claim with the object id of the security groups, make sure that the user accounts you plan to sign-in in is assigned to a few security groups in this AAD tenant.
You could use policy in asp.net core , use an attribute with a named policy then you define the policy in startup to require group claim and set allowed Group ID . See code sample here .
In addition, User.IsInRole("admin") will check whether http://schemas.microsoft.com/ws/2008/06/identity/claims/role: admin exists in user claims . You can also set the RoleClaimType to use group information and then use Roles .

Related

Authenticate AZURE Ad user by App role assigned to the user group

I have created an App role for my AZURE AD Backend Api and assigned this role to a group. Now I want to authenticate user in my .net core backend application on the basis if user has a group which has this role. I am getting the group ids in the access token but how can I get app roles assigned to these groups.
Please check how you enabled group claims in Azure Portal.
If you check the Emit groups as role claims option like below you cannot see application roles, but you can see group ids.
If the above option is enabled, make sure to uncheck the box.
Note
If you use the option to emit group data as roles, only groups will
appear in the role claim. Any application roles that the user is assigned to won't appear in the role claim.
Also, I would suggest you refer to this Microsoft official documentation below which states that if you add a service principal to a group, and then assign an app role to that group, Azure AD does not add the roles claim to tokens it issues.You can modify the “groupMembershipClaims” field in application manifest if you want to include groups claim in your token like below: -
Add app roles to your application and receive them in the token
For more in detail, please refer below link:
Configure group claims for applications by using Azure Active Directory

Azure Logic app, AzureAD remove group members, insuficcient permission

I'm creating a Azure Logic app to replace members of defined Azure AD group. I have used this blog (https://geekshangout.com/logic-app-remove-azure-ad-group-members/) as of base for my job, but so far remove-member fails with insufficient permissions.
Basically logic app does:
Retrieve list of users from Azure SQL table with specific query: OK
Get list of users from AzureAD group : OK
For-each member:
remove member.objectID from azure group object ID:: Fails with following error:
"body": {
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"date": "2022-02-10T07:32:44",
"request-id": "--------------",
"client-request-id": "------------"
}
}
}
So far: I re-created the logic app and taking care of:
Admin consent is given as described in the blog, by using the Global Admin account.
I can see in the 'Enterprise Applications' blade this 'logic app' created
permissions should be correct: API name: Microsoft graph, Claims: Directory.readwrite.all, group.readwrite.all, user.readwrite.all, offline_access , as of Microsoft documentation describes (https://learn.microsoft.com/en-us/connectors/azuread/)
Awaited now about 24 hours, so no 'cloud-lag' should be problem.
Should this 'Enterprise Application' have an additional permissions? If so, what and where?
Already tried to create a custom role with permissions described here: https://learn.microsoft.com/en-us/azure/active-directory/roles/custom-group-permissions
"Life is not a problem to be solved, but a reality to be experienced"
~T
Assuming the user with which you set up the Logic Apps connection for Azure AD is authorized to manage this group's membership (e.g. which would be the case if this was a Global Administrator), the most likely cause for this is that the group you are trying to change membership for is a role-assignable group.
Role-assignable groups are special groups to which directory roles can be assigned. Adding a member to the group is equivalent to assigning a directory role to that member, so neither of the delegated permissions Directory.ReadWrite.All nor Group.ReadWrite.All allow this. (For regular groups, either of them would be sufficient.) The app would also need to be granted the delegated permission RoleManagement.ReadWrite.Directory.
From the look of things, the built-in Logic Apps connector for Azure AD is not built to handle group membership for role-assignable groups.
If you really do need to be able to do this, you could update the delegated permissions granted to the connector to include RoleManagement.ReadWrite.Directory, but you should be very careful about this (and your entire solution, including the SQL database and the Logic App), as misuse could carry significant security risks.

Blazor Authentication via existing database table

I want to build a Blazor server application that has user authentication. The only experience I have with Blazor was a simple app for work that used AD authentication and made various api calls to get the data necessary.
I have an existing sql table containing: userId, username, permissionLevel
Basically I want to be able to make a new table with the username and a hashed password that when matched will return an object containing userid, username, and permissionlevel that will be used for authentication in the Blazor server app.
Is this possible and are there any resources pointing me in the right direction for this? I have searched but have not come up with anything I am looking for. I am looking for examples of how to display certain options based on PermissionLevel.
Blazor Server supports Policy based authorization (https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#authorize-attribute) - Example:
#page "/"
#attribute [Authorize(Policy = "PermissionLevel.5")]
<p>You can only see this if you satisfy the 'PermissionLevel.5' policy.</p>
You can register all policies (PermissionLevels) in Startup.cs, example:
services.AddAuthorization(options =>
{
options.AddPolicy("PermissionLevel.5",
policy => policy.RequireClaim("Permission", "PermissionLevel.5"));
});
Unlike with Role based authorization, only a single policy can be applied inside any Authorize attribute, or AuthorizeView component. You can however evaluate multiple requirements for a single policy (such as if PermissionLevel must be '5' or higher) by customising your own AuthorizationHandler (see MS Docs for some good examples: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-6.0#use-a-handler-for-multiple-requirements - You can also refer to my last link below for a detailed example using Role Claims, by #pacificoder).
If you use ASP.NET Identity (such as with a Blazor Project's Individual User Accounts), the AspNetUserClaims table is created for you (see https://learn.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-6.0#entity-types), which contains all the user-claim pairs. Claims can be assigned to users during runtime by using UserManager.AddClaimAsync().
This would be sufficient if you do not have many claims - However the more permissions and roles a user has, the larger the access token becomes (and you could get an "Access token must not be longer than 4K" error - I started getting this after adding 5+ claims to a role, but not sure how easy it is to exceed 4K with user claims only...).
If you consider using Policy-based authorization, I would recommend taking a look at this answer by #pacificoder: https://stackoverflow.com/a/49539930/13678817 - Although this relates to Role based policies, the same approach can be used for user based policies, and I also liked the way Enums are used to create and add all the permissions/policies.

How to get the [Authorize(Roles = "RoleName")] into variable?

i am trying to save the role from the AuthorizeAttribute in a variable but i cant seem to figure out how. i want something like this. Note: the User/Roles is created from Azure Active Directory
private string CalculateRole()
{
var role = authorize.role;
return role;
}
i searched all over and "closest" i got is this question asp.net identity get all roles of logged in user
but all i get back is a list of Claims I cant find any "roles".
[Authorize(Roles = "RoleName")] is used for access. We can specify the roles that have access to the requested resource using the Roles property of Authorize attribute. For example, [Authorize(Roles = "Admin")] allows us to access the action method to users who are member of "Admin" role.
For the currently signed in user for an application, you can always find the Application Roles assigned to them from the Role claims available as part of the access token from Azure Active Directory.
For more information, here's a sample that uses OpenID Connect to sign-in users and use Azure AD Application Roles (app roles) for authorization. Also, you could use Microsoft Graph API to get the roles.
You can get roles from db by current user id.
You can have a bool validation within the Controller (where HttpContext.User e
bool isAdminUser = User.IsInRole("Admin");
This is fine if you want to validate for specific -or a few- Roles defined. If you have many roles this may not be the best option and you might want to consider to call GraphApi instead for membership validation.

Yii multiple user login in an application

I am a new in Yii framework, I just setup an application and separate front-end & Back-end part. Both User can register / log in properly. Now I want to login different user from front-end site.
Example : Front-End user are tow types
1. Customer
2. Merchant
I want to set different role of theme. How to possible it, Please share with me.
You will probably need to use Yii's RBAC. In order to implement and use RBAC in yii you need to follow the following steps:
1-configure main.php which is located at '/path/to/yourApp/protected/config/main.php'
'authManager'=>array(
'class'=>'CDbAuthManager',
'connectionID'=>'db', //your database config name
),
2-import yii's rbac database scheme into your database. You can find it under /path/to/yii/framework/web/auth/ directory
3-add your operations. Operations such as 'VIEW_POST' or 'EDIT_POST':
$auth=Yii::app()->authManager;
$auth->createOperation('VIEW_POST','view a post');
$auth->createOperation('EDIT_POST','edit a post');
4-create your roles. For example in your case you will have two roles. First Customer and second Merchant.
$role=$auth->createRole('CUSTOMER');
5- Assign operations to your roles:
$role->addChild('VIEW_POST');
6- All done! You can restrict the access like below:
if(Yii::app()->user->checkAccess('VIEW_POST'))
{
//user has access to view a post
}else{
//logged in user has no access to view a post
}
You can also check access with role like below:
if(Yii::app()->user->checkAccess('CUSTOMER')) {}
In order to assign a role to a user use the assign method:
$auth->assign('CUSTOMER','USERNAME | USER ID'); //user will hold the CUSTOMER ROLE
It might also be noted that, I assumed that you have implemented your authentication class. You can find more about Yii's RBAC and authentication in the following link which is Yii's official document:
Yii Authentication and Authorization