Building User Authorization in Flutter

Efikas
2 min readApr 28, 2021
AppKnox

Many of the flutter applications require users to login with with either username and password or with their social media account. These applications require both user authentication and user authorization.

User Authorization

Authorization is the function of specifying access rights/privileges to resources, which is related to information security and computer security in general and to access control in particular (wikipedia).

User authorization can also be define as the ability of the system to give User access/privileges to some features in your application base on the role or permission given to the user.

There are different methods use in creating user authorization.

Using If-Else

some developer use the If-Else method which may be difficult to maintain if there are many user roles or permissions involve. This method require the widget to wrap in an IF statement.

Builder(
builder: (context) {
if(user.permission.contains("DELETE_POST")){
return DeletePost(postId: post.id);
}
return SizedBox();
})

Using Auth Widget

I use this method a lot by creating a wrapper widget to handle the user authorization. The wrapper widget accept required authorization and a child widget.

HasPermission(
permission: "DELETE_POST",
child: DeletePost(postId: post.id),
)

Let’s break open the HasPermission widget.

class HasPermission extends StatelessWidget {
final String permission;
Widget child = Container();
HasPermission({
@required this.permission,
@required this.child,
});
@override
Widget build(BuildContext context) {
return Consumer<AuthProvider>(
builder: (context, value, _child) {
if(value.userInfo.permissions.contains(permission)){
return child;
}
return SizedBox();
});
}
}

The HasPermission in the code above has access to the user information in the AuthProvider.

The widget accept a permission and check against the user permissions to know if the user can have access to the child widget.

Usage

Now, to use the HasPermission widget, we pass the permission string and the child widget to it.

HasPermission(
permission: "DELETE_POST",
child: DeletePost(postId: post.id),
),

Conclusion

Code readability and maintenance has always been a must in software development. Splitting your code into smaller widgets help abstract some functionalities and make the code more readable.

Don’t forget to always give a descriptive name to your widgets.

--

--

Efikas

Flutter Enthusiast, Writer, Health Researcher, Affiliate Marketer