fix(login): switch frontend account login to oidc flow

This commit is contained in:
Chris
2026-03-31 23:43:57 +08:00
parent 80a571d227
commit febfafc55c
3 changed files with 56 additions and 72 deletions

View File

@@ -112,7 +112,11 @@ def login(payload: LoginRequest) -> LoginResponse:
@router.get("/oidc/url", response_model=OIDCAuthUrlResponse)
def get_oidc_authorize_url(redirect_uri: str) -> OIDCAuthUrlResponse:
def get_oidc_authorize_url(
redirect_uri: str,
login_hint: str | None = None,
prompt: str = "login",
) -> OIDCAuthUrlResponse:
settings = get_settings()
client_id = settings.authentik_client_id or settings.authentik_audience
if not settings.authentik_base_url or not client_id:
@@ -120,16 +124,18 @@ def get_oidc_authorize_url(redirect_uri: str) -> OIDCAuthUrlResponse:
authorize_endpoint = urljoin(settings.authentik_base_url.rstrip("/") + "/", "application/o/authorize/")
state = secrets.token_urlsafe(24)
params = httpx.QueryParams(
{
"client_id": client_id,
"response_type": "code",
"scope": "openid profile email",
"redirect_uri": redirect_uri,
"state": state,
"prompt": "login",
}
)
query = {
"client_id": client_id,
"response_type": "code",
"scope": "openid profile email",
"redirect_uri": redirect_uri,
"state": state,
"prompt": prompt or "login",
}
if login_hint:
query["login_hint"] = login_hint
params = httpx.QueryParams(query)
return OIDCAuthUrlResponse(authorize_url=f"{authorize_endpoint}?{params}")

View File

@@ -1,10 +1,13 @@
import { userHttp } from './http'
export const loginWithPassword = (username, password) =>
userHttp.post('/auth/login', { username, password })
export const getOidcAuthorizeUrl = (redirectUri) =>
userHttp.get('/auth/oidc/url', { params: { redirect_uri: redirectUri } })
export const getOidcAuthorizeUrl = (redirectUri, options = {}) =>
userHttp.get('/auth/oidc/url', {
params: {
redirect_uri: redirectUri,
login_hint: options.loginHint || undefined,
prompt: options.prompt || undefined
}
})
export const exchangeOidcCode = (code, redirectUri) =>
userHttp.post('/auth/oidc/exchange', { code, redirect_uri: redirectUri })

View File

@@ -4,7 +4,7 @@
<template #header>
<div class="text-center">
<h1 class="text-xl font-bold text-gray-800">member.ose.tw</h1>
<p class="text-sm text-gray-500 mt-1">可使用帳號密碼 Google SSO 登入</p>
<p class="text-sm text-gray-500 mt-1">可使用帳號登入 Google SSO 登入</p>
</div>
</template>
@@ -26,23 +26,13 @@
@keyup.enter="handlePasswordLogin"
/>
</el-form-item>
<el-form-item label="密碼">
<el-input
v-model="form.password"
type="password"
show-password
placeholder="請輸入密碼"
autocomplete="current-password"
@keyup.enter="handlePasswordLogin"
/>
</el-form-item>
<el-button
type="primary"
class="w-full"
:loading="passwordLoading"
@click="handlePasswordLogin"
>
帳號密碼登入
使用帳號登入
</el-button>
</el-form>
@@ -58,7 +48,7 @@
</el-button>
<div class="mt-4 text-xs text-gray-400 text-center space-y-1">
<p>Google SSO 會跳轉到 Authentik完成驗證後自動返回</p>
<p>登入會跳轉到 Authentik 驗證完成後自動返回</p>
<p>登入成功後 access token 會存於本機 localStorage</p>
</div>
</el-card>
@@ -67,20 +57,16 @@
<script setup>
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getOidcAuthorizeUrl, loginWithPassword } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'
import { useRoute } from 'vue-router'
import { getOidcAuthorizeUrl } from '@/api/auth'
const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const passwordLoading = ref(false)
const oidcLoading = ref(false)
const error = ref('')
const form = reactive({
username: '',
password: ''
username: ''
})
function getPostLoginRedirect() {
@@ -89,31 +75,19 @@ function getPostLoginRedirect() {
}
async function handlePasswordLogin() {
if (!form.username || !form.password) {
error.value = '請輸入帳號與密碼'
if (!form.username) {
error.value = '請輸入帳號'
return
}
passwordLoading.value = true
error.value = ''
try {
const res = await loginWithPassword(form.username, form.password)
const token = res.data?.access_token
if (!token) {
error.value = '登入失敗:缺少 access token'
return
}
authStore.setToken(token)
await authStore.fetchMe()
router.push(getPostLoginRedirect())
} catch (err) {
const detail = err.response?.data?.detail
if (detail === 'invalid_username_or_password') {
error.value = '帳號或密碼錯誤'
} else if (detail === 'authentik_login_not_configured') {
error.value = '後端尚未設定帳密登入參數'
} else {
error.value = '登入失敗,請稍後再試'
}
await redirectToOidc({
loginHint: form.username,
prompt: 'login'
})
} catch (_err) {
error.value = '登入失敗,請稍後再試'
} finally {
passwordLoading.value = false
}
@@ -123,25 +97,26 @@ async function handleOidcLogin() {
oidcLoading.value = true
error.value = ''
try {
sessionStorage.setItem('post_login_redirect', getPostLoginRedirect())
const callbackUrl = `${window.location.origin}/auth/callback`
const res = await getOidcAuthorizeUrl(callbackUrl)
const authorizeUrl = res.data.authorize_url
const parsed = new URL(authorizeUrl)
const state = parsed.searchParams.get('state')
if (state) {
sessionStorage.setItem('oidc_expected_state', state)
}
window.location.href = authorizeUrl
await redirectToOidc({
prompt: 'select_account'
})
} catch (err) {
const detail = err.response?.data?.detail
if (detail === 'authentik_login_not_configured') {
error.value = '後端尚未設定 Authentik 登入參數'
} else {
error.value = '登入失敗,請稍後再試'
}
error.value = err.message || '登入失敗,請稍後再試'
} finally {
oidcLoading.value = false
}
}
async function redirectToOidc(options = {}) {
sessionStorage.setItem('post_login_redirect', getPostLoginRedirect())
const callbackUrl = `${window.location.origin}/auth/callback`
const res = await getOidcAuthorizeUrl(callbackUrl, options)
const authorizeUrl = res.data.authorize_url
const parsed = new URL(authorizeUrl)
const state = parsed.searchParams.get('state')
if (state) {
sessionStorage.setItem('oidc_expected_state', state)
}
window.location.href = authorizeUrl
}
</script>