Student teaching - JWT Roles for User / Admin user


checkpoint A

Published on January 12, 2024 by

APCSP Student Teaching JWT Roles

5 min READ

JWT Roles for User / Admin user

What JWT Roles do

  • JWT (JSON Web Token) roles are used to define the permissions and access levels of a user within a system.
  • Roles help in implementing role-based access control, where different users may have different levels of access based on their roles.

User Roles

What is it?

  • The “User” role is assigned to regular individuals who have registered or signed up for an account in the application or system.
  • Permission:
    • Access to basic features and functionalities of the application.
    • The ability to create, update, and delete their own content
    • Limited or no access to sensitive/administrative functionalities.

image.png

How to implement Roles into user login

Add a _role column to DB

Add role to User table with a default value of “User”. The role attribute is set during the initialization of the User object. The is_admin method checks if the user has the role of an admin.

What this will do is differentiate between if a user that logs in will be granted regular user permissions, or will have admin permissions.

this will be put in model/users.py

class User(db.Model):
    # ... (existing code)

    _role = db.Column(db.String(20), default="User", nullable=False)

    def __init__(self, name, uid, password="123qwerty", dob=date.today(), role="User"):
        # ... (existing code)
        self._role = role

    @property
    def role(self):
        return self._role

    @role.setter
    def role(self, role):
        self._role = role

    def is_admin(self):
        return self._role == "Admin"
    
    # ... (existing code)

    # CRUD read converts self to dictionary
    # returns dictionary
    def read(self):
        return {
            "id": self.id,
            "name": self.name,
            "uid": self.uid,
            "dob": self.dob,
            "age": self.age,
            "role": self.role,
            "posts": [post.read() for post in self.posts]
        }

JWT for Admin users

What is JWT for Admin Users?

  • JWT can be used to handle user roles, including those for administrative users. JWTs are widely used for authentication and authorization in web applications. Roles in JWTs are often represented as claims, which are assertions about a subject.


What specifically can Admin users do with JWT Roles?

  • Here are some common features and rights that administrative users may have:
    • User Management
      • Create, update, or delete user accounts.
      • Reset passwords or change user credentials.
      • Manage user roles and permissions.
    • Content Management
      • Create, edit, or delete content on the platform.
      • Moderate user-generated content.
      • Manage and organize data within the application.
    • Audit Trails
      • View logs and audit trails for system activities.
      • Monitor and investigate user actions.
    • Security Management
      • Implement and oversee security measures.
      • Respond to security incidents and vulnerabilities.

Make one of the users have an admin role

def initUsers():
    with app.app_context():
        """Create database and tables"""
        db.create_all()
        """Tester data for table"""
        u1 = User(name='Thomas Edison', uid='toby', password='123toby', dob=date(1847, 2, 11), role="Admin")a

# ... (existing code)

Change token payload to include role

this will go in api/users.py.

    class _Security(Resource):
        def post(self):
            try:
                body = request.get_json()
                if not body:
                    return {
                        "message": "Please provide user details",
                        "data": None,
                        "error": "Bad request"
                    }, 400
                ''' Get Data '''
                uid = body.get('uid')
                if uid is None:
                    return {'message': f'User ID is missing'}, 400
                password = body.get('password')
                
                ''' Find user '''
                user = User.query.filter_by(_uid=uid).first()
                if user is None or not user.is_password(password):
                    return {'message': f"Invalid user id or password"}, 400
                if user:
                    try:
                        token_payload = {
                            "_uid": user._uid,
                            "role": user.role  # Add the role information to the token
                        }

                        token = jwt.encode(
                            token_payload,
                            current_app.config["SECRET_KEY"],
                            algorithm="HS256"
                        )
# ... (existing code)