Data from protected endpoint:
"Text"
Pobranie stringa - autoryzacja przy użyciu JWT.
import React, { useState, useEffect } from 'react';
const AuthorizedComponent = ({ jwtToken }) => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('http://localhost:5203/api/Login/GetTxt', {
headers: {
'Authorization': `Bearer ${jwtToken}`,
'Content-Type': 'text/plain',
},
});
if (response.ok) {
const result = await response.text();
setData(result);
} else {
setError('Unauthorized');
}
} catch (error) {
setError('Error fetching data');
}
};
if (jwtToken) {
fetchData();
} else {
setError('JWT token not provided');
}
}, [jwtToken]);
return (
<div>
{data ? (
<div>
<h2>Data from protected endpoint:</h2>
<pre>{data}</pre>
</div>
) : (
<p>{error}</p>
)}
</div>
);
};
export default AuthorizedComponent;
Endpoint:
[Authorize(Roles = "User")]
[HttpGet("GetTxt")]
public ActionResult<string> GetText()
{
return "Text";
}
Przykładowe użycie komponentu.
const App = () => {
const jwtToken = 'token_jwt';
return (
<div>
<h1>Your App</h1>
<AuthorizedComponent jwtToken={jwtToken} />
</div>
);
};
Przykładowy token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy
8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6ImRhYTk4ZWQwLTgzMTEtN
DgwYi04NmMwLWRkYTVjYjkzMjRh
NCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW
1zL25hbWUiOiJBZHJpYW4gVXJ6xJlkbmljemVrIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0Lm
NvbS93cy8yMDA4LzA2L2lkZW50aXR
5L2NsYWltcy9yb2xlIjoiVXNlciIsIkRhdGVDcmVhdGlvbiI6IjIwMjMtMTAtMjUiLCJleHAiOjE3MDYzM
zE1NzEsImlzcyI6Imh0dHA6Ly93d3cuY28ucGwiLCJhdWQiOiJodHRwOi8vd3d3LmNvLnBsIn0.Mf
jyGx40DjeY2UAhTtt5tVL5c4pzDeWytHGwY_7Hydk