Код: Выделить всё
@RestController
@RequestMapping("spotify/v3")
public class AuthControllerV3 {
private static final Logger logger = LoggerFactory.getLogger(AuthControllerV3.class);
private final AuthServiceV3 authServiceV3;
public AuthControllerV3(AuthServiceV3 auth2Service) {
this.authServiceV3 = auth2Service;
}
@GetMapping("/authorize")
public ResponseEntity authorizeUser(
@RequestParam(name = "redirect_url") String redirectUrl) {
logger.info("Authorize request received for redirect url {}", redirectUrl);
try {
String scopes = "";
String randomId = UUID.randomUUID().toString();
SecretKey secretKey = EncryptionUtil.getFixedKey();
String encryptedState = EncryptionUtil.encrypt(randomId, secretKey);
String state = encryptedState + ":" + randomId;
String spotifyUrl = authServiceV3.getRedirectUrl(scopes, state, redirectUrl);
return ResponseEntity.status(HttpStatus.FOUND)
.header(HttpHeaders.LOCATION, spotifyUrl).build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
...
}
Код: Выделить всё
@Service
public class AuthServiceV3 {
private final static String API_BASE = "https://api.spotify.com";
private final String SPOTIFY_AUTH_BASE = "https://accounts.spotify.com";
private final String SPOTIFY_AUTH_TOKEN_URL = SPOTIFY_AUTH_BASE + "/api/token";
private final String SPOTIFY_AUTH_URL = SPOTIFY_AUTH_BASE + "/authorize";
private final String CLIENT_ID = "4d06007cc0de44f8a9eda9a47890adf3";
private final String CLIENT_SECRET = "d87046dfma9941668aebb40efe1bbb24";
private RestTemplate restTemplate = new RestTemplate();
public String getRedirectUrl(String scope, String genState, String AUTH_REDIRECT_URL) {
return UriComponentsBuilder.fromUriString(SPOTIFY_AUTH_URL)
.queryParam("client_id", CLIENT_ID)
.queryParam("response_type", "code")
.queryParam("redirect_uri", AUTH_REDIRECT_URL)
.queryParam("scope", scope)
.queryParam("state", genState)
.build()
.toUriString();
}
..
}
Код: Выделить всё
@RequestMapping("spotify")
@Controller
public class SpotifyCallbackController {
@Value("${spring.security.oauth2.client.registration.spotify.client-id}")
private String clientId;
@Value("${spring.security.oauth2.client.registration.spotify.client-secret}")
private String clientSecret;
@GetMapping("/")
public String home() {
return "index";
}
@GetMapping("/callback")
public String callback(OAuth2AuthenticationToken token, Model model) {
OAuth2User user = token.getPrincipal();
model.addAttribute("user", user.getAttributes());
return "profile";
}
}
Код: Выделить всё
[img]https: //i.sstatic.net/iOWNaSj8.png[/img]
Подробнее здесь: https://stackoverflow.com/questions/793 ... ow-in-java
Мобильная версия