首页 > web前端 > js教程 > 正文

JS如何与SpringOAuth2安全认证配合_JS与SpringOAuth2安全认证配合的教程

星夢妙者
发布: 2025-11-09 19:30:04
原创
455人浏览过
前端通过OAuth2授权码模式+PKCE跳转登录,获取access_token后在请求头携带Bearer Token访问受Spring Security保护的API,后端配置JWT资源服务器验证令牌并启用CORS支持跨域。

js如何与springoauth2安全认证配合_js与springoauth2安全认证配合的教程

JavaScript前端应用与Spring Boot后端集成OAuth2安全认证,是现代全栈开发中的常见需求。通常前端使用JS(如Vue、React或原生JS)发起请求,后端使用Spring Security + OAuth2进行权限控制。下面介绍如何让JS与Spring OAuth2协同工作,实现安全的用户登录和资源访问。

理解整体架构

在典型的前后端分离项目中:

  • 前端(JS)运行在浏览器中,负责展示界面并与用户交互
  • 后端(Spring Boot)暴露REST API,通过Spring Security和OAuth2保护接口
  • 认证服务器负责颁发token(可以是独立服务,也可以内嵌在Spring应用中)

常见的流程是:用户在前端点击“登录”,跳转到OAuth2授权服务器(如Google、GitHub或自建),授权后获取access_token,后续请求携带该token访问受保护的API。

配置Spring Boot OAuth2资源服务器

确保你的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如何处理OAuth2登录与请求

由于浏览器安全限制,不推荐在JS中直接处理client_secret等敏感信息。应采用授权码模式 + PKCE,适合单页应用(SPA)。

琅琅配音
琅琅配音

全能AI配音神器

琅琅配音 208
查看详情 琅琅配音

使用官方推荐库如 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';
});
}
登录后复制

JS发起受保护的API请求

每次调用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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号