前端通过OAuth2授权码模式+PKCE跳转登录,获取access_token后在请求头携带Bearer Token访问受Spring Security保护的API,后端配置JWT资源服务器验证令牌并启用CORS支持跨域。

JavaScript前端应用与Spring Boot后端集成OAuth2安全认证,是现代全栈开发中的常见需求。通常前端使用JS(如Vue、React或原生JS)发起请求,后端使用Spring Security + OAuth2进行权限控制。下面介绍如何让JS与Spring OAuth2协同工作,实现安全的用户登录和资源访问。
在典型的前后端分离项目中:
常见的流程是:用户在前端点击“登录”,跳转到OAuth2授权服务器(如Google、GitHub或自建),授权后获取access_token,后续请求携带该token访问受保护的API。
确保你的Spring Boot应用正确配置为OAuth2资源服务器,能验证JWT格式的access token。
application.yml 示例:spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8080/auth/realms/your-realm
# 或者指定 jwk-set-uri
添加依赖(Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
启用Security配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authz ->
authz.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
);
http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
}
由于浏览器安全限制,不推荐在JS中直接处理client_secret等敏感信息。应采用授权码模式 + PKCE,适合单页应用(SPA)。
使用官方推荐库如 openid-client 或更轻量的 simple-oauth2,但更推荐使用 Auth.js(原NextAuth)或 OAuth2-Client 库简化流程。
一个简单的JS登录跳转示例:
function login() {
const clientId = 'your-spa-client-id';
const redirectUri = 'https://www.php.cn/link/c7e07c312fd6bafc9f5192b3dfdf3d3f';
const scope = 'openid profile email';
const state = generateRandomString();
const codeVerifier = generateCodeVerifier(); // PKCE用
const codeChallenge = base64UrlEncode(sha256(codeVerifier));
<p>// 存储codeVerifier以便回调时使用
sessionStorage.setItem('code_verifier', codeVerifier);</p><p>const authUrl = new URL('<a href="https://www.php.cn/link/90918c5b8c17f80e32d5b155a7bf6197">https://www.php.cn/link/90918c5b8c17f80e32d5b155a7bf6197</a>');
authUrl.searchParams.append('client_id', clientId);
authUrl.searchParams.append('response_type', 'code');
authUrl.searchParams.append('scope', scope);
authUrl.searchParams.append('redirect_uri', redirectUri);
authUrl.searchParams.append('state', state);
authUrl.searchParams.append('code_challenge', codeChallenge);
authUrl.searchParams.append('code_challenge_method', 'S256');</p><p>window.location.href = authUrl.toString();
}
回调页面(callback.html)处理授权码并换取token:
// 假设URL中包含 ?code=xxx&state=yyy
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
<p>if (code) {
const codeVerifier = sessionStorage.getItem('code_verifier');
fetch('<a href="https://www.php.cn/link/d996e31032e7c288d7e20e7b82221c20">https://www.php.cn/link/d996e31032e7c288d7e20e7b82221c20</a>', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: 'your-spa-client-id',
code: code,
redirect_uri: '<a href="https://www.php.cn/link/c7e07c312fd6bafc9f5192b3dfdf3d3f">https://www.php.cn/link/c7e07c312fd6bafc9f5192b3dfdf3d3f</a>',
code_verifier: codeVerifier
})
})
.then(response => response.json())
.then(data => {
localStorage.setItem('access_token', data.access_token);
window.location.href = '/dashboard.html';
});
}
每次调用Spring保护的接口时,在请求头中带上access token:
fetch('http://localhost:8080/api/user/profile', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('access_token')
}
})
.then(response => {
if (response.status === 401) {
// token过期,重新登录
window.location.href = '/login.html';
}
return response.json();
})
.then(data => console.log(data));
建议封装一个API客户端,自动附加token:
function apiGet(url) {
return fetch(url, {
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('access_token')
}
});
}
基本上就这些。只要前后端约定好token传递方式,Spring会自动解析JWT并建立安全上下文。注意跨域问题需在后端配置CORS,允许前端域名访问。
以上就是JS如何与SpringOAuth2安全认证配合_JS与SpringOAuth2安全认证配合的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号