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.
- 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.
- 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
- Log inWith your Mpuza account.
- Create your applicationIn the box under Register your application. You get your client ID and secret.
- Set your valuesType them once, or let creating fill them in. The code examples then show yours.
- Try the sign-in nowNothing to set: it uses the guide's own test application.
- 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 is | In this guide | In your application |
|---|---|---|
| The application | My Shop | The name people see when they sign in. |
| Mpuza's address | https://accounts.mpuza.com | Keep it as it is. |
| Return address | https://myapp.example.com/auth/mpuza/callback | The page of your application where people come back. |
| Sign-out return address | https://myapp.example.com/login | The page where people come back after signing out. |
| Return address on your computer | http://localhost:3000/callback | Only for testing. |
| Client ID | YOUR_CLIENT_ID | Yours starts with mpz_. You get it in step 1. |
| Client secret | mpzs_... | Yours starts with mpzs_. Keep it on your server only. |
| What My Shop asks for | openid profile email | The name and email. Add a scope for each other group of information you need. |
| The person who signs in | Aline Uwase, aline@example.com | Whoever signs in to your application. |
| Values made new for each sign-in | RANDOM_STATE, RANDOM_NONCE, YOUR_CODE_VERIFIER | Your server makes them. Step 3 says how. |
| Values Mpuza gives back | THE_CODE, THE_ID_TOKEN, THE_ACCESS_TOKEN | You 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.
- 1Register your applicationGive Mpuza the name of your application and its return addresses. You get a client ID and a secret.
- 2Add your settingsPut your client ID, secret and return address in your server's settings. The other settings are the same for everyone.
discovery - 3Send the person to sign inWhen a person chooses Sign in with Mpuza, your server sends their browser to Mpuza.
GET /oauth/authorize - 4Handle the answerThe person comes back with a code. Your server swaps it for an ID token and an access token.
POST /oauth/token - 5Check the ID tokenMake sure the ID token really comes from Mpuza, is meant for your application and has not run out.
jwks.json - 6Match the person to your accountFind the person in your own application using their Mpuza id (sub), and read the information they allowed.
- 7Sign out optionalEnd the session in your application, and at Mpuza too if you want.
GET /oauth/logout - 8Test your integrationRun a whole sign-in with a test application before other people use it.
- 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.
- A person chooses Sign in with Mpuza in your application.
- Your server sends their browser to Mpuza.
- They sign in there with their password, Google or GitHub.
- Mpuza sends the browser back to your application with a code that works once, for 60 seconds.
- Your server exchanges the code for a signed ID token, checks it, and starts your own session.
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.
| Field | Ask for | What it is | Example |
|---|---|---|---|
| sub | openid | The person's Mpuza ID. It never changes: save it, and find the person by it. | 3f8a1c2e-5b7d-4e19-9a64-0c2f8d1b7e35 |
| Their email address. A person can change it, so do not use it as their ID. | aline@example.com | ||
| email_verified | Whether the email address is confirmed. Check that it is true before you rely on the address. | true | |
| name | profile | Their full name. | Aline Uwase |
| given_name | profile | Their first name. | Aline |
| family_name | profile | Their last name. | Uwase |
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.
| scope | You get |
|---|---|
| openid | sub |
| openid email | sub, email, email_verified |
| openid profile | sub, name, given_name, family_name |
| openid profile email | All 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
- In the ID token you get when you swap the code. Check the token first (step 5).
- From the user info call, with the access token. It gives the same fields.
{
"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.
| Group | scope | What is in it | Where it arrives |
|---|---|---|---|
| Profile | mpuza:profile | Photo, headline, about, degree, field of study, licence, profile views and languages | mpuza_profile |
| Contact and location | mpuza:contact | Phone number, country, city, province, district, sector, cell and village | mpuza_contact |
| Career | mpuza:career | Work experience, education, certificates and skills | mpuza_career |
| Your companies | mpuza:company | For each company you own, administer or work for: its name, your roles (owner, admin, employee), your position, type of work and start date | mpuza_companies |
| Company details | mpuza:company_details | Logo, tagline, description, slogan, mission, vision, industry, type, location, website, phone, email, number of employees, year founded, specialization and whether Mpuza verified it | mpuza_companies |
| Personal details Sensitive | mpuza:personal | Date of birth, whether you are Rwandan, expected salary and job preferences | mpuza_personal |
| Licences and permits Sensitive | mpuza:permits | Driving licences, and work permits with the passport number | mpuza_permits |
| References Sensitive | mpuza:references | The names, emails, phone numbers, companies, positions and relationship of the people you listed as references | mpuza_references |
| Job activity Sensitive | mpuza:activity | Your job applications (job, organization, date, your expected salary, and the status once it is published or withdrawn) and your saved jobs | mpuza_activity |
| Account details | mpuza:account | Date you joined, last sign-in, and how you signed up | mpuza_account |
- 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.
- The Mpuza team looks at it and approves each group. View details on your dashboard then shows the scope to use.
- Add the approved scopes to your sign-in link, after openid profile email.
- 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.
- Read it with the user info call (step 6). It is never in the ID token.
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.
{
"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.
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.
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
| Field | What it is | Example |
|---|---|---|
| sub | The Mpuza ID. It never changes | 3f8a1c2e-5b7d-4e19-9a64-0c2f8d1b7e35 |
| Email address | aline@example.com | |
| email_verified | Whether the email is confirmed | true |
| name | Full name | Aline Uwase |
| given_name | First name | Aline |
| family_name | Last name | Uwase |
Profile 12 fields, scope mpuza:profile
| Field | What it is | Example |
|---|---|---|
| mpuza_profile.photo | Address of the profile photo | https://api.example.com/api/profile/profiles?p=photo.png |
| mpuza_profile.headline | Headline | Software engineer |
| mpuza_profile.about | About the person | I build web applications. |
| mpuza_profile.degree | Degree | BSc |
| mpuza_profile.field_of_study | Field of study | Computer Science |
| mpuza_profile.license | The licence field of the profile | Professional engineer |
| mpuza_profile.profile_views | How often the profile was seen | 14 |
| mpuza_profile.languages[].name | Language | English |
| mpuza_profile.languages[].reading | Level in reading | Good |
| mpuza_profile.languages[].writing | Level in writing | Good |
| mpuza_profile.languages[].listening | Level in listening | Good |
| mpuza_profile.languages[].speaking | Level in speaking | Good |
Contact and location 8 fields, scope mpuza:contact
| Field | What it is | Example |
|---|---|---|
| mpuza_contact.phone_number | Phone number, only when the person shows it on the profile | +250 700 000 000 |
| mpuza_contact.country | Country | RW |
| mpuza_contact.province | Province | Kigali City |
| mpuza_contact.district | District | Gasabo |
| mpuza_contact.sector | Sector | Remera |
| mpuza_contact.cell | Cell | Rukiri |
| mpuza_contact.village | Village | Amahoro |
| mpuza_contact.city | City | Kigali |
Career 35 fields, scope mpuza:career
| Field | What it is | Example |
|---|---|---|
| mpuza_career.experience[].company | Where they worked | Example Ltd |
| mpuza_career.experience[].position | Job | Developer |
| mpuza_career.experience[].employment_type | Type of work | Full-time |
| mpuza_career.experience[].current | Whether they work there now | true |
| mpuza_career.experience[].start | Start date | 2024-01-05 |
| mpuza_career.experience[].end | End date, when not current | 2025-06-30 |
| mpuza_career.experience[].company_website | Website of the employer | https://example.com |
| mpuza_career.experience[].industry | Industry | Technology |
| mpuza_career.experience[].location | Place | Kigali |
| mpuza_career.experience[].description | What they did | Built the web application. |
| mpuza_career.experience[].skills | Skills used | ["Node.js"] |
| mpuza_career.experience[].verified | Whether it was verified | true |
| mpuza_career.education[].school | School | Sample University |
| mpuza_career.education[].degree | Degree | BSc |
| mpuza_career.education[].field_of_study | Field of study | Computer Science |
| mpuza_career.education[].start | Start date | 2019-09-01 |
| mpuza_career.education[].end | End date, when finished | 2023-06-30 |
| mpuza_career.education[].current | Whether still studying | false |
| mpuza_career.education[].grade | Grade | First class |
| mpuza_career.education[].specialization | Specialization | Software |
| mpuza_career.education[].courses | Courses | Databases, Networks |
| mpuza_career.education[].school_website | Website of the school | https://university.example.com |
| mpuza_career.education[].verified | Whether it was verified | false |
| mpuza_career.certificates[].name | Certificate | Cloud practitioner |
| mpuza_career.certificates[].organization | Who issued it | Example Academy |
| mpuza_career.certificates[].through | How it was earned | Online course |
| mpuza_career.certificates[].expires | Whether it ends | true |
| mpuza_career.certificates[].valid_from | Valid from | 2024-01-01 |
| mpuza_career.certificates[].valid_to | Valid until, when it ends | 2027-01-01 |
| mpuza_career.certificates[].credential_id | Its number | ABC-123 |
| mpuza_career.certificates[].credential_url | Where it can be checked | https://academy.example.com/ABC-123 |
| mpuza_career.certificates[].verified | Whether it was verified | true |
| mpuza_career.skills[].name | Skill | Node.js |
| mpuza_career.skills[].years | Years of experience | 3 |
| mpuza_career.skills[].verified | Whether it was verified | true |
Your companies 6 fields, scope mpuza:company
| Field | What it is | Example |
|---|---|---|
| mpuza_companies[].id | ID of the company | 7d1f0c3a-2b4e-4a6f-8c9d-0e1f2a3b4c5d |
| mpuza_companies[].name | Name of the company | Example Ltd |
| mpuza_companies[].roles | Their roles: owner, admin, employee | ["employee"] |
| mpuza_companies[].position | Their job there, when an employee | Developer |
| mpuza_companies[].employment_type | Type of work | Full-time |
| mpuza_companies[].since | Since when | 2024-02-01 |
Company details 17 fields, scope mpuza:company_details
| Field | What it is | Example |
|---|---|---|
| mpuza_companies[].details.logo | Address of the logo | https://api.example.com/api/profile/profiles?p=logo.png |
| mpuza_companies[].details.tagline | Tagline | We build things |
| mpuza_companies[].details.description | Description | A software company. |
| mpuza_companies[].details.slogan | Slogan | Build well |
| mpuza_companies[].details.slug | Short name used in addresses | example-ltd |
| mpuza_companies[].details.industry | Industry | Technology |
| mpuza_companies[].details.type | Type of company | Private |
| mpuza_companies[].details.location | Place | Kigali |
| mpuza_companies[].details.website | Website | https://example.com |
| mpuza_companies[].details.mission | Mission | Make hiring simple. |
| mpuza_companies[].details.vision | Vision | Work for everyone. |
| mpuza_companies[].details.verified | Whether Mpuza verified the company | true |
| mpuza_companies[].details.employees_number | Number of employees | 12 |
| mpuza_companies[].details.formation_year | Year founded | 2020 |
| mpuza_companies[].details.specialization | Specialization | Web software |
| mpuza_companies[].details.phone_number | Phone of the company | +250 700 000 001 |
| mpuza_companies[].details.email | Email of the company | hello@example.com |
Personal details 4 fields, scope mpuza:personal Sensitive
| Field | What it is | Example |
|---|---|---|
| mpuza_personal.date_of_birth | Date of birth | 1995-04-02 |
| mpuza_personal.is_rwandan | Whether they are Rwandan | true |
| mpuza_personal.expected_salary | Expected salary | 1000000 |
| mpuza_personal.job_preferences | What 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
| Field | What it is | Example |
|---|---|---|
| mpuza_permits.driving_licences[].country | Country of the licence | RW |
| mpuza_permits.driving_licences[].valid_until | Valid until | 2030-01-01 |
| mpuza_permits.driving_licences[].categories | Categories | ["B"] |
| mpuza_permits.work_permits[].passport_number | Passport number | PC0000000 |
| mpuza_permits.work_permits[].issued_by | Who issued the permit | Directorate of Immigration |
| mpuza_permits.work_permits[].issued_on | Issued on | 2024-01-01 |
| mpuza_permits.work_permits[].valid_until | Valid until | 2029-01-01 |
References 6 fields, scope mpuza:references Sensitive
| Field | What it is | Example |
|---|---|---|
| mpuza_references[].names | Name of the referee | Jean Referee |
| mpuza_references[].email | Their email | referee@example.com |
| mpuza_references[].phone_number | Their phone number | +250 700 000 002 |
| mpuza_references[].company | Their company | Example Ltd |
| mpuza_references[].position | Their job | Team lead |
| mpuza_references[].relationship | How they know the person | Manager |
Job activity 8 fields, scope mpuza:activity Sensitive
| Field | What it is | Example |
|---|---|---|
| mpuza_activity.job_applications[].job_title | Job applied for | Backend developer |
| mpuza_activity.job_applications[].organization | Organization | Another Company |
| mpuza_activity.job_applications[].applied_on | When they applied | 2026-10-02 |
| mpuza_activity.job_applications[].expected_salary | Salary they asked for | 900000 |
| mpuza_activity.job_applications[].status | Status, only once published to them, or withdrawn | accepted |
| mpuza_activity.saved_jobs[].job_title | Saved job | Data engineer |
| mpuza_activity.saved_jobs[].organization | Organization | Another Company |
| mpuza_activity.saved_jobs[].saved_on | When they saved it | 2026-10-05 |
Account details 3 fields, scope mpuza:account
| Field | What it is | Example |
|---|---|---|
| mpuza_account.member_since | When they joined | 2022-03-01 |
| mpuza_account.last_login | Last sign-in | 2026-11-29 |
| mpuza_account.signed_up_with | How they signed up |
{
"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 shared | Why |
|---|---|
| Passwords, tokens and secret codes | They protect the account. The password is typed on the Mpuza page only. |
| Uploaded documents, such as degrees, contracts and permits | Anyone 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 employees | Working for or owning a company does not make their information yours to share. |
| What employers write about an application, match scores, payments and system logs | They belong to the employer or to the running of Mpuza, not to your application. |
| Anything from Google or GitHub | A person who signs in with them gives you only what this page lists. |
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.
| Step | Someone with an account (log in) | New with Google or GitHub (sign up) | New with email (sign up) |
|---|---|---|---|
| 1. Your button sends the link | The same link | The same link | The same link |
| 2. On the Mpuza page | Email and password, Google or GitHub | Continue with Google or GitHub: Mpuza makes the account at once | Create 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 share | They see what you ask for and untick what they do not want | The same | The same |
| 4. Your return address gets | code and state | code and state | code and state |
Where your application gets it
| When | You send | You get |
|---|---|---|
| The person comes back | Nothing: Mpuza sends them to your return address | code and state |
| Your server swaps the code (step 4) | grant_type, code, redirect_uri, code_verifier, with your client ID and secret | id_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: Bearer | Everything that was allowed: the name and email, and the mpuza_ fields |
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)
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: 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.
- Find your own account by sub. Not found: this is a new person for you.
- New: create the account from the answer. Show your own registration form already filled in, and ask only for what your application still needs.
- Found: update what you saved with what was sent now.
- Start your own session. What the person may do is your decision: never give rights from a Mpuza role or company.
- If you already have an account with the same email but no sub, read step 6 before you join them.
| From | Fields of your own account | Where each is in the answer |
|---|---|---|
| Name and email (always) | mpuza_id, email, full_name, first_name, last_name | sub, email, name, given_name, family_name |
| Profile | photo, headline, about, degree, field_of_study, languages | mpuza_profile.photo, mpuza_profile.headline, mpuza_profile.about, mpuza_profile.degree, mpuza_profile.field_of_study, mpuza_profile.languages |
| Contact and location | phone, country, province, district, sector, cell, village, city | mpuza_contact.phone_number, mpuza_contact.country, mpuza_contact.province, mpuza_contact.district, mpuza_contact.sector, mpuza_contact.cell, mpuza_contact.village, mpuza_contact.city |
| Career | experience, education, certificates, skills | mpuza_career.experience, mpuza_career.education, mpuza_career.certificates, mpuza_career.skills |
| Your companies | companies | mpuza_companies |
| Personal details | date_of_birth, is_rwandan, expected_salary, job_preferences | mpuza_personal.date_of_birth, mpuza_personal.is_rwandan, mpuza_personal.expected_salary, mpuza_personal.job_preferences |
| Licences and permits | driving_licences, work_permits | mpuza_permits.driving_licences, mpuza_permits.work_permits |
| References | references | mpuza_references |
| Job activity | job_applications, saved_jobs | mpuza_activity.job_applications, mpuza_activity.saved_jobs |
| Account details | member_since, signed_up_with, last_login | mpuza_account.member_since, mpuza_account.signed_up_with, mpuza_account.last_login |
Save it, and keep it up to date
- Save it on your server with the person, and find the person by sub. Do it each time someone logs in or signs up.
- Right after a sign up the Mpuza profile is mostly empty: expect only the name and email. More arrives at later sign-ins, as the person fills in their profile.
- Mpuza does not send changes by itself. You read the newest information by calling user info again while the access token works (one hour), or when the person signs in again.
- Replace what you saved with the newest answer. When a field you had is missing, the person removed it, hid it, unticked it, or the team took the approval away: remove your copy.
- With Google or GitHub, a name those do not give is saved by Mpuza as User. Let people correct their name in your application.
Changing what you get
| Who | How |
|---|---|
| Your application, to ask for more or less | Change the scope in your link. For more, tick it on your developer dashboard first and wait for the Mpuza team to approve it. |
| The person | Signs 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 team | The 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.
- 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.
- Give the name and your return addresses, and choose Create my application.
- 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 enter | Rule |
|---|---|
| The name of your application | People see it on the sign-in page. 2 to 60 characters. It cannot contain "Mpuza". |
| Your return addresses | Where 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 addresses | Where people come back after signing out. Optional. |
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.
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
| Name | What it is | Where you get it |
|---|---|---|
| Client ID | The public name of your application at Mpuza. It starts with mpz_ | You get it when you register your application. |
| Client secret | The 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 it | The 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.
# 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:30002. 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 words | Name your library may use | Value |
|---|---|---|
| Mpuza's address | Issuer | https://accounts.mpuza.com |
| Mpuza's settings page, which libraries read the rest from | Discovery URL | https://accounts.mpuza.com/.well-known/openid-configuration |
| What Mpuza sends back after a sign-in | Response type | code |
| Extra protection for that code. It must be on. | PKCE method | S256 |
| How your server shows who it is | Token endpoint authentication | client_secret_basic |
| How the proof of sign-in is signed | ID token signature | RS256 |
| What you ask to know about the person: who they are, name and email | Scopes | openid profile email |
3. Mpuza's addresses, ready to copy (also already set)
| What happens there | Name your library may use | Full address |
|---|---|---|
| You send people here to sign in | Authorization endpoint | https://accounts.mpuza.com/oauth/authorize |
| Your server swaps the code for the proof of sign-in | Token endpoint | https://accounts.mpuza.com/oauth/token |
| Your server can read the person's name and email | User info endpoint | https://accounts.mpuza.com/oauth/userinfo |
| The keys to check that the proof is real | Public keys (JWKS URI) | https://accounts.mpuza.com/.well-known/jwks.json |
| You send people here to sign out | Logout (end session) endpoint | https://accounts.mpuza.com/oauth/logout |
| Your server cancels a token | Revocation endpoint | https://accounts.mpuza.com/oauth/revoke |
Read Mpuza's settings
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()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.
| Value | What it is for |
|---|---|
| state | Matches the answer to the request. |
| nonce | Comes back inside the ID token. |
| code_verifier | For PKCE. You send its hash first and the value itself later. |
Send the person to sign in
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
| Field | Required | What it is |
|---|---|---|
| client_id | Yes | Yours. |
| redirect_uri | Yes | Your return address, exactly as you registered it. |
| response_type | Yes | Already set: code. |
| scope | Yes | Already set: openid profile email. |
| state | Yes | A new random value for each sign-in. |
| nonce | Yes | A new random value for each sign-in. |
| code_challenge | Yes | The SHA-256 of your new random code_verifier, in base64url. |
| code_challenge_method | Yes | Already 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=S256const 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)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 nowAnswer 303
https://myapp.example.com/auth/mpuza/callback?code=...&state=RANDOM_STATE4. Handle the answer
The browser returns to your address with code and state, or with error (for example access_denied when the person cancels).
- Find the sign-in by state. Refuse an unknown one, one from another browser, or one already used.
- From your server, exchange the code. The answer has id_token and access_token.
Swap the code for the proof of sign-in
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
| Field | Required | What it is |
|---|---|---|
| grant_type | Yes | Already set: authorization_code. |
| code | Yes | The code that came back. |
| redirect_uri | Yes | The same return address as before. |
| code_verifier | Yes | The 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()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.
- The signature, with the key from the public keys address whose kid matches, with the algorithm RS256 only.
- iss is exactly the issuer.
- aud is your client ID.
- exp is in the future.
- nonce is the one you made.
- email_verified is true, if you rely on the email address.
What else is inside it is listed under What information you get.
Mpuza's public keys
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()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
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()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
- Store sub with your account and find people by sub. An email address can change.
- Signing in says who the person is. What they may do in your application is your decision. Do not give anyone rights just because they signed in.
- Be careful when your application already has an account with the same email. If someone could have made that account without proving the email is theirs, joining it automatically would give them a way in. The safest choice is to let the person sign in the old way once and connect Mpuza from their settings. If you join by email, join only when email_verified is true, and remove any password on your side that was set before the email was proved.
Read the information about the person
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
| Field | Required | What it is |
|---|---|---|
| Authorization header | Yes | Bearer, 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()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
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
| Field | Required | What it is |
|---|---|---|
| id_token_hint | No | The ID token of the sign-in. If you do not keep it, send client_id instead. |
| client_id | No | Yours, instead of id_token_hint. |
| post_logout_redirect_uri | No | Your 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/loginconst 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)Ends your Try it and signs you out of Mpuza in this browser. Mpuza asks you first.
Try it: sign out nowCancel a token
https://accounts.mpuza.com/oauth/revoke From your server. Makes an access token stop working before its hour is over.
What you send
| Field | Required | What it is |
|---|---|---|
| token | Yes | The 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 itimport 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 itCancels the access token of your Try it sign-in.
Answer 200
(nothing)Errors you may see
| What you see | Usual cause |
|---|---|
| A Sign-in could not finish page instead of a redirect | Unknown 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 address | PKCE is missing or not S256. |
| error=invalid_scope back at your address | You asked for information the Mpuza team has not approved for your application. |
| Token answer 401 invalid_client | Wrong secret, or the secret was sent in the body instead of the Basic header. |
| Token answer 400 invalid_grant | The 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 expired | More than an hour passed, or the page was opened in another browser. |
| The person is asked to allow your application | Normal for an application a developer registers. If they choose Cancel, you get error=access_denied. |
| error=access_denied saying the application is still being tested | The 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.
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.
- 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/
- Save the example as node-app.js.
- Run it with one of the commands below, then open the address of APP_URL (http://localhost:3000 unless you changed it).
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.
node --env-file=mpuza.env node-app.jsOr give the values in the command itself. They are filled in from your values.
MPUZA_CLIENT_ID=mpz_... MPUZA_CLIENT_SECRET=mpzs_... \
node node-app.js$env:MPUZA_CLIENT_ID = 'mpz_...'
$env:MPUZA_CLIENT_SECRET = 'mpzs_...'
node node-app.jsThen try each case in your own application.
| What to do | What must happen |
|---|---|
| Sign in with email and password | You come back signed in, with your own name and email. |
| Sign in with Google, and with GitHub, using the same email address | The same account in your application every time. |
| Choose Cancel on the Mpuza page | You come back with error=access_denied and are not signed in. |
| Type a wrong password | You stay on the Mpuza page. Your application is not called. After many wrong tries Mpuza makes you wait. |
| Reload your return address after signing in | Refused: the sign-in works once. |
| Copy the sign-in link into another browser and finish there | Your application refuses it. |
| Sign out, choose Sign out on the Mpuza page, then sign in again | Mpuza asks for the password again. |
| Put a wrong client secret in your settings | Nobody 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 Mpuza | A 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 testing | Refused 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.
| Stage | Who can sign in | What happens next |
|---|---|---|
| Testing | You and your testers | When your tests pass, choose Ask to go live on the developer page. |
| Waiting for the Mpuza team | You and your testers | The team looks at the name and the addresses and approves or refuses. You can take your request back. |
| Live | Everyone | A new secret keeps it live. Changing the name or an address puts it back in testing. |
Before you ask, check all of these.
- The client secret is only on the server and not in Git.
- A new state, nonce and verifier for every sign-in, used once and tied to the browser.
- Every ID token check above.
- People are found by sub.
- A new account gets no special rights.
- Your session cookie is HttpOnly, Secure and SameSite=Lax or stricter.
- Codes and tokens are not written to logs.
- The old way of signing in still works if Mpuza sign-in is down.
- Switch off the applications you registered only for testing.
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.
// 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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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}`));