Spring 授权服务器 1.0.0:请求 /oauth2/token 时出现 javascript 错误
P粉314915922
2023-09-04 15:24:41
<p>我已经创建了一个 Spring 授权服务器 - 你可以在 github 上找到代码 https://github.com/costerutilo/UTILO-Authorization-Server</p>
<p>我无法通过 JavaScript 读取令牌。我创建了一个简单的 Vue Web 应用程序来获取客户端授权代码,但我无法获取令牌。</p>
<p>尝试使用 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_vshTgNhAfbsBlkwh3n50jkAxs3hTqavqsy");
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>在浏览器的 javascript 控制台中,我看到 CORS 异常</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>服务器控制台给出错误:</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>如果我在 Postman 中尝试相同的请求,我会得到带有令牌的 JSON。</p>
<p>我不知道我的推理错误是什么,或者我做错了什么。</p>
您将需要为您的 Spring Security 过滤器链启用 CORS 并提供
@Bean
例如 此示例: p>注意:端口
4200
用于 Angular 开发环境,替换为您的 Vue 开发服务器端口。