No httponly with fast and react. Fast, React and httponly with Oauth2. #149250
Replies: 1 comment
-
🕒 Discussion Activity Reminder 🕒 This Discussion has been labeled as dormant by an automated system for having no activity in the last 60 days. Please consider one the following actions: 1️⃣ Close as Out of Date: If the topic is no longer relevant, close the Discussion as 2️⃣ Provide More Information: Share additional details or context — or let the community know if you've found a solution on your own. 3️⃣ Mark a Reply as Answer: If your question has been answered by a reply, mark the most helpful reply as the solution. Note: This dormant notification will only apply to Discussions with the Thank you for helping bring this Discussion to a resolution! 💬 |
Beta Was this translation helpful? Give feedback.
-
Select Topic Area
Question
Body
So first is my provider file, sice it works for my /mobile i havent added that. I use regular token for swiftapp.
`@oauth_router.get('/authorize')
async def authorize(request: Request, db_pool=Depends(get_db_pool)):
log_request_details(request) # Log request details
session = request.session
client_id = request.query_params.get('client_id') or session.get('client_id')
redirect_uri = request.query_params.get('redirect_uri') or session.get('redirect_uri')
code_challenge = request.query_params.get('code_challenge') or session.get('code_challenge')
code_challenge_method = request.query_params.get('code_challenge_method') or session.get('code_challenge_method', 'S256')
prompt = request.query_params.get('prompt')
@oauth_router.get('/login')
async def login_get(request: Request):
log_request_details(request) # Log request details
session = request.session
client_id = request.query_params.get('client_id') or session.get('client_id')
redirect_uri = request.query_params.get('redirect_uri') or session.get('redirect_uri')
code_challenge = request.query_params.get('code_challenge') or session.get('code_challenge')
code_challenge_method = request.query_params.get('code_challenge_method') or session.get('code_challenge_method', 'S256')
prompt = request.query_params.get('prompt')
logger.debug(f"/login: client_id={client_id}, redirect_uri={redirect_uri}, code_challenge={code_challenge}, code_challenge_method={code_challenge_method}, prompt={prompt}")
@oauth_router.get('/login')
async def login_get(request: Request):
logger.debug(f"--- /login (GET) (START) ---")
log_request_details(request) # Log request details
session = request.session
logger.debug(f"Session at start: {dict(request.session)}") # Log session at the beginning
@oauth_router.post('/login')
async def login_post(request: Request, db_pool=Depends(get_db_pool)):
logger.debug(f"--- /login (POST) (START) ---")
log_request_details(request) # Log request details
session = request.session
logger.debug(f"Session at start: {dict(request.session)}") # Log session at the beginning
@oauth_router.get('/logout')
async def logout(request: Request):
logger.debug(f"--- /logout (START) ---")
session = request.session
logger.debug(f"Session at start: {dict(request.session)}")
Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(name)
@oauth_router.post('/token')
async def token(request: Request, db_pool=Depends(get_db_pool)):
logger.debug(f"--- /token (START) ---")
form_data = await request.form()
log_request_details(request, form_data) # Log request details and form data
grant_type = form_data.get('grant_type')
@oauth_router.post('/token/refresh')
async def token_refresh(request: Request, db_pool=Depends(get_db_pool)):
logger.debug(f"--- /token/refresh (START) ---")
log_request_details(request) # Log request details
logger.debug(f"Cookies received: {request.cookies}")
logger.debug(f"Headers received: {request.headers}")
app.add_middleware(
CORSMiddleware,
allow_origins=["https://dev.xx.xx", "https://web.xx.xx"],
allow_credentials=True,
allow_methods=[""],
allow_headers=[""],
expose_headers=["set-cookie"]
)
Add Session Middleware
app.add_middleware(
SessionMiddleware,
secret_key=Config.SECRET_KEY,
session_cookie="session",
same_site="Lax",
https_only=True,
)`
And last is my authcontext and my callback in React:```
import React, { createContext, useState, useContext, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { setAuthToken, clearAuthToken } from '../features/auth/authSlice';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [authTokens, setAuthTokens] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const dispatch = useDispatch();
useEffect(() => {
const loadTokens = async () => {
const storedTokens = sessionStorage.getItem('authTokens');
console.log('Loading tokens from sessionStorage:', storedTokens);
}, [dispatch]);
const setTokens = (data) => {
console.log('Received data:', data);
};
const clearTokens = () => {
console.log('Clearing tokens.');
setAuthTokens(null);
sessionStorage.removeItem('authTokens');
dispatch(clearAuthToken());
};
const refreshTokens = async () => {
console.log('Trying to refresh token');
try {
const response = await fetch('https://xx.xx.xx/oauth/token/refresh', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
credentials: 'include',
body: new URLSearchParams({
client_id: 'webapp',
}),
});
};
return (
<AuthContext.Provider value={{ authTokens, isLoading, setAuthTokens: setTokens, clearTokens }}>
{children}
</AuthContext.Provider>
);
};
export default AuthProvider;
export const useAuth = () => useContext(AuthContext);
``` And here is the callback: `import React, { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
export default function Callback() {
const navigate = useNavigate();
const location = useLocation();
const { setAuthTokens } = useAuth();
useEffect(() => {
const fetchTokens = async () => {
const query = new URLSearchParams(location.search);
const authorizationCode = query.get('code'); // Get the authorization code from the URL
const codeVerifier = localStorage.getItem('code_verifier');
}, []); // Add an empty dependency array to ensure it runs only once
return
}
` But we do not get the httponly: DEBUG:oauth_provider:Request Query Params:
DEBUG:oauth_provider:Cookies received: {'session': 'eyJjbGllbnRfaWQiOiAiZGV2IiwgInJlZGlyZWN0X3VyaSI6ICJodHRwczovL2Rldi5maXhpLm9uZS9jYWxsYmFjayIsICJjb2RlX2NoYWxsZW5nZSI6ICJxMVU2UEJjVjNuRHRCaS1fTUFNUEMzNi11emJKVFI4dnV0QzFJXzFPQjZjIiwgImNvZGVfY2hhbGxlbmdlX21ldGhvZCI6ICJTMjU2IiwgInVzZXJfaWQiOiAzLCAiY2l0eSI6ICJTa2llbiJ9.Z4foGg.SKuPNCeR1wzkzSVPYcokir4SEsg'}
DEBUG:oauth_provider:Headers received: Headers({'via': '1.1 kong/3.9.0.0-enterprise-edition', 'host': '193.69.47.207:5000', 'connection': 'keep-alive', 'x-forwarded-for': '82.148.179.117, 162.158.222.101, 127.0.0.1', 'x-forwarded-proto': 'https', 'x-forwarded-host': 'xx.xx.one', 'x-forwarded-port': '8443', 'x-forwarded-path': '/oauth/token/refresh', 'x-real-ip': '127.0.0.1', 'x-kong-request-id': '82ad823fa38ad22e7ceac84ffe4b0477', 'content-length': '16', 'cf-ray': '902763bddbf2b50b-OSL', 'cookie': 'session=eyJjbGllbnRfaWQiOiAiZGV2IiwgInJlZGlyZWN0X3VyaSI6ICJodHRwczovL2Rldi5maXhpLm9uZS9jYWxsYmFjayIsICJjb2RlX2NoYWxsZW5nZSI6ICJxMVU2UEJjVjNuRHRCaS1fTUFNUEMzNi11emJKVFI4dnV0QzFJXzFPQjZjIiwgImNvZGVfY2hhbGxlbmdlX21ldGhvZCI6ICJTMjU2IiwgInVzZXJfaWQiOiAzLCAiY2l0eSI6ICJTa2llbiJ9.Z4foGg.SKuPNCeR1wzkzSVPYcokir4SEsg', 'accept-encoding': 'gzip, br', 'cf-ipcountry': 'NO', 'priority': 'u=1, i', 'accept-language': 'nb-NO,nb;q=0.9,no;q=0.8,nn;q=0.7,en-US;q=0.6,en;q=0.5,sv;q=0.4', 'cf-visitor': '{"scheme":"https"}', 'referer': 'https://xx.xx.one/', 'sec-fetch-dest': 'empty', 'cf-connecting-ip': '82.148.179.117', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-site', 'cdn-loop': 'cloudflare; loops=1', 'sec-ch-ua-platform': '"macOS"', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', 'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"', 'content-type': 'application/x-www-form-urlencoded', 'sec-ch-ua-mobile': '?0', 'accept': '/', 'origin': 'https://xx.xx.xx'})
ERROR:oauth_provider:No refresh token found in cookies
INFO: 193.69.47.207:37490 - "POST /oauth/token/refresh HTTP/1.1" 401 Unauthorized
Beta Was this translation helpful? Give feedback.
All reactions