Spring Security Spring授权服务器1.0.0:请求/oauth2/令牌时出现javascript错误

ajsxfq5m  于 2023-03-12  发布在  Spring
关注(0)|答案(2)|浏览(155)

我已经创建了一个Spring授权服务器-您可以在github https://github.com/costerutilo/UTILO-Authorization-Server上找到代码
我无法通过javascript读取令牌。我创建了一个简单的Vue Web应用程序来获取客户端授权码,但我无法获取令牌。
尝试使用获取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。
我不知道我的推理错在哪里,也不知道我做错了什么。

hjqgdpho

hjqgdpho1#

您需要为Spring Security过滤器链启用CORS,并提供@Bean,例如this example

@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开发服务器端口。

szqfcxe2

szqfcxe22#

感谢你的评分
我添加了以下代码

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS"));
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        //
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return urlBasedCorsConfigurationSource;
    }

在我 AJAX 调用中我必须添加mode:“无腐 eclipse ”

const url =  'http://127.0.0.1:9000/oauth2/token';

    let myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

    var urlencoded = new URLSearchParams();
    urlencoded.append("grant_type", "authorization_code");
    urlencoded.append("code", code);
    urlencoded.append("redirect_uri", "http://127.0.0.1:9010/admin");
    urlencoded.append("client_id", "utilo-client");
    urlencoded.append("client_secret", "secret");

    var requestOptions = {
      method: 'POST',
      mode: 'no-cors', // no-cors, *cors, same-origin
      headers: myHeaders,
      body: urlencoded,
      redirect: 'follow'
    };

    fetch("http://127.0.0.1:9000/oauth2/token", requestOptions)
        .then((response) => {
          return response.text();
        })
        .then((data) => {
          console.log('data: ' + data); // is empty string???
        })
        .catch(error => console.log('error', error));

现在我不再在Javascript控制台中收到错误消息,也不再在Java控制台中收到错误消息。
但是服务器的响应是空的。当我用Postman测试时,我得到了一个正确的结果。我不明白这有什么问题。

相关问题