|
1 | 1 | // Copyright © 2024 Ory Corp |
2 | 2 | // SPDX-License-Identifier: Apache-2.0 |
3 | 3 |
|
4 | | -import { acceptConsentRequest, rejectConsentRequest } from "@ory/nextjs/app" |
| 4 | +import { |
| 5 | + acceptConsentRequest, |
| 6 | + getServerSession, |
| 7 | + rejectConsentRequest, |
| 8 | +} from "@ory/nextjs/app" |
5 | 9 | import { NextResponse } from "next/server" |
6 | 10 |
|
7 | 11 | interface ConsentBody { |
@@ -40,6 +44,24 @@ async function parseRequest(request: Request): Promise<ConsentBody> { |
40 | 44 | } |
41 | 45 |
|
42 | 46 | export async function POST(request: Request) { |
| 47 | + const session = await getServerSession() |
| 48 | + if (!session) { |
| 49 | + console.error("Consent security: No session found") |
| 50 | + return NextResponse.json( |
| 51 | + { error: "unauthorized", error_description: "No session" }, |
| 52 | + { status: 401 }, |
| 53 | + ) |
| 54 | + } |
| 55 | + |
| 56 | + const identityId = session.identity?.id |
| 57 | + if (!identityId) { |
| 58 | + console.error("Consent security: Session has no identity ID") |
| 59 | + return NextResponse.json( |
| 60 | + { error: "unauthorized", error_description: "Invalid session" }, |
| 61 | + { status: 401 }, |
| 62 | + ) |
| 63 | + } |
| 64 | + |
43 | 65 | const body = await parseRequest(request) |
44 | 66 |
|
45 | 67 | const action = body.action |
@@ -68,14 +90,31 @@ export async function POST(request: Request) { |
68 | 90 | redirectTo = await acceptConsentRequest(consentChallenge, { |
69 | 91 | grantScope, |
70 | 92 | remember, |
| 93 | + identityId, |
71 | 94 | }) |
72 | 95 | } else { |
73 | | - redirectTo = await rejectConsentRequest(consentChallenge) |
| 96 | + redirectTo = await rejectConsentRequest(consentChallenge, { |
| 97 | + identityId, |
| 98 | + }) |
74 | 99 | } |
75 | 100 |
|
76 | 101 | return NextResponse.json({ redirect_to: redirectTo }) |
77 | 102 | } catch (error) { |
78 | 103 | console.error("Consent error:", error) |
| 104 | + |
| 105 | + if ( |
| 106 | + error instanceof Error && |
| 107 | + error.message.includes("does not match consent request subject") |
| 108 | + ) { |
| 109 | + return NextResponse.json( |
| 110 | + { |
| 111 | + error: "forbidden", |
| 112 | + error_description: "Session does not match consent request subject", |
| 113 | + }, |
| 114 | + { status: 403 }, |
| 115 | + ) |
| 116 | + } |
| 117 | + |
79 | 118 | return NextResponse.json( |
80 | 119 | { error: "server_error", error_description: "Failed to process consent" }, |
81 | 120 | { status: 500 }, |
|
0 commit comments