Mpuza Sign InMpuza Sign Indocs
Developer guide

Sign in with Mpuza

Let people sign in to your application with their Mpuza account: how to set it up, build it and test it.

What you are going to do

You will put a Sign in with Mpuza button in your application. A person chooses it, signs in at Mpuza with their password, Google or GitHub, sees what your application asks for, and comes back to your application signed in. Your application never sees their password.

What you need before you start
  • A Mpuza account with a confirmed email address. You can make one on the way.
  • An application with a server. An application that is only a web page, a mobile app or a desktop app cannot use this.
  • An https address for your application. To test on your own computer, http://localhost is enough.
What you will have at the end
  • Your application registered at Mpuza, with its client ID and secret.
  • People signing in to your application with their Mpuza account, and the information they allowed.
  • A tested sign-in that you can ask the Mpuza team to make live for everyone.

Start here

  1. Log inWith your Mpuza account.
  2. Create your applicationIn the box under Register your application. You get your client ID and secret.
  3. Set your valuesType them once, or let creating fill them in. The code examples then show yours.
  4. Try the sign-in nowNothing to set: it uses the guide's own test application.
  5. Test your own applicationDownload your settings file and run the example application with it.

The example we use in this guide

The whole guide follows one made-up application, called My Shop, from the first step to the last. Where you see one of these values, use your own. For the client ID, the secret and the two return addresses, type yours once in Your values (step 2) and the code examples change by themselves.

What it isIn this guideIn your application
The applicationMy ShopThe name people see when they sign in.
Mpuza's addresshttps://accounts.mpuza.comKeep it as it is.
Return addresshttps://myapp.example.com/auth/mpuza/callbackThe page of your application where people come back.
Sign-out return addresshttps://myapp.example.com/loginThe page where people come back after signing out.
Return address on your computerhttp://localhost:3000/callbackOnly for testing.
Client IDYOUR_CLIENT_IDYours starts with mpz_. You get it in step 1.
Client secretmpzs_...Yours starts with mpzs_. Keep it on your server only.
What My Shop asks foropenid profile emailThe name and email. Add a scope for each other group of information you need.
The person who signs inAline Uwase, aline@example.comWhoever signs in to your application.
Values made new for each sign-inRANDOM_STATE, RANDOM_NONCE, YOUR_CODE_VERIFIERYour server makes them. Step 3 says how.
Values Mpuza gives backTHE_CODE, THE_ID_TOKEN, THE_ACCESS_TOKENYou get them in step 4.

The steps, in order

Do them from 1 to 9. Under each name is what you do there. Choose a step to go to it.

  1. 1Register your applicationGive Mpuza the name of your application and its return addresses. You get a client ID and a secret.
  2. 2Add your settingsPut your client ID, secret and return address in your server's settings. The other settings are the same for everyone.discovery
  3. 3Send the person to sign inWhen a person chooses Sign in with Mpuza, your server sends their browser to Mpuza.GET /oauth/authorize
  4. 4Handle the answerThe person comes back with a code. Your server swaps it for an ID token and an access token.POST /oauth/token
  5. 5Check the ID tokenMake sure the ID token really comes from Mpuza, is meant for your application and has not run out.jwks.json
  6. 6Match the person to your accountFind the person in your own application using their Mpuza id (sub), and read the information they allowed.
  7. 7Sign out optionalEnd the session in your application, and at Mpuza too if you want.GET /oauth/logout
  8. 8Test your integrationRun a whole sign-in with a test application before other people use it.
  9. 9Go live: the Mpuza team approvesAsk to go live. After the Mpuza team approves, everyone with a Mpuza account can sign in.

How it works

People sign in to your application with their Mpuza account. Your application never sees their password.

It is standard OpenID Connect, so it works in any language with a server, and a maintained OpenID Connect library can do most of it.

  1. A person chooses Sign in with Mpuza in your application.
  2. Your server sends their browser to Mpuza.
  3. They sign in there with their password, Google or GitHub.
  4. Mpuza sends the browser back to your application with a code that works once, for 60 seconds.
  5. Your server exchanges the code for a signed ID token, checks it, and starts your own session.
Your application needs a server. The client secret must never be in a web page, a mobile app or a desktop app. Applications without a server are not supported. This sign-in is for the people who use your application; it does not use your Mpuza AI Portal API key and secret key.

What information you get

Signing in tells your application who the person is. It is the same for every Mpuza account: a candidate, a company admin, an employee or any other user.

FieldAsk forWhat it isExample
subopenidThe person's Mpuza ID. It never changes: save it, and find the person by it.3f8a1c2e-5b7d-4e19-9a64-0c2f8d1b7e35
emailemailTheir email address. A person can change it, so do not use it as their ID.aline@example.com
email_verifiedemailWhether the email address is confirmed. Check that it is true before you rely on the address.true
nameprofileTheir full name.Aline Uwase
given_nameprofileTheir first name.Aline
family_nameprofileTheir last name.Uwase
A part of the name is left out when the account does not have it. Your application should still work without it.

What each request gives you

You choose with scope when you send the person to sign in. Always include openid. You get only what you ask for.

scopeYou get
openidsub
openid emailsub, email, email_verified
openid profilesub, name, given_name, family_name
openid profile emailAll six fields

Anything Mpuza does not offer, such as address or offline_access, is ignored: you get no extra data and no refresh token.

Where you read it

Inside an ID token, with scope openid profile email (an example person)
{
  "sub": "3f8a1c2e-5b7d-4e19-9a64-0c2f8d1b7e35",
  "email": "aline@example.com",
  "email_verified": true,
  "name": "Aline Uwase",
  "given_name": "Aline",
  "family_name": "Uwase",

  "iss": "https://accounts.mpuza.com",
  "aud": "YOUR_CLIENT_ID",
  "nonce": "RANDOM_NONCE",
  "iat": 1899996400,
  "exp": 1900000000
}

The fields iss, aud, nonce, iat and exp are about the sign-in itself, not about the person. You use them to check the token.

More information, when the Mpuza team approves it

Your application can also receive more of the person's Mpuza account, one group at a time. Nothing in this table is given just because you ask for it.

GroupscopeWhat is in itWhere it arrives
Profilempuza:profilePhoto, headline, about, degree, field of study, licence, profile views and languagesmpuza_profile
Contact and locationmpuza:contactPhone number, country, city, province, district, sector, cell and villagempuza_contact
Careermpuza:careerWork experience, education, certificates and skillsmpuza_career
Your companiesmpuza:companyFor each company you own, administer or work for: its name, your roles (owner, admin, employee), your position, type of work and start datempuza_companies
Company detailsmpuza:company_detailsLogo, tagline, description, slogan, mission, vision, industry, type, location, website, phone, email, number of employees, year founded, specialization and whether Mpuza verified itmpuza_companies
Personal details Sensitivempuza:personalDate of birth, whether you are Rwandan, expected salary and job preferencesmpuza_personal
Licences and permits Sensitivempuza:permitsDriving licences, and work permits with the passport numbermpuza_permits
References Sensitivempuza:referencesThe names, emails, phone numbers, companies, positions and relationship of the people you listed as referencesmpuza_references
Job activity Sensitivempuza:activityYour job applications (job, organization, date, your expected salary, and the status once it is published or withdrawn) and your saved jobsmpuza_activity
Account detailsmpuza:accountDate you joined, last sign-in, and how you signed upmpuza_account
The groups marked Sensitive hold private information, such as job applications and permits, and References name other people. Ask for one only when your application cannot work without it, keep it no longer than you need it, and protect it.
  1. Tick the information your application needs when you create it (in the box of step 1 here, or on your developer dashboard), and change it later with Change on the dashboard. All boxes start ticked.
  2. The Mpuza team looks at it and approves each group. View details on your dashboard then shows the scope to use.
  3. Add the approved scopes to your sign-in link, after openid profile email.
  4. The person sees each group you ask for with a tick box, unticks what they do not want to share, and presses Allow or Cancel. Every box starts ticked; private groups are marked in red. Name and email are always part of signing in.
  5. Read it with the user info call (step 6). It is never in the ID token.
The person can untick any group. The sign-in still works: that group is simply missing from the user info, and the scope in the token answer lists what you were really given. Check it, and let your application work without any of them. To choose again, a person signs out at Mpuza and signs in once more.

Asking for a group that is not approved for your application ends the sign-in with error=invalid_scope. If the team takes a group away, it stops at once, also for access tokens you already have.

The person's privacy switches on their Mpuza profile still apply: a hidden section is not sent, and the phone number is sent only when they chose to show it. Anything an account does not have is left out, so your application must work without it.

User info with scope openid profile email mpuza:profile mpuza:contact mpuza:career mpuza:company (an example person)
{
  "sub": "3f8a1c2e-5b7d-4e19-9a64-0c2f8d1b7e35",
  "email": "aline@example.com",
  "email_verified": true,
  "name": "Aline Uwase",
  "mpuza_profile": { "headline": "Software engineer", "degree": "BSc", "languages": [{ "name": "English", "speaking": "Good" }] },
  "mpuza_contact": { "country": "RW", "city": "Kigali" },
  "mpuza_career": {
    "experience": [{ "company": "Example Ltd", "position": "Developer", "current": true, "start": "2024-01-05", "verified": true }],
    "education": [], "certificates": [], "skills": [{ "name": "Node.js", "years": 3, "verified": true }]
  },
  "mpuza_companies": [{ "id": "...", "name": "Example Ltd", "roles": ["employee"], "position": "Developer" }]
}

In mpuza_companies, roles holds owner, admin or employee. A company is listed only when the person owns it, is an active administrator of it, or works there now. mpuza:company_details adds details to each of them, and brings mpuza:company with it.

See all of your own information

Sign in with your Mpuza account. Every box starts ticked: untick what you do not want to see. What stays ticked is then shown here, only to you. What you have hidden on your Mpuza profile does not appear.

Show my information

Every field, one by one

At every log in and sign up, user info sends all the fields of every group that was approved, asked for and left ticked. With every group approved and every box ticked, that is all of the fields below that the person has.

A field the person has nothing for is not sent: it is not there at all, not empty. This is so for a new account, whose profile is mostly empty, and for sections the person hid. Treat a missing field as empty in your registration form.

112 fields in all. [] marks a list, with one entry for each thing the person has.

Name and email 6 fields, scope openid profile email
FieldWhat it isExample
subThe Mpuza ID. It never changes3f8a1c2e-5b7d-4e19-9a64-0c2f8d1b7e35
emailEmail addressaline@example.com
email_verifiedWhether the email is confirmedtrue
nameFull nameAline Uwase
given_nameFirst nameAline
family_nameLast nameUwase
Profile 12 fields, scope mpuza:profile
FieldWhat it isExample
mpuza_profile.photoAddress of the profile photohttps://api.example.com/api/profile/profiles?p=photo.png
mpuza_profile.headlineHeadlineSoftware engineer
mpuza_profile.aboutAbout the personI build web applications.
mpuza_profile.degreeDegreeBSc
mpuza_profile.field_of_studyField of studyComputer Science
mpuza_profile.licenseThe licence field of the profileProfessional engineer
mpuza_profile.profile_viewsHow often the profile was seen14
mpuza_profile.languages[].nameLanguageEnglish
mpuza_profile.languages[].readingLevel in readingGood
mpuza_profile.languages[].writingLevel in writingGood
mpuza_profile.languages[].listeningLevel in listeningGood
mpuza_profile.languages[].speakingLevel in speakingGood
Contact and location 8 fields, scope mpuza:contact
FieldWhat it isExample
mpuza_contact.phone_numberPhone number, only when the person shows it on the profile+250 700 000 000
mpuza_contact.countryCountryRW
mpuza_contact.provinceProvinceKigali City
mpuza_contact.districtDistrictGasabo
mpuza_contact.sectorSectorRemera
mpuza_contact.cellCellRukiri
mpuza_contact.villageVillageAmahoro
mpuza_contact.cityCityKigali
Career 35 fields, scope mpuza:career
FieldWhat it isExample
mpuza_career.experience[].companyWhere they workedExample Ltd
mpuza_career.experience[].positionJobDeveloper
mpuza_career.experience[].employment_typeType of workFull-time
mpuza_career.experience[].currentWhether they work there nowtrue
mpuza_career.experience[].startStart date2024-01-05
mpuza_career.experience[].endEnd date, when not current2025-06-30
mpuza_career.experience[].company_websiteWebsite of the employerhttps://example.com
mpuza_career.experience[].industryIndustryTechnology
mpuza_career.experience[].locationPlaceKigali
mpuza_career.experience[].descriptionWhat they didBuilt the web application.
mpuza_career.experience[].skillsSkills used["Node.js"]
mpuza_career.experience[].verifiedWhether it was verifiedtrue
mpuza_career.education[].schoolSchoolSample University
mpuza_career.education[].degreeDegreeBSc
mpuza_career.education[].field_of_studyField of studyComputer Science
mpuza_career.education[].startStart date2019-09-01
mpuza_career.education[].endEnd date, when finished2023-06-30
mpuza_career.education[].currentWhether still studyingfalse
mpuza_career.education[].gradeGradeFirst class
mpuza_career.education[].specializationSpecializationSoftware
mpuza_career.education[].coursesCoursesDatabases, Networks
mpuza_career.education[].school_websiteWebsite of the schoolhttps://university.example.com
mpuza_career.education[].verifiedWhether it was verifiedfalse
mpuza_career.certificates[].nameCertificateCloud practitioner
mpuza_career.certificates[].organizationWho issued itExample Academy
mpuza_career.certificates[].throughHow it was earnedOnline course
mpuza_career.certificates[].expiresWhether it endstrue
mpuza_career.certificates[].valid_fromValid from2024-01-01
mpuza_career.certificates[].valid_toValid until, when it ends2027-01-01
mpuza_career.certificates[].credential_idIts numberABC-123
mpuza_career.certificates[].credential_urlWhere it can be checkedhttps://academy.example.com/ABC-123
mpuza_career.certificates[].verifiedWhether it was verifiedtrue
mpuza_career.skills[].nameSkillNode.js
mpuza_career.skills[].yearsYears of experience3
mpuza_career.skills[].verifiedWhether it was verifiedtrue
Your companies 6 fields, scope mpuza:company
FieldWhat it isExample
mpuza_companies[].idID of the company7d1f0c3a-2b4e-4a6f-8c9d-0e1f2a3b4c5d
mpuza_companies[].nameName of the companyExample Ltd
mpuza_companies[].rolesTheir roles: owner, admin, employee["employee"]
mpuza_companies[].positionTheir job there, when an employeeDeveloper
mpuza_companies[].employment_typeType of workFull-time
mpuza_companies[].sinceSince when2024-02-01
Company details 17 fields, scope mpuza:company_details
FieldWhat it isExample
mpuza_companies[].details.logoAddress of the logohttps://api.example.com/api/profile/profiles?p=logo.png
mpuza_companies[].details.taglineTaglineWe build things
mpuza_companies[].details.descriptionDescriptionA software company.
mpuza_companies[].details.sloganSloganBuild well
mpuza_companies[].details.slugShort name used in addressesexample-ltd
mpuza_companies[].details.industryIndustryTechnology
mpuza_companies[].details.typeType of companyPrivate
mpuza_companies[].details.locationPlaceKigali
mpuza_companies[].details.websiteWebsitehttps://example.com
mpuza_companies[].details.missionMissionMake hiring simple.
mpuza_companies[].details.visionVisionWork for everyone.
mpuza_companies[].details.verifiedWhether Mpuza verified the companytrue
mpuza_companies[].details.employees_numberNumber of employees12
mpuza_companies[].details.formation_yearYear founded2020
mpuza_companies[].details.specializationSpecializationWeb software
mpuza_companies[].details.phone_numberPhone of the company+250 700 000 001
mpuza_companies[].details.emailEmail of the companyhello@example.com
Personal details 4 fields, scope mpuza:personal Sensitive
FieldWhat it isExample
mpuza_personal.date_of_birthDate of birth1995-04-02
mpuza_personal.is_rwandanWhether they are Rwandantrue
mpuza_personal.expected_salaryExpected salary1000000
mpuza_personal.job_preferencesWhat jobs they look for: job types, locations, industries, company sizes, employment types, remote{"job_types":["Developer"],"locations":["Kigali"],"remote_preference":"any"}
Licences and permits 7 fields, scope mpuza:permits Sensitive
FieldWhat it isExample
mpuza_permits.driving_licences[].countryCountry of the licenceRW
mpuza_permits.driving_licences[].valid_untilValid until2030-01-01
mpuza_permits.driving_licences[].categoriesCategories["B"]
mpuza_permits.work_permits[].passport_numberPassport numberPC0000000
mpuza_permits.work_permits[].issued_byWho issued the permitDirectorate of Immigration
mpuza_permits.work_permits[].issued_onIssued on2024-01-01
mpuza_permits.work_permits[].valid_untilValid until2029-01-01
References 6 fields, scope mpuza:references Sensitive
FieldWhat it isExample
mpuza_references[].namesName of the refereeJean Referee
mpuza_references[].emailTheir emailreferee@example.com
mpuza_references[].phone_numberTheir phone number+250 700 000 002
mpuza_references[].companyTheir companyExample Ltd
mpuza_references[].positionTheir jobTeam lead
mpuza_references[].relationshipHow they know the personManager
Job activity 8 fields, scope mpuza:activity Sensitive
FieldWhat it isExample
mpuza_activity.job_applications[].job_titleJob applied forBackend developer
mpuza_activity.job_applications[].organizationOrganizationAnother Company
mpuza_activity.job_applications[].applied_onWhen they applied2026-10-02
mpuza_activity.job_applications[].expected_salarySalary they asked for900000
mpuza_activity.job_applications[].statusStatus, only once published to them, or withdrawnaccepted
mpuza_activity.saved_jobs[].job_titleSaved jobData engineer
mpuza_activity.saved_jobs[].organizationOrganizationAnother Company
mpuza_activity.saved_jobs[].saved_onWhen they saved it2026-10-05
Account details 3 fields, scope mpuza:account
FieldWhat it isExample
mpuza_account.member_sinceWhen they joined2022-03-01
mpuza_account.last_loginLast sign-in2026-11-29
mpuza_account.signed_up_withHow they signed upgoogle
One answer with every field (an example person)
{
  "sub": "3f8a1c2e-5b7d-4e19-9a64-0c2f8d1b7e35",
  "email": "aline@example.com",
  "email_verified": true,
  "name": "Aline Uwase",
  "given_name": "Aline",
  "family_name": "Uwase",
  "mpuza_profile": {
    "photo": "https://api.example.com/api/profile/profiles?p=photo.png",
    "headline": "Software engineer",
    "about": "I build web applications.",
    "degree": "BSc",
    "field_of_study": "Computer Science",
    "license": "Professional engineer",
    "profile_views": 14,
    "languages": [
      {
        "name": "English",
        "reading": "Good",
        "writing": "Good",
        "listening": "Good",
        "speaking": "Good"
      }
    ]
  },
  "mpuza_contact": {
    "phone_number": "+250 700 000 000",
    "country": "RW",
    "province": "Kigali City",
    "district": "Gasabo",
    "sector": "Remera",
    "cell": "Rukiri",
    "village": "Amahoro",
    "city": "Kigali"
  },
  "mpuza_career": {
    "experience": [
      {
        "company": "Example Ltd",
        "position": "Developer",
        "employment_type": "Full-time",
        "current": true,
        "start": "2024-01-05",
        "end": "2025-06-30",
        "company_website": "https://example.com",
        "industry": "Technology",
        "location": "Kigali",
        "description": "Built the web application.",
        "skills": [
          "Node.js"
        ],
        "verified": true
      }
    ],
    "education": [
      {
        "school": "Sample University",
        "degree": "BSc",
        "field_of_study": "Computer Science",
        "start": "2019-09-01",
        "end": "2023-06-30",
        "current": false,
        "grade": "First class",
        "specialization": "Software",
        "courses": "Databases, Networks",
        "school_website": "https://university.example.com",
        "verified": false
      }
    ],
    "certificates": [
      {
        "name": "Cloud practitioner",
        "organization": "Example Academy",
        "through": "Online course",
        "expires": true,
        "valid_from": "2024-01-01",
        "valid_to": "2027-01-01",
        "credential_id": "ABC-123",
        "credential_url": "https://academy.example.com/ABC-123",
        "verified": true
      }
    ],
    "skills": [
      {
        "name": "Node.js",
        "years": 3,
        "verified": true
      }
    ]
  },
  "mpuza_companies": [
    {
      "id": "7d1f0c3a-2b4e-4a6f-8c9d-0e1f2a3b4c5d",
      "name": "Example Ltd",
      "roles": [
        "employee"
      ],
      "position": "Developer",
      "employment_type": "Full-time",
      "since": "2024-02-01",
      "details": {
        "logo": "https://api.example.com/api/profile/profiles?p=logo.png",
        "tagline": "We build things",
        "description": "A software company.",
        "slogan": "Build well",
        "slug": "example-ltd",
        "industry": "Technology",
        "type": "Private",
        "location": "Kigali",
        "website": "https://example.com",
        "mission": "Make hiring simple.",
        "vision": "Work for everyone.",
        "verified": true,
        "employees_number": 12,
        "formation_year": 2020,
        "specialization": "Web software",
        "phone_number": "+250 700 000 001",
        "email": "hello@example.com"
      }
    }
  ],
  "mpuza_personal": {
    "date_of_birth": "1995-04-02",
    "is_rwandan": true,
    "expected_salary": "1000000",
    "job_preferences": {
      "job_types": [
        "Developer"
      ],
      "locations": [
        "Kigali"
      ],
      "remote_preference": "any"
    }
  },
  "mpuza_permits": {
    "driving_licences": [
      {
        "country": "RW",
        "valid_until": "2030-01-01",
        "categories": [
          "B"
        ]
      }
    ],
    "work_permits": [
      {
        "passport_number": "PC0000000",
        "issued_by": "Directorate of Immigration",
        "issued_on": "2024-01-01",
        "valid_until": "2029-01-01"
      }
    ]
  },
  "mpuza_references": [
    {
      "names": "Jean Referee",
      "email": "referee@example.com",
      "phone_number": "+250 700 000 002",
      "company": "Example Ltd",
      "position": "Team lead",
      "relationship": "Manager"
    }
  ],
  "mpuza_activity": {
    "job_applications": [
      {
        "job_title": "Backend developer",
        "organization": "Another Company",
        "applied_on": "2026-10-02",
        "expected_salary": "900000",
        "status": "accepted"
      }
    ],
    "saved_jobs": [
      {
        "job_title": "Data engineer",
        "organization": "Another Company",
        "saved_on": "2026-10-05"
      }
    ]
  },
  "mpuza_account": {
    "member_since": "2022-03-01",
    "last_login": "2026-11-29",
    "signed_up_with": "google"
  }
}

What you never get

Never sharedWhy
Passwords, tokens and secret codesThey protect the account. The password is typed on the Mpuza page only.
Uploaded documents, such as degrees, contracts and permitsAnyone who knows a file's address can open it, so no address of a document is given.
Other people's records, such as a company's applicants or its other employeesWorking for or owning a company does not make their information yours to share.
What employers write about an application, match scores, payments and system logsThey belong to the employer or to the running of Mpuza, not to your application.
Anything from Google or GitHubA person who signs in with them gives you only what this page lists.
What a person may do in your application is your decision. Save sub with your own account and keep their rights there. A role in a Mpuza company does not give anybody rights in your application by itself.

Before an application made by a developer learns anything, the person sees what it asks for and chooses Allow or Cancel. Every application, Mpuza's own too, has to ask before it receives more than the name and email.

Get the information when someone logs in or signs up

Log in and sign up use the same link. There is no separate sign-up call: you send the person to Mpuza, and if they have no account they make one there and carry on. What you send, and what you get back, is the same.

StepSomeone with an account (log in)New with Google or GitHub (sign up)New with email (sign up)
1. Your button sends the linkThe same linkThe same linkThe same link
2. On the Mpuza pageEmail and password, Google or GitHubContinue with Google or GitHub: Mpuza makes the account at onceCreate one: the account is made on the Mpuza website, they confirm their email, come back and sign in. The sign-in waits for one hour
3. What to shareThey see what you ask for and untick what they do not wantThe sameThe same
4. Your return address getscode and statecode and statecode and state

Where your application gets it

WhenYou sendYou get
The person comes backNothing: Mpuza sends them to your return addresscode and state
Your server swaps the code (step 4)grant_type, code, redirect_uri, code_verifier, with your client ID and secretid_token with sub, and the name and email you asked for; access_token; scope, which lists what was really allowed
Your server asks for the information (step 6)The access token, as Authorization: BearerEverything that was allowed: the name and email, and the mpuza_ fields
Choose what you need

Name and email always come with openid profile email. Everything is ticked: untick what your application does not need, and the examples below change to what you must send. Your client ID and return address are used when you have typed them in your values.

1. Send the person to Mpuza (the same for log in and sign up)

2. Swap the code that comes back (from your server)

3. Read the information (from your server)

4. Register the person in your application, or update them (your own database)

Try it with what you ticked

It uses the guide's own test application and your real answers are shown only to you. To try signing up, use the second button, then choose Create one, Google or GitHub on the Mpuza page with an account you do not have yet.

Try it: log in

Try it: sign up first signs this browser out of Mpuza, so the Mpuza page asks who you are, as it would a new person.

Register the person in your application with it

At log in and at sign up your server gets the same answer, so one piece of code does both. Step 4 of the box above writes it for the groups you ticked.

  1. Find your own account by sub. Not found: this is a new person for you.
  2. New: create the account from the answer. Show your own registration form already filled in, and ask only for what your application still needs.
  3. Found: update what you saved with what was sent now.
  4. Start your own session. What the person may do is your decision: never give rights from a Mpuza role or company.
  5. If you already have an account with the same email but no sub, read step 6 before you join them.
FromFields of your own accountWhere each is in the answer
Name and email (always)mpuza_id, email, full_name, first_name, last_namesub, email, name, given_name, family_name
Profilephoto, headline, about, degree, field_of_study, languagesmpuza_profile.photo, mpuza_profile.headline, mpuza_profile.about, mpuza_profile.degree, mpuza_profile.field_of_study, mpuza_profile.languages
Contact and locationphone, country, province, district, sector, cell, village, citympuza_contact.phone_number, mpuza_contact.country, mpuza_contact.province, mpuza_contact.district, mpuza_contact.sector, mpuza_contact.cell, mpuza_contact.village, mpuza_contact.city
Careerexperience, education, certificates, skillsmpuza_career.experience, mpuza_career.education, mpuza_career.certificates, mpuza_career.skills
Your companiescompaniesmpuza_companies
Personal detailsdate_of_birth, is_rwandan, expected_salary, job_preferencesmpuza_personal.date_of_birth, mpuza_personal.is_rwandan, mpuza_personal.expected_salary, mpuza_personal.job_preferences
Licences and permitsdriving_licences, work_permitsmpuza_permits.driving_licences, mpuza_permits.work_permits
Referencesreferencesmpuza_references
Job activityjob_applications, saved_jobsmpuza_activity.job_applications, mpuza_activity.saved_jobs
Account detailsmember_since, signed_up_with, last_loginmpuza_account.member_since, mpuza_account.signed_up_with, mpuza_account.last_login
Any of these can be missing: the person unticked the group, hid it, has nothing there, or your application is not approved for it. Your registration form must work with only the name and the email.

Save it, and keep it up to date

Changing what you get

WhoHow
Your application, to ask for more or lessChange the scope in your link. For more, tick it on your developer dashboard first and wait for the Mpuza team to approve it.
The personSigns out at Mpuza and signs in to your application again: they see the boxes again and their new choice replaces the old one. You can also add prompt=consent to your link to show the boxes again.
The Mpuza teamThe Information button on the team dashboard. A group that is taken away stops at once.

1. Register your application

Create your application here

You can also do this on your developer dashboard.

You register your application yourself. You do not need to ask anybody: all you need is a Mpuza account with a confirmed email address. You can do it in the box above, without leaving this page.

  1. Use Create your application here, above (or open https://accounts.mpuza.com/developer). Sign in with your Mpuza account; if you have none, you can make one on the way.
  2. Give the name and your return addresses, and choose Create my application.
  3. Copy the client ID (it starts with mpz_) and the client secret (it starts with mpzs_). Created here, they are filled into Your values and the examples by themselves.
What you enterRule
The name of your applicationPeople see it on the sign-in page. 2 to 60 characters. It cannot contain "Mpuza".
Your return addressesWhere the code is sent. https only; http is accepted for localhost and 127.0.0.1. They must match exactly: no * is allowed.
Your sign-out return addressesWhere people come back after signing out. Optional.
The client secret is shown only once. Keep it in your server's secret settings, never in Git. If you lose it, make a new one on the same page; the old one stops at once.

On the same page you can change the name and the addresses, make a new secret, and switch an application off and on. One account can register 10 applications. Register a second one for testing.

The first time a person signs in to your application, Mpuza asks them to allow it. The page shows your application's name, says that a developer registered it, and shows the address they go to next.

A new application is in testing: only you and the testers you list (up to 10 email addresses of Mpuza accounts) can sign in. Build and test everything this way. To let everyone sign in, the Mpuza team has to approve it: see Go live.

2. Your settings

There are two kinds of settings. A few are yours: you fill them in. All the others are already set. They are the same for every application, so do not change them.

1. Yours: you fill these in

NameWhat it isWhere you get it
Client IDThe public name of your application at Mpuza. It starts with mpz_You get it when you register your application.
Client secretThe password of your application. It starts with mpzs_ . Keep it on your server only.You get it when you register. It is shown once.
Return address (your library may call it Redirect URI)The page of your application where people come back after signing in.You choose it. Enter exactly the same address when you register.
Sign-out return address (Post-logout redirect URI), only if you want itThe page where people come back after signing out.You choose it, and enter it when you register.

Your values: type them once

They are put into the examples of this page, ready to copy. If you create your application above, they fill in by themselves. What you type here stays in your browser: it is not sent anywhere. The secret is not saved: reload the page and it is gone.

Copy this into the settings file of your server, then fill in your own values. The first line is already filled in. These are the names the example application reads; in your own application you can name them as you like.

Your settings file
# Already set: the same for everyone, do not change
MPUZA_ISSUER=https://accounts.mpuza.com

# Yours: fill these in
MPUZA_CLIENT_ID=
MPUZA_CLIENT_SECRET=
# the address of your application; the example's return address is this followed by /callback
APP_URL=http://localhost:3000

2. Already set: the same for everyone, do not change

Most libraries only ask for Mpuza's address and your own values, and set all the rest by themselves. If yours asks for one of these, use the Copy button.

Name in plain wordsName your library may useValue
Mpuza's addressIssuerhttps://accounts.mpuza.com
Mpuza's settings page, which libraries read the rest fromDiscovery URLhttps://accounts.mpuza.com/.well-known/openid-configuration
What Mpuza sends back after a sign-inResponse typecode
Extra protection for that code. It must be on.PKCE methodS256
How your server shows who it isToken endpoint authenticationclient_secret_basic
How the proof of sign-in is signedID token signatureRS256
What you ask to know about the person: who they are, name and emailScopesopenid profile email

3. Mpuza's addresses, ready to copy (also already set)

What happens thereName your library may useFull address
You send people here to sign inAuthorization endpointhttps://accounts.mpuza.com/oauth/authorize
Your server swaps the code for the proof of sign-inToken endpointhttps://accounts.mpuza.com/oauth/token
Your server can read the person's name and emailUser info endpointhttps://accounts.mpuza.com/oauth/userinfo
The keys to check that the proof is realPublic keys (JWKS URI)https://accounts.mpuza.com/.well-known/jwks.json
You send people here to sign outLogout (end session) endpointhttps://accounts.mpuza.com/oauth/logout
Your server cancels a tokenRevocation endpointhttps://accounts.mpuza.com/oauth/revoke

Read Mpuza's settings

GET https://accounts.mpuza.com/.well-known/openid-configuration

Everything that is already set, in one answer. Most libraries read it by themselves. No sign-in and no key is needed.

curl "https://accounts.mpuza.com/.well-known/openid-configuration"
const response = await fetch("https://accounts.mpuza.com/.well-known/openid-configuration");
const data = await response.json();
import requests

response = requests.get("https://accounts.mpuza.com/.well-known/openid-configuration")
data = response.json()
Try it with the documentation's own test application

Asks this Mpuza service now and shows its real answer.

Answer 200

{
  "issuer": "https://accounts.mpuza.com",
  "authorization_endpoint": "https://accounts.mpuza.com/oauth/authorize",
  "token_endpoint": "https://accounts.mpuza.com/oauth/token",
  "jwks_uri": "https://accounts.mpuza.com/.well-known/jwks.json",
  ...
}

3. Send the person to sign in

Make three new random values for every sign-in and keep them on your server.

ValueWhat it is for
stateMatches the answer to the request.
nonceComes back inside the ID token.
code_verifierFor PKCE. You send its hash first and the value itself later.
Also tie the sign-in to the browser that started it, with a cookie or an equal value, so a link made by someone else cannot sign anyone in.

Send the person to sign in

GET https://accounts.mpuza.com/oauth/authorize

Your server sends the person's browser to this address. They sign in at Mpuza and come back to your return address with a code.

What is in the address

FieldRequiredWhat it is
client_idYesYours.
redirect_uriYesYour return address, exactly as you registered it.
response_typeYesAlready set: code.
scopeYesAlready set: openid profile email.
stateYesA new random value for each sign-in.
nonceYesA new random value for each sign-in.
code_challengeYesThe SHA-256 of your new random code_verifier, in base64url.
code_challenge_methodYesAlready set: S256.

Errors: invalid_request access_denied

# open this in the person's browser
https://accounts.mpuza.com/oauth/authorize
  ?client_id=YOUR_CLIENT_ID
  &redirect_uri=https://myapp.example.com/auth/mpuza/callback
  &response_type=code
  &scope=openid profile email
  &state=RANDOM_STATE
  &nonce=RANDOM_NONCE
  &code_challenge=BASE64URL_SHA256_OF_VERIFIER
  &code_challenge_method=S256
const address = new URL("https://accounts.mpuza.com/oauth/authorize");
address.search = new URLSearchParams({
  client_id: "YOUR_CLIENT_ID",
  redirect_uri: "https://myapp.example.com/auth/mpuza/callback",
  response_type: "code",
  scope: "openid profile email",
  state: "RANDOM_STATE",
  nonce: "RANDOM_NONCE",
  code_challenge: "BASE64URL_SHA256_OF_VERIFIER",
  code_challenge_method: "S256",
});
// send the person's browser there
response.redirect(address.toString());
from urllib.parse import urlencode

address = "https://accounts.mpuza.com/oauth/authorize?" + urlencode({
    "client_id": "YOUR_CLIENT_ID",
    "redirect_uri": "https://myapp.example.com/auth/mpuza/callback",
    "response_type": "code",
    "scope": "openid profile email",
    "state": "RANDOM_STATE",
    "nonce": "RANDOM_NONCE",
    "code_challenge": "BASE64URL_SHA256_OF_VERIFIER",
    "code_challenge_method": "S256",
})
# send the person's browser there
return redirect(address)
Try it with the documentation's own test application

Takes you to the real Mpuza sign-in with your own account, and brings you back here. The steps below then show what really happened. Nothing is saved after 15 minutes.

Try it: sign in now

Answer 303

https://myapp.example.com/auth/mpuza/callback?code=...&state=RANDOM_STATE

4. Handle the answer

The browser returns to your address with code and state, or with error (for example access_denied when the person cancels).

  1. Find the sign-in by state. Refuse an unknown one, one from another browser, or one already used.
  2. From your server, exchange the code. The answer has id_token and access_token.

Swap the code for the proof of sign-in

POST https://accounts.mpuza.com/oauth/token

From your server only. You send the code with your client ID and secret, and get the ID token (the proof of who signed in) and an access token. The code works once, for 60 seconds.

What you send

FieldRequiredWhat it is
grant_typeYesAlready set: authorization_code.
codeYesThe code that came back.
redirect_uriYesThe same return address as before.
code_verifierYesThe random value whose hash you sent.

Errors: 401 invalid_client 400 invalid_grant

curl -X POST "https://accounts.mpuza.com/oauth/token" \
  -u "$MPUZA_CLIENT_ID:$MPUZA_CLIENT_SECRET" \
  --data-urlencode "grant_type=authorization_code" \
  --data-urlencode "code=THE_CODE" \
  --data-urlencode "redirect_uri=https://myapp.example.com/auth/mpuza/callback" \
  --data-urlencode "code_verifier=YOUR_CODE_VERIFIER"
const response = await fetch("https://accounts.mpuza.com/oauth/token", {
  method: "POST",
  headers: {
    Authorization: "Basic " + Buffer.from(
      process.env.MPUZA_CLIENT_ID + ":" + process.env.MPUZA_CLIENT_SECRET,
    ).toString("base64"),
  },
  body: new URLSearchParams({
    grant_type: "authorization_code",
    code: "THE_CODE",
    redirect_uri: "https://myapp.example.com/auth/mpuza/callback",
    code_verifier: "YOUR_CODE_VERIFIER",
  }),
});
const data = await response.json();
import os, requests

response = requests.post(
    "https://accounts.mpuza.com/oauth/token",
    auth=(os.environ["MPUZA_CLIENT_ID"], os.environ["MPUZA_CLIENT_SECRET"]),
    data={
        "grant_type": "authorization_code",
        "code": "THE_CODE",
        "redirect_uri": "https://myapp.example.com/auth/mpuza/callback",
        "code_verifier": "YOUR_CODE_VERIFIER",
    },
)
data = response.json()
Try it with the documentation's own test application

After you sign in with Try it above, the real exchange shows here by itself. The button sends the same code once more.

Answer 200

{
  "access_token": "...",
  "expires_in": 3600,
  "id_token": "eyJhbGciOiJSUzI1NiIs...",
  "scope": "openid profile email",
  "token_type": "Bearer"
}

5. Check the ID token

All of these must pass. A good library does them for you. Never use a token that you only decoded.

What else is inside it is listed under What information you get.

Mpuza's public keys

GET https://accounts.mpuza.com/.well-known/jwks.json

The keys that prove an ID token really comes from Mpuza. Use the one whose kid matches the token.

curl "https://accounts.mpuza.com/.well-known/jwks.json"
const response = await fetch("https://accounts.mpuza.com/.well-known/jwks.json");
const data = await response.json();
import requests

response = requests.get("https://accounts.mpuza.com/.well-known/jwks.json")
data = response.json()
Try it with the documentation's own test application

Shows the keys this Mpuza service uses now.

Answer 200

{
  "keys": [
    { "kty": "RSA", "use": "sig", "alg": "RS256", "kid": "...", "n": "...", "e": "AQAB" }
  ]
}

Your ID token, checked

GET https://accounts.mpuza.com/.well-known/jwks.json

What your code must do with the ID token: every check listed in this step. Try it shows each one on the ID token of your own sign-in.

curl "https://accounts.mpuza.com/.well-known/jwks.json"
const response = await fetch("https://accounts.mpuza.com/.well-known/jwks.json");
const data = await response.json();
import requests

response = requests.get("https://accounts.mpuza.com/.well-known/jwks.json")
data = response.json()
Try it with the documentation's own test application

Sign in with Try it above first.

Answer claims

{
  "sub": "the person's Mpuza id",
  "email": "person@example.com",
  "email_verified": true,
  "name": "...",
  "iss": "https://accounts.mpuza.com",
  "aud": "YOUR_CLIENT_ID",
  "nonce": "RANDOM_NONCE",
  "exp": 1900000000
}

6. Match the person to your own account

Read the information about the person

GET https://accounts.mpuza.com/oauth/userinfo

With the access token your server reads everything the person allowed: the name and email, and every field of the approved groups. Try it here asks for all of them.

What you send

FieldRequiredWhat it is
Authorization headerYesBearer, then the access token.

Errors: 401 invalid_token

curl "https://accounts.mpuza.com/oauth/userinfo" \
  -H "Authorization: Bearer ACCESS_TOKEN"
const response = await fetch("https://accounts.mpuza.com/oauth/userinfo", {
  headers: { Authorization: "Bearer " + accessToken },
});
const data = await response.json();
import requests

response = requests.get("https://accounts.mpuza.com/oauth/userinfo",
    headers={"Authorization": "Bearer " + access_token})
data = response.json()
Try it with the documentation's own test application

Uses the access token of your Try it sign-in. Without one you see the real answer to a made-up token.

Answer 200

{
  "sub": "...",
  "email": "person@example.com",
  "email_verified": true,
  "name": "...",
  "given_name": "...",
  "family_name": "..."
}

7. Sign out

End your own session first. To also end the Mpuza session, send the browser to the address below. The return address must be one you registered. If you do not keep the ID token, send client_id in place of id_token_hint. A person who is signed in at Mpuza is asked to confirm; if they are not signed in there, they go straight back to your address.

Sign out at Mpuza too

GET https://accounts.mpuza.com/oauth/logout

End your own session first, then send the browser here. Mpuza asks the person to confirm and sends them back to your sign-out return address.

What is in the address

FieldRequiredWhat it is
id_token_hintNoThe ID token of the sign-in. If you do not keep it, send client_id instead.
client_idNoYours, instead of id_token_hint.
post_logout_redirect_uriNoYour sign-out return address, as registered.
# open this in the person's browser
https://accounts.mpuza.com/oauth/logout
  ?id_token_hint=THE_ID_TOKEN
  &post_logout_redirect_uri=https://myapp.example.com/login
const address = new URL("https://accounts.mpuza.com/oauth/logout");
address.search = new URLSearchParams({
  id_token_hint: "THE_ID_TOKEN",
  post_logout_redirect_uri: "https://myapp.example.com/login",
});
// send the person's browser there
response.redirect(address.toString());
from urllib.parse import urlencode

address = "https://accounts.mpuza.com/oauth/logout?" + urlencode({
    "id_token_hint": "THE_ID_TOKEN",
    "post_logout_redirect_uri": "https://myapp.example.com/login",
})
# send the person's browser there
return redirect(address)
Try it with the documentation's own test application

Ends your Try it and signs you out of Mpuza in this browser. Mpuza asks you first.

Try it: sign out now

Cancel a token

POST https://accounts.mpuza.com/oauth/revoke

From your server. Makes an access token stop working before its hour is over.

What you send

FieldRequiredWhat it is
tokenYesThe token to cancel.

Errors: 401 invalid_client

curl -X POST "https://accounts.mpuza.com/oauth/revoke" \
  -u "$MPUZA_CLIENT_ID:$MPUZA_CLIENT_SECRET" \
  --data-urlencode "token=THE_ACCESS_TOKEN"
const response = await fetch("https://accounts.mpuza.com/oauth/revoke", {
  method: "POST",
  headers: {
    Authorization: "Basic " + Buffer.from(
      process.env.MPUZA_CLIENT_ID + ":" + process.env.MPUZA_CLIENT_SECRET,
    ).toString("base64"),
  },
  body: new URLSearchParams({
    token: "THE_ACCESS_TOKEN",
  }),
});
const data = response.status; // 200, with nothing in it
import os, requests

response = requests.post(
    "https://accounts.mpuza.com/oauth/revoke",
    auth=(os.environ["MPUZA_CLIENT_ID"], os.environ["MPUZA_CLIENT_SECRET"]),
    data={
        "token": "THE_ACCESS_TOKEN",
    },
)
response.status_code  # 200, with nothing in it
Try it with the documentation's own test application

Cancels the access token of your Try it sign-in.

Answer 200

(nothing)

Errors you may see

What you seeUsual cause
A Sign-in could not finish page instead of a redirectUnknown client ID, an application that is switched off, or a return address that is not exactly the registered one.
error=invalid_request back at your addressPKCE is missing or not S256.
error=invalid_scope back at your addressYou asked for information the Mpuza team has not approved for your application.
Token answer 401 invalid_clientWrong secret, or the secret was sent in the body instead of the Basic header.
Token answer 400 invalid_grantThe code was already used or is older than 60 seconds, the code_verifier or return address differ, or the account no longer exists.
This sign-in has expiredMore than an hour passed, or the page was opened in another browser.
The person is asked to allow your applicationNormal for an application a developer registers. If they choose Cancel, you get error=access_denied.
error=access_denied saying the application is still being testedThe application is not live yet and this person is not you or one of your testers.

Not offered: applications without a server (browser only, mobile, desktop), passwords sent to your application, the implicit flow, and refresh tokens (the offline_access scope has not been tested, so leave it out).

8. Test your integration

Test with a second application registered only for testing. The tests use real Mpuza accounts, so use your own.

To check that your server can reach Mpuza, run the cURL of Read Mpuza's settings and of Mpuza's public keys on it. Both must answer with JSON. To see a whole sign-in work first, use the Try it buttons.

Then run the example application at the end of this page. It needs Node 22 or later and no packages. Mpuza's address is already built into it, so you only give your client ID and secret.

  1. Register a test application at https://accounts.mpuza.com/developer with the return address http://localhost:3000/callback and the sign-out address http://localhost:3000/
  2. Save the example as node-app.js.
  3. Run it with one of the commands below, then open the address of APP_URL (http://localhost:3000 unless you changed it).
If the example works and your application does not, look at your code. If the example fails too, look at the registration and at Errors you may see.

The easiest way: set your values in step 2 (creating your application fills them in), choose Download your settings file, save mpuza.env beside node-app.js, and run this one command.

Run the example with your settings file
node --env-file=mpuza.env node-app.js

Or give the values in the command itself. They are filled in from your values.

Run the example (Git Bash, macOS or Linux)
MPUZA_CLIENT_ID=mpz_... MPUZA_CLIENT_SECRET=mpzs_... \
node node-app.js
Run the example (Windows PowerShell)
$env:MPUZA_CLIENT_ID = 'mpz_...'
$env:MPUZA_CLIENT_SECRET = 'mpzs_...'
node node-app.js

Then try each case in your own application.

What to doWhat must happen
Sign in with email and passwordYou come back signed in, with your own name and email.
Sign in with Google, and with GitHub, using the same email addressThe same account in your application every time.
Choose Cancel on the Mpuza pageYou come back with error=access_denied and are not signed in.
Type a wrong passwordYou stay on the Mpuza page. Your application is not called. After many wrong tries Mpuza makes you wait.
Reload your return address after signing inRefused: the sign-in works once.
Copy the sign-in link into another browser and finish thereYour application refuses it.
Sign out, choose Sign out on the Mpuza page, then sign in againMpuza asks for the password again.
Put a wrong client secret in your settingsNobody gets signed in, and your log shows the refusal without the secret.
Sign in as a person your application has never seen (add them as a tester)A new account with no special rights, or your own sign-up step.
Stop your application from reaching MpuzaA clear message, and your other way of signing in still works.
Sign in with an account that is neither yours nor a tester's, while in testingRefused with error=access_denied.

9. Go live

You test on your own. Only the Mpuza team can make an application live, so that everyone with a Mpuza account can sign in to it.

StageWho can sign inWhat happens next
TestingYou and your testersWhen your tests pass, choose Ask to go live on the developer page.
Waiting for the Mpuza teamYou and your testersThe team looks at the name and the addresses and approves or refuses. You can take your request back.
LiveEveryoneA new secret keeps it live. Changing the name or an address puts it back in testing.

Before you ask, check all of these.

The example application

A whole application in one file. It keeps sessions in memory to stay short; a real application keeps them, and the sign-ins that are waiting, in its database or cache.

node-app.jsDownload
// A whole application that uses Sign in with Mpuza, with nothing but Node (22 or later).
//
//   MPUZA_CLIENT_ID=mpz_... MPUZA_CLIENT_SECRET=mpzs_... node node-app.js
//
// Those two are yours. Mpuza's address is already set (MPUZA_ISSUER changes it, for trying another copy of the service only), and the
// application runs at http://localhost:3000 unless APP_URL says otherwise.
//
// Register it first with the redirect address <APP_URL>/callback and the logout address <APP_URL>/ .
// It keeps its sessions in memory to stay short. A real application keeps them in its database or cache.
import crypto from 'node:crypto';
import http from 'node:http';

// the same for everyone: do not change
const MPUZA_ADDRESS = 'https://accounts.mpuza.com';
const issuer = String(process.env.MPUZA_ISSUER || MPUZA_ADDRESS).replace(/\/+$/, '');
const clientId = process.env.MPUZA_CLIENT_ID;
const clientSecret = process.env.MPUZA_CLIENT_SECRET;
const appUrl = String(process.env.APP_URL || 'http://localhost:3000').replace(/\/+$/, '');
if (!clientId || !clientSecret) throw new Error('set MPUZA_CLIENT_ID and MPUZA_CLIENT_SECRET (you get them when you register your application)');

const redirectUri = `${appUrl}/callback`;
const secure = appUrl.startsWith('https://') ? '; Secure' : '';
const waiting = new Map(); // state -> what was made when the sign-in started
const sessions = new Map(); // session id -> the signed-in person

const random = () => crypto.randomBytes(32).toString('base64url');
const sha256 = (text) => crypto.createHash('sha256').update(text).digest('base64url');
const cookieOf = (req, name) => new RegExp(`(?:^|; )${name}=([^;]+)`).exec(req.headers.cookie || '')?.[1];
const cookie = (name, value, maxAge) => `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`;

const discovery = await (await fetch(`${issuer}/.well-known/openid-configuration`)).json();
if (discovery.issuer !== issuer) throw new Error('the discovery document names another issuer');

// Never trust an ID token before all of these have passed.
const checkIdToken = async (idToken, nonce) => {
  const [head, body, signature] = idToken.split('.');
  const header = JSON.parse(Buffer.from(head, 'base64url'));
  if (header.alg !== 'RS256') throw new Error('unexpected signature kind');
  const { keys } = await (await fetch(discovery.jwks_uri)).json();
  const jwk = keys.find((key) => key.kid === header.kid);
  if (!jwk) throw new Error('unknown signing key');
  const publicKey = crypto.createPublicKey({ key: jwk, format: 'jwk' });
  if (!crypto.verify('RSA-SHA256', Buffer.from(`${head}.${body}`), publicKey, Buffer.from(signature, 'base64url'))) throw new Error('bad signature');
  const claims = JSON.parse(Buffer.from(body, 'base64url'));
  if (claims.iss !== issuer) throw new Error('wrong issuer');
  if (claims.aud !== clientId) throw new Error('made for another application');
  if (claims.exp * 1000 <= Date.now()) throw new Error('expired');
  if (claims.nonce !== nonce) throw new Error('belongs to another sign-in');
  return claims;
};

const send = (res, status, html, headers = {}) => {
  res.writeHead(status, { 'content-type': 'text/html; charset=utf-8', ...headers });
  res.end(html);
};
const redirect = (res, location, cookies = []) => {
  res.writeHead(303, { location, ...(cookies.length ? { 'set-cookie': cookies } : {}) });
  res.end();
};
const escapeHtml = (text) => String(text).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);

const server = http.createServer(async (req, res) => {
  try {
    const url = new URL(req.url, appUrl);
    const session = sessions.get(cookieOf(req, 'session'));

    if (url.pathname === '/login') {
      const state = random();
      const nonce = random();
      const verifier = random();
      const binder = random(); // stays in this browser, so a link someone else made cannot sign anyone in
      waiting.set(state, { nonce, verifier, binder: sha256(binder), until: Date.now() + 3600000 });
      const query = new URLSearchParams({
        client_id: clientId, redirect_uri: redirectUri, response_type: 'code', scope: 'openid profile email',
        state, nonce, code_challenge: sha256(verifier), code_challenge_method: 'S256',
      });
      return redirect(res, `${discovery.authorization_endpoint}?${query}`, [cookie('binder', binder, 3600)]);
    }

    if (url.pathname === '/callback') {
      const state = url.searchParams.get('state');
      const flow = waiting.get(state);
      waiting.delete(state); // works once
      if (!flow || flow.until < Date.now() || sha256(cookieOf(req, 'binder') || '') !== flow.binder) return send(res, 401, 'This sign-in is not valid. <a href="/login">Start again</a>');
      if (url.searchParams.get('error')) return send(res, 401, `Sign-in stopped: ${escapeHtml(url.searchParams.get('error'))}`);
      const answer = await fetch(discovery.token_endpoint, {
        method: 'POST',
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
          authorization: `Basic ${Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString('base64')}`,
        },
        body: new URLSearchParams({ grant_type: 'authorization_code', code: url.searchParams.get('code'), redirect_uri: redirectUri, code_verifier: flow.verifier }),
      });
      if (!answer.ok) return send(res, 401, 'The code was not accepted. <a href="/login">Start again</a>');
      const { id_token: idToken } = await answer.json();
      const claims = await checkIdToken(idToken, flow.nonce);
      if (claims.email_verified !== true) return send(res, 403, 'Confirm your email address at Mpuza first.');
      const id = random();
      // claims.sub is the person: it never changes, an email address can
      sessions.set(id, { sub: claims.sub, email: claims.email, name: claims.name, idToken });
      return redirect(res, '/', [cookie('session', id, 8 * 3600), cookie('binder', '', 0)]);
    }

    if (url.pathname === '/logout' && session) {
      sessions.delete(cookieOf(req, 'session'));
      const query = new URLSearchParams({ id_token_hint: session.idToken, post_logout_redirect_uri: `${appUrl}/` });
      return redirect(res, `${discovery.end_session_endpoint}?${query}`, [cookie('session', '', 0)]);
    }

    return send(res, 200, session
      ? `<p>Signed in as ${escapeHtml(session.name || session.email)} (${escapeHtml(session.email)})</p><a href="/logout">Sign out</a>`
      : '<a href="/login">Sign in with Mpuza</a>');
  } catch (error) {
    console.error(error.message);
    return send(res, 500, 'The sign-in could not finish. <a href="/login">Start again</a>');
  }
});

server.listen(Number(new URL(appUrl).port) || 3000, () => console.log(`example application on ${appUrl}`));