I learn Santum and I want to make system of authorize. I made login controller and it return a token but I need send token to the server. I read that the best way is using httpOnly cookie.Look at this example
function Login () {
const emailRef = useRef(),
passwordRef = useRef();
const [cookies, setCookie] = useCookies();
const handleSubmit = (event) => {
event.preventDefault();
instance.post('/api/auth/login', {
email: emailRef.current.value,
password: passwordRef.current.value
}).then(res => {
console.log(res.data.access_token);
setCookie('Authorize', res.data.access_token, {
httpOnly: true
})
})
}
return(
<div>
<form onSubmit={handleSubmit}>
<input ref={emailRef} type="text" />
<input type="password" ref={passwordRef} placeholder="password" />
<button role="submit">Wyślij</button>
</form>
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/me">About</Link>
</li>
</ul>
</nav>
<Switch>
<Route path="/about">
<About />
</Route>
</Switch>
</div>
</Router>
</div>
);
}
At this example I send request and next I get a token from server. So how can I send cookie in header (becouse I should do that to autorize my request, am I?)
Cookies are added to requests automatically by the browser, you don't add them manually. The browser will now which cookie and when to add based on the properties of that cookie (the domain, path, whether it's a secure only cookie, same-site, etc).
You're trying to set a http-only cookie. HTTP-only cookies are cookies which cannot be accessed by Javascript run in the browser. This means that such cookies should be set by the backend server and sent together with the response. Your Javascript in the frontend cannot create an http-only cookie.
So, to solve your problem you can try two solutions:
Set the cookie with token in the server (by adding a Set-Cookie header to the response). Then it can be an HTTP-only cookie. It will be automatically added to any requests to the same domain as the server.
You can set the cookie in the Javascript as you do now, but it can't be HTTP-only and you should add the domain parameter with the domain of the backend to which you want the cookie to be sent.
Note that the first option should be the preferred one. In the second solution an XSS attack will be able to read and write your cookie.