Spring Authorization Server 1.0.0: javascript error when requesting /oauth2/token
P粉314915922
2023-09-04 15:24:41
<p>I have created a Spring Authorization Server - you can find the code on github https://github.com/costerutilo/UTILO-Authorization-Server</p>
<p>I cannot read the token via JavaScript. I created a simple Vue web application to get the client authorization code, but I can't get the token. </p>
<p>Try using the fetch API: </p>
<pre class="brush:php;toolbar:false;">const url = 'http://127.0.0.1:9000/oauth2/token';
var credentials = btoa(import.meta.env.VITE_CLIENT_ID ':' 'secret');
var basicAuth = 'Basic ' credentials;
var myHeaders = new Headers();
//myHeaders.append("Authorization", "Basic dXRpbG8tY2xpZW50OnNlY3JldA==");
myHeaders.append("Authorization", basicAuth);
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "authorization_code");
// urlencoded.append("code", "yyJTTI3JqNno1XlSW59qxX3CCytMm-ChoHnqVw3iSUGyT6ltT_tpPclQ8bdSyeApO4IWE442irBiRwntJJzae9BIntpC3_vshTgNhAfbsBlkwh3n50jkAxs3 hTqavqsy");
urlencoded.append("code", code);
urlencoded.append("redirect_uri", "https://www.utilo.eu");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch(url, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));</pre>
<p>In the browser's javascript console, I see a CORS exception</p>
<pre class="brush:php;toolbar:false;">Access to fetch at 'http://127.0.0.1:9000/oauth2/token' from origin 'http://127.0.0.1:9010' has been blocked by CORS policy: Response to preflight request doesn't pass access control check</pre>
<p>The server console gives the error: </p>
<pre class="brush:php;toolbar:false;">2023-02-27T09:35:53.786 01:00 TRACE 33212 --- [nio-9000-exec-3] o.s.s.w.a.ExceptionTranslationFilter : Sending AnonymousAuthenticationToken [Principal =anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]] to authentication entry point since access is denied
org.springframework.security.access.AccessDeniedException: Access Denied</pre>
<p>If I try the same request in Postman, I get JSON with the token. </p>
<p>I don't know what my reasoning error is, or what I'm doing wrong. </p>
You will need to enable CORS for your Spring Security filter chain and provide a
@Bean
such as this example: p>Note: Port
4200
is for the Angular development environment, replace it with your Vue development server port.