spring-boot - 如何将 Spring Boot 与 Spotify OAuth 2 身份验证集成

标签 spring-boot spotify spring-security-oauth2 spring-oauth2

我是 Spring Boot 和 Spring Security 的新手。所以我从一些教程开始。现在我想在我的示例应用程序中将 oauth 身份验证与 Spotify 集成。

我已经向我介绍了 spring.io 的 spring boot oauth 2 教程。将解释如何将 oauth 与 facebook 和 github 集成。我自定义了 application.yml 来进行 Spotify 配置,但它不起作用。

应用程序.yml

security:
  oauth2:
    client:
      clientId: <my-client-id>
      clientSecret: <my-secret>
      accessTokenUri: https://accounts.spotify.com/api/token
      userAuthorizationUri: https://accounts.spotify.com/authorize
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
      scope: user-read-private, user-read-email
    resource:
      userInfoUri: https://api.spotify.com/v1/me

SpotifyOAuthApplication.java

package sh.stern.SpotifyOAuth;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class SpotifyOAuthApplication extends WebSecurityConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(SpotifyOAuthApplication.class, args);
    }

    @RequestMapping("/user")
    public Principal user(Principal principal) {
        return principal;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/", "/login**", "/webjars/**", "/error**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and().logout().logoutSuccessUrl("/").permitAll()
                .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
}

/resources/static/index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>Demo</title>
    <meta name="description" content=""/>
    <meta name="viewport" content="width=device-width"/>
    <base href="/"/>
    <link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css"/>
    <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Demo</h1>
<div class="container">
    <div class="container unauthenticated">
        With Spotify: <a href="/login">click here</a>
    </div>
    <div class="container authenticated" style="display:none">
        Logged in as: <span id="user"></span>
        <div>
            <button onClick="logout()" class="btn btn-primary">Logout</button>
        </div>
    </div>
    <script type="text/javascript">
      $.get("/user", function(data) {
        $("#user").html(data.userAuthentication.details.name);
        $(".unauthenticated").hide()
        $(".authenticated").show()
      });

      var logout = function() {
        $.post("/logout", function() {
          $("#user").html('');
          $(".unauthenticated").show();
          $(".authenticated").hide();
        });
        return true;
      }

      $.ajaxSetup({
        beforeSend : function(xhr, settings) {
          if (settings.type == 'POST' || settings.type == 'PUT'
            || settings.type == 'DELETE') {
            if (!(/^http:.*/.test(settings.url) || /^https:.*/
              .test(settings.url))) {
              // Only send the token to relative URLs i.e. locally.
              xhr.setRequestHeader("X-XSRF-TOKEN",
                Cookies.get('XSRF-TOKEN'));
            }
          }
        }
      });
    </script>
    <script type="text/javascript" src="/webjars/js-cookie/js.cookie.js"></script>
</div>
</body>
</html>

构建.gradle

plugins {
    id 'org.springframework.boot' version '2.1.5.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'sh.stern'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'

    compile group: 'org.springframework.security.oauth.boot', name: 'spring-security-oauth2-autoconfigure', version: '2.1.5.RELEASE'
    compile group: 'org.webjars', name: 'jquery', version: '3.4.1'
    compile group: 'org.webjars', name: 'js-cookie', version: '2.1.0'
    compile group: 'org.webjars', name: 'bootstrap', version: '4.3.1'
    compile group: 'org.webjars', name: 'webjars-locator-core', version: '0.37'
}

如果我启动我的应用程序并在 localhost:8080 上打开 Web 应用程序,我会被重定向到 Spotify。我正在登录我的 Spotify 帐户,并且被重定向到我的应用程序,但重定向后我收到以下错误:

2019-05-24 23:00:17.564  WARN 55176 --- [io-8080-exec-10] o.s.b.a.s.o.r.UserInfoTokenServices      : Could not fetch user details: class org.springframework.web.client.HttpClientErrorException$Unauthorized, 401 Unauthorized

我是否错误配置了 application.yml?

最佳答案

我可以找到问题所在,application.yml 配置错误。看来 tokenName 是错误的。我删除了这个属性,现在它可以工作了。

配置现在看起来像这样:

security:
  oauth2:
    client:
      clientId: <my-client-id>
      clientSecret: <my-client-secret>
      accessTokenUri: https://accounts.spotify.com/api/token
      userAuthorizationUri: https://accounts.spotify.com/authorize
      authenticationScheme: query
      clientAuthenticationScheme: form
      scope: user-read-private, user-read-email
    resource:
      userInfoUri: https://api.spotify.com/v1/me

关于spring-boot - 如何将 Spring Boot 与 Spotify OAuth 2 身份验证集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56299566/

相关文章:

Spring boot + Thymeleaf + webjars Bootstrap 4

node.js - Spotify API Web : OAuth without Node. js

java - 在 Spring Boot 中全局启用 CORS

postgresql - 错误 : operator does not exist: timestamp without time zone >= boolean Hint: No operator matches the given name and argument type(s)

python - 如何设置 Spotipy 并访问 Spotify 的 Web API

spotify - 如何在最小化时使用 Autohotkey 为 Spotify 歌曲加注星标?

spring - 迁移到 Spring Boot 1.5.1 和 OAuth2 + JWT token - 错误 401 未经授权

java - Spring Oauth2 客户端凭证流程示例

spring-boot - Spring Boot 安全性 - 允许用户请求使用过期的 JWT token

java - Spring @ComponentScan 不适用于 @Repository