我已经创建了一个 Spring 授权服务器 - 你可以在 github 上找到代码 https://github.com/costerutilo/UTILO-Authorization-Server
我无法通过 JavaScript 读取令牌。我创建了一个简单的 Vue Web 应用程序来获取客户端授权代码,但我无法获取令牌。
尝试使用 fetch API:
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));
在浏览器的 javascript 控制台中,我看到 CORS 异常
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
服务器控制台给出错误:
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
如果我在 Postman 中尝试相同的请求,我会得到带有令牌的 JSON。
我不知道我的推理错误是什么,或者我做错了什么。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您将需要为您的 Spring Security 过滤器链启用 CORS 并提供
@Bean例如 此示例: p>@Configuration public class CorsConfig { @Bean public CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.addAllowedHeader("*"); config.addAllowedMethod("*"); config.addAllowedOrigin("http://127.0.0.1:4200"); config.setAllowCredentials(true); source.registerCorsConfiguration("/**", config); return source; } }注意:端口
4200用于 Angular 开发环境,替换为您的 Vue 开发服务器端口。