Skip to content

Commit

Permalink
Merge pull request #124 from piny940/csrf
Browse files Browse the repository at this point in the history
Csrf対策を追加
  • Loading branch information
piny940 authored Nov 29, 2024
2 parents 6b2681f + 1d3111e commit a594e2f
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
1 change: 1 addition & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ DB_DEBUG=false
SERVER_URL=https://example.com/api/v1
SERVER_PORT=8081
SERVER_ALLOW_ORIGINS=http://localhost:3000
SERVER_CSRF_ENABLED=false # for testing purposes

API_LOGIN_URL=http://localhost:3000/
API_APPROVE_URL=http://localhost:3000/approve
Expand Down
8 changes: 8 additions & 0 deletions frontend/src/utils/client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import createClient from 'openapi-fetch'
import { paths } from './api'
import { fromCookie } from './cookie'

export const client = createClient<paths>({
fetch: (input: Request) => {
const csrf = fromCookie('_csrf')
if (csrf) {
input.headers.set('X-CSRF-Token', csrf)
}
return fetch(input)
},
baseUrl: process.env.NEXT_PUBLIC_API_URL,
credentials: 'include',
})
5 changes: 5 additions & 0 deletions frontend/src/utils/cookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const fromCookie = (key: string): string | undefined => {
const match = document.cookie.match(new RegExp('(^| )' + key + '=([^;]+)'))
if (match) return match[2]
return
}
17 changes: 15 additions & 2 deletions internal/server/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"os"
"os/signal"
"strings"
"time"

"github.com/kelseyhightower/envconfig"
Expand All @@ -20,6 +21,7 @@ var config = &Config{}
type Config struct {
Port string `required:"true"`
AllowOrigins []string `split_words:"true" required:"true"`
CSRFEnabled bool `split_words:"true" default:"true"`
}

func Init() *echo.Echo {
Expand All @@ -35,9 +37,20 @@ func Init() *echo.Echo {
}
e.Use(middleware.Recover())
e.Use(middleware.Secure())
if config.CSRFEnabled {
e.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
Skipper: func(c echo.Context) bool { return strings.HasPrefix(c.Path(), "/oauth") },
CookiePath: "/",
}))
}
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: config.AllowOrigins,
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
AllowOrigins: config.AllowOrigins,
AllowHeaders: []string{
echo.HeaderOrigin,
echo.HeaderContentType,
echo.HeaderAccept,
echo.HeaderXCSRFToken,
},
AllowCredentials: true,
}))
e.Use(myMiddleware.Session())
Expand Down

0 comments on commit a594e2f

Please sign in to comment.