does serverless databases like faunadb support role based auth? - serverless

i'm new to serverless architecture in general, and i'm studying migrating my current php/mysql rest api to serverless arch.
my main concern is access control.
in certain app, i allow users to access content based on role, and groups they are assigned to "
example
role: user groups: [1,2,3] can only access content with group_id: 1 || 2 || 3
is it possible to do such access control in serverless databases like faunadb ?

It is possible to do such access control with FaunaDB and much more with the ABAC system (https://docs.fauna.com/fauna/current/security/abac.html)
Roles:
In essence you have Roles and these roles provide permissions
CreateRole({
name: "access_todos",
privileges: [{
resource: Collection("todos"),
actions: {
create: true,
update: true,
delete: true,
write: true
}
}]
})
(you might notice that this of course gives access to all groups which is not what you want, we'll get to that)
Roles can be assigned to different things:
Keys: simply make a key with that role and that key can only access the groups collection
Functions: a User Defined Function (like a stored procedure) can assume a role.
Entities in a collection or part of a collection: any entity (e.g. Users, ShareLinks, Accounts) could be assigned a role by adding a 'membership.
Roles Membership (assign roles to a database entity):
You assign a role to database entities by using the membership field.
In this case, all accounts in your database will have these privileges. You can also use a function here to filter out a certain type of account etc..
CreateRole({
name: "access_todos",
membership: [{ resource: Collection("accounts") }],
privileges: [{
resource: Collection("todos"),
actions: {
create: true,
update: true,
delete: true,
write: true
}
}]
})
Assume the identity of that entity, (get a key for that database entity):
Then that leaves us with the question: "how do we assume the identity of a user?".
We use login for that. First you create an account with a password:
Create(
Class("account"),
{
data: { email: "alice#example.com" }
credentials: { password: "secret password" },
}));
The important part is the credentials.password field which is a special field for FaunaDB. It will be encrypted and when a database entity has such a password you can use Login to assume the identity of the entity:
Login(
Index("accounts_by_email"), "alice#example.com"),
{ password: "secret password" })
Login will provide you a token and that token will now have all the rights that this account has. Or in other words all the privileges of the roles for which this database entity of the collection 'accounts' is member (and membership is defined on the role with the membership key)
The power of Role predicates and the 'Identity()' function
Ok but how do we get more fine-grained access?
Roles can have lambda predicates instead of booleans. That means in your case you could store the array of groups on the user (or vice versa) and link the account to the user.
privileges: [
{
resource: Collection("Groups"),
actions: {
read: Query(
Lambda("groupReference",
// Write your logic
)
)
}
}
]
In such a query, the lambda parameter is the reference of the entity you try to access (e.g. a group)
One question remains.. how do we check whether the user linked to an account has access to the groups? Well we use 'Identity()' for that which is an FQL function that returns the reference of the currently logged in database entity.
Note: by default you get read/write access to the entity you are logged into. Hence you do not want to store the group ids on the account since a user could in theory change these. This is why I split account and user in my explanation. We will probably change this in a future FQL version since this appears to be confusing/cumbersome.
A few good resources:
- ABAC docs: https://docs.fauna.com/fauna/current/security/abac.html
- ABAC with GraphQL: https://medium.com/fauna/abac-graphql-6e3273945b1c
- Authentication docs: https://app.fauna.com/tutorials/authentication#creating-users
We are building a complete example as we speak which I expect to appear on our blog in the coming weeks.

Related

How to set the Sort Key(Secondary key) in AWS Cognito?

I'm using Cognito User Pool for my iOS App User Registration. In general, when Registering a user with Cognito I'm using the email as userID. And also I'm collecting other info like Phone number, Business Name and etc. In this case when I try to register with the same email id with a Different Business name it will show an alert like User already Exist.
In my new Work case, I want to save/register the same email with a different Business name. How can I achieve it?
for example, if we are using a DynamoDB table we have the Partition key and Sort key. By using those we set the email as the Partition key and the Business Name as the Sort key and we can achieve uniqueness.
can we implement the same using Cognito? Does Cognito support the Partition key and Sort key concept?
Is there any way to achieve this by using Cognito?
Please help me with this issue.
Let start from this link :
Configuring User Pool Attributes
You can have changeable standard attributes as far as they are not required. You can add custom attributes as well but they are un-changeable.
Well, let's move on another case on some projects I have a need to storing a user federated identity id (i.e ap-northeast-1:3c2f5c30-0dc8-4d74-91a8-bf5c688abcde) into a cognito user pool attribute. I should store it on a custom attribute (i.e custom:identity_id) because of it will never change in the future.
Back to your case, as it will be dynamic values where users has ability to change their organization list so you can utilize an unused standard attributes for. For example, I will use "zoneinfo" although it looks strange to use unassociated attribute because there is no one with the name "organization". However at least users can pull their organization from their token once logged-in as like :
"zoneinfo": "[org1, org2, org3, etc]"
But it can't full accomodate your case as it should be stored after user registration. While if you set the "zoneinfo" on required registration, it must be unchangeable then. To solve this problem, you can utilize the cognito user pool Post-Confirmation trigger to run some logic to init a standard attribute with empty organization list (i.e "zoneinfo": "[]") adminUpdateUserAttributes. That so users can modify this attribute then because of it is not required attribute.
Sample of adminUpdateUserAttributes :
async function updateOrgAttr() {
try {
var params = {
UserAttributes: [ /* required */
{
Name: 'zoneinfo', /* required */
Value: '[]'
}
],
UserPoolId: 'ap-northeast-1_xxxxxxxx', /* required */
Username: event.userName /* event.userName is an item of post-confirmation trigger event source */
};
let cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
await cognitoidentityserviceprovider.adminUpdateUserAttributes(params).promise()
} catch(e) {
throw e
}
}

Providing access to User Groups using Identity Server 3

The application I'm currently working on is a huge ASP.NET MVC web application which uses traditional Windows Authentication model. We are trying to migrate to Single Sign On model using Identity Server 3 and Open ID Connect.
Coming to my question, is there any way/work around to provide access on a user group basis when using Identity Server? The problem here is that the my user groups could either be role based or Active directory groups. I'm looking for something like InMemoryGroup (similar to InMemoryUser).
Something that mimicks the following for a Group of users that can be role based or not:
new InMemoryUser
{
Username = "harry",
Password = "thisispassword#123",
Subject = "1",
Claims = new Claim[]
{
new Claim(Constants.ClaimTypes.Name, "Harry Potter"),
new Claim(Constants.ClaimTypes.GivenName, "Harry"),
new Claim(Constants.ClaimTypes.FamilyName, "Potter"),
new Claim(Constants.ClaimTypes.Email, "harry.potter#hogwarts.com"),
new Claim(Constants.ClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(Constants.ClaimTypes.Role, "Administrator"),
}
}
I'm relatively new to Identity Server and Open ID Connect and not able to find anything online and would really appreciate any leads.
To represent the fact that a user is a member of a group you just add a claim. You could add:
new Claim("Group", "Hogwarts Student")
to your in memory user. The claim indicates that Harry is a member of the "Hogwarts Student" group. There is a couple of things going on here you want to be aware of. The constructor being called is:
new Claim(string claimType, string claimValue)
There Identity Server provides some standard ones in the Constants class but you can make up your own. Also, you can have multiple group claims, so you could have
new Claim("Group", "Hogwarts Student"),
new Claim("Group", "Gryffindor House)
If you wanted to see if Harry was in the "Gryffindor House" group, you'd just search through is list of claims where the claim type is equal to "Group" and the claim value is equal to "Gryffindor House".
Finally, the difference between groups and roles is generally more a matter of application semantics that a physical difference in how they are stored. In general, the set of users that can perform the "Administrator" role for an application is just a group of users. It is the way that an application treats users of a group that makes the group a role.

Apache Usergrid 2.x: can you restrict API access by a Data Entity's property value?

Say I have the following API, where users can have zero or more registeredIds, which model identifiers by type (with effective dates).
Two examples of registeredIds include:
// Social Security Number
{
"id" : "111-11-1111",
"type" : "SSN",
"validFrom": 315554400000,
"validTo" : null,
"registrationAuthority": "United States Social Security Administration"
},
// Employee ID
{
"id" : "12345678",
"type" : "employee-id",
"validFrom": 1262325600000,
"validTo" : null,
"registrationAuthority": "YoYoDyne"
}
When Anonymous User requests an employee, e.g.,
https://api.usergrid.com/your-org/your-app/users/janedoe
Anonymous User should only get a single registeredId.type with the type value "employee-id." Administrators, however, should see both the "employee-id" and "SSN" registeredId.types.
How would Apache Usergrid apply access control by the registeredId.type? I know I can assign permissions, but this is too restrictive. Can I create some kind of Entity SubType? Or should I handle this through relationships?
Currently, Usergrid does not allow you to set property validation checks. One solution to this problem is to have separate "EmployeeID" entities, have a connection from each User to that their id entity and setup permissions so that only authenticated users can access the EmployeeID entities.

Best Practices for Roles vs. Claims in ASP.NET Identity

I am completely new to the use of claims in ASP.NETIdentity and want to get an idea of best practices in the use of Roles and/or Claims.
After all this reading, I still have questions like...
Q: Do we no longer use Roles?
Q: If so, why are Roles still offered?
Q: Should we only use Claims?
Q: Should we use Roles & Claims together?
My initial thought is that we "should" use them together. I see Claims as sub-categories to the Roles they support.
FOR EXAMPLE:
Role: Accounting
Claims: CanUpdateLedger, CanOnlyReadLedger, CanDeleteFromLedger
Q: Are they intended to be mutually exclusive?
Q: Or is it better to go Claims ONLY and "fully-qualify" you claims?
Q: So what are the best practices here?
EXAMPLE: Using Roles & Claims Together
Of course, you would have to write your own Attribute logic for this...
[Authorize(Roles="Accounting")]
[ClaimAuthorize(Permission="CanUpdateLedger")]
public ActionResult CreateAsset(Asset entity)
{
// Do stuff here
return View();
}
EXAMPLE: Fully-Qualifying Your Claims
[ClaimAuthorize(Permission="Accounting.Ledger.CanUpdate")]
public ActionResult CreateAsset(Asset entity)
{
// Do stuff here
return View();
}
A role is a symbolic category that collects together users who share the same levels of security privileges. Role-based authorization requires first identifying the user, then ascertaining the roles to which the user is assigned, and finally comparing those roles to the roles that are authorized to access a resource.
In contrast, a claim is not group based, rather it is identity based.
from Microsoft documentation:
When an identity is created it may be assigned one or more claims issued by a trusted party. A claim is a name value pair that represents what the subject is, not what the subject can do.
A security check can later determine the right to access a resource based on the value of one or more claims.
You can use both in concert, or use one type in some situations and the other in other situations. It mostly depends on the inter-operation with other systems and your management strategy. For example, it might be easier for a manager to manage a list of users assigned to a role than it is to manage who has a specific Claim assigned. Claims can be very useful in a RESTful scenario where you can assign a claim to a client, and the client can then present the claim for authorization rather than passing the Username and Password for every request.
As #Claies perfectly explained, claims could be a more descriptive and is a deep kind of role. I think about them as your role's ids. I have a gym Id, so I belong to the members role. I am also in the kickboxing lessons, so I have a kickboxing Id claim for them. My application would need the declaration of a new role to fit my membership rights. Instead, I have ids for each group class that I belong to, instead of lots of new membership types. That is why claims fit better for me.
There is a a great explanation video of Barry Dorrans, talking about the advantage of using claims over roles. He also states that roles, are still in .NET for backward compatibility. The video is very informative about the way claims, roles, policies, authorization and authentication works.
Or check a related session shared by Lafi
Having used various authentication and authorisation techniques over decades, my current MVC application uses the following methodology.
Claims are used for all authorisation. Users are assigned one role (multiple roles are possible but I do not need this) - more below.
As is common practice, A ClaimsAuthorize attribute class is used. Since most controller actions are CRUD, I have a routine in the code-first database generation that iterates all controller actions and creates claim types for each controller action attribute of Read/Edit/Create/Delete. E.g. from,
[ClaimsAuthorize("SomeController", "Edit")]
[HttpPost]
For use at in an MVC View, a base controller class presents view bag items
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// get user claims
var user = filterContext.HttpContext.User as System.Security.Claims.ClaimsPrincipal;
if (user != null)
{
// Get all user claims on this controller. In this controler base class, [this] still gets the descendant instance type, hence name
List<Claim> claims = user.Claims.Where(c => c.Type == this.GetType().Name).ToList();
// set Viewbag with default authorisations on this controller
ViewBag.ClaimRead = claims.Any(c => c.Value == "Read");
ViewBag.ClaimEdit = claims.Any(c => c.Value == "Edit");
ViewBag.ClaimCreate = claims.Any(c => c.Value == "Create");
ViewBag.ClaimDelete = claims.Any(c => c.Value == "Delete");
}
base.OnActionExecuting(filterContext);
}
For website menus and other non-controller actions, I have other claims. E.g. whether a user can view a particular monetary field.
bool UserHasSpecificClaim(string claimType, string claimValue)
{
// get user claims
var user = this.HttpContext.User as System.Security.Claims.ClaimsPrincipal;
if (user != null)
{
// Get the specific claim if any
return user.Claims.Any(c => c.Type == claimType && c.Value == claimValue);
}
return false;
}
public bool UserHasTradePricesReadClaim
{
get
{
return UserHasSpecificClaim("TradePrices", "Read");
}
}
So where do Roles fit in?
I have a table that links a Role to a (default) set of claims. When setting user authorisation, the default is to give the user the claims of their role. Each user can have more or less claims than the default. To make editing simple, the claims list is show by controller and actions (in a row), with other claims then listed. Buttons are used with a bit of Javascript to select a set of actions to minimise the "clicking" required to select claims. On Save, the users claims are deleted and all of the selected claims are added. The web application loads claims only once, so any changes must prompt a reload within this static data.
Managers can therefore select which claims are in each role and which claims a user has after setting them to a role and those default claims. The system has only a small number of users so managing this data is straightforward
To understand the difference between Roles and Claims you must face the limitation of roles and feel how claims come over these issues, so let me give you 2 scenarios to recognize the power of claims where role can't resolve these issues :
1- Your site has two modules (pages, service ..etc) the first module for children (under 18 years old) the other for adults (over 18 years old)
your user identity has a birthday claim
You need to create a policy on this claim so the authorization for each module will be given on this value and if the age of the user is over 18 years then he can go to the adult module and not before this age.
Role is Boolean data type you can have or not have the role, it doesn't have multi values.
2- Your site has role user and you want to prevent access of users to make some maintenance without changing the code.
In claims, you can create an UnderConstrain policy that if true the user can't view the page give property authorize for role user.
At the time of writing this answer we were at '.NET 5.0' with '.NET 6.0' just around the corner. And this is my understanding of what I've seen:
Q: Do we no longer use Roles?
Yep, you're not supposed to use Roles any longer (at least not the way you did it in the previous frameworks.
Q: If so, why are Roles still offered?
To make upgrading projects easier/faster?
Q: Should we only use Claims?
yes. But be sure to check out the video posted here in the answer by #Jonathan Ramos.
Q: Should we use Roles & Claims together?
No, but you can put a role into a claim ofcourse, but be sure to upgrade your project to use Claims only.
And you should not have to write you're own attributes, you should use policy for that, as it's the way of the newer framework. If you need you're own attributes you're "doing it wrong", just create your own Requirement(handler) that's what the whole 'new' policy is all about.
In the current framework the attribute ClaimAuthorize is not even available anymore.

Spring Security in Grails providing authorization

A suggestion here would be deeply appreciated.
We use Spring Security domain object security to lock down access to specific objects in our Grails application. We have extended permissions as well. We use normal #PreAuthorize annotation to control access to the domain objects depending up the privileges assigned to a specific user.
In this architecture, I want for one user to be able to invite a second user to join a group. To do this, the second user receives an invitation from the first user to join a group with specific privileges. The second user can choose to accept or reject the invitation.
Given that the domain object belongs to the first user, not the second user, how could I grant access to the second user to the domain object with the privileges offered?
I have tried to hack a solution using #PreAuthorize("permitAll") on a service method just to see if that would work. While not ask secure as granting an object the privilege to set privileges to a domain object, it at least would get me going. But no joy, I continue to get "accessDenied for class" errors, presumably because the current user is the second user, not the domain object owner.
Do I need to work through the SpEL suggestion here? I barely understand how the bean resolver works unfortunately.
Edit: Even when I verify the invitation is valid at invocation Spring ACL throws an exception when the first ACE for the new user is attempted to be inserted. The exception occurs in void setPermissions(ObjectIdentity oid, recipient, Collection permissions) at the insertAce call:
void setPermissions(ObjectIdentity oid, recipient, Collection permissions) {
Sid sid = createSid(recipient)
MutableAcl acl
try {
acl = aclService.readAclById(oid)
}
catch (NotFoundException e) {
acl = aclService.createAcl(oid)
}
int deleted = 0
acl.entries.eachWithIndex { AccessControlEntry ace, int i ->
if (ace.sid == sid) {
acl.deleteAce(i-deleted)
deleted++
}
}
permissions.each {
acl.insertAce(acl.entries.size(), it, sid, true)
}
aclService.updateAcl acl
}
I assume that the access is denied because the current user (who did not exist when the invitation was issued) does not have the rights to set permissions on an object owned by another user.
You can use your Role class not only for generic roles (Admin,User, etc.), but for application specific ones as well. Simply allow the user to create a Role for a resource and then allow their invitees to be granted that role. Spring Security comes with a handy ifAnyGranted() method, which accepts a comma-delimited String of role names. At a resource entry-point simply ensure that a particular role is granted:
class Conversation{
Role role
}
class ConversationController{
def enterConversation(){
// obtain conversation instance
if(!SpringSecurityUtils.ifAnyGranted(conversationInstance.role.authority){response.sendError(401)}
}
}
The answer turned out to be using RunAs. For Grails, I did this as follows:
Create a Role specific for allowing invited users to act as an administrator in order to access a protected object. In Bootstrap, ensure this role is loaded into the SecRole domain:
def invitedRole = SecRole.findByAuthority('ROLE_RUN_AS_INVITED_USER')
if (!invitedRole) {
invitedRole = new SecRole()
invitedRole.authority = "ROLE_RUN_AS_INVITED_USER"
invitedRole.save(failOnError:true, flush:true)
}
Ensure in config.groovy that the role can change the target object:grails.plugins.springsecurity.acl.authority.changeAclDetails = 'ROLE_RUN_AS_INVITED_USER'
Enable RunAs in config.groovy
grails.plugins.springsecurity.useRunAs = true
grails.plugins.springsecurity.runAs.key = [key]
annotate the service method
#PreAuthorize([check that this is indeed an invited user])
#Secured(['ROLE_USER', 'RUN_AS_INVITED_USER'])
and it all works. The trick was to make the ROLE_RUN_AS_INVITED_USER able to change acl's.
Reference:
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/runas.html
http://grails-plugins.github.io/grails-spring-security-acl/docs/manual/guide/2.%20Usage.html#2.5%20Run-As%20Authentication%20Replacement

Resources