400 Плохой запрос по вопросам сообщения для "https://oauth2.googleapis.com/token"JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 400 Плохой запрос по вопросам сообщения для "https://oauth2.googleapis.com/token"

Сообщение Anonymous »

Я пытаюсь использовать oAuth2, но эта линия (responseentity tokenresponse = resttemplate.postforentity (tokenendpoint, request, map.class);) приводит меня к за исключением 400 плохого запроса. < /p>
Я достиг этой конечной точки в соответствии с учебником.

Код: Выделить всё

localhost:8080/auth/google/callback?code=2/0872Qbj4HJQtB5n7EiDEiTFv6InSZFatpnWe6X6114hA_0YPuPZ-w
Я изменил URL -жесткое значение для целей безопасности.
Кроме того, это значение кода внутри URL -адреса получено от "https://developers.google.com/oauthplayplayground" на первом шаге. Затем, на втором этапе этого сайта, я вставил кодовое значение, и он дал мне доступ и обновлять токены правильно. Вместо этого ошибка 400 Bad Req. Учебное пособие, по которым я следую, сделал то же самое.
код приведен ниже: < /p>

Код: Выделить всё

package com.secure.notes.OAuth;
import com.secure.notes.model.User;
import com.secure.notes.model.UserRole;
import com.secure.notes.repositories.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/auth/google")
public class GoogleAuthController {
@Value("${spring.security.oauth2.client.registration.google.client-id}")
private String clientId;
@Value("${spring.security.oauth2.client.registration.google.client-secret}")
private String clientSecret;

@Autowired
private RestTemplate restTemplate;

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private UserRepository userRepository;

@GetMapping("/callback")
public ResponseEntity handleGoogleCallback(@RequestParam String code){
try{
// 1.  Exchange auth code from tokens
String tokenEndpoint = "https://oauth2.googleapis.com/token";

MultiValueMap params = new LinkedMultiValueMap();
params.add("code", code);
params.add("client_id", clientId);
params.add("client_secret", clientSecret);
params.add("redirect_uri", "https://developers.google.com/oauthplayground/"); // should be "redirect_uri", not "redirect_url"
params.add("grant_type", "authorization_code");

//By headers, we are telling google that what type of request we are sending
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

HttpEntity request = new HttpEntity(params, headers);

ResponseEntity tokenResponse = restTemplate.postForEntity(tokenEndpoint, request, Map.class);
String idToken = (String) tokenResponse.getBody().get("id_token");
String userInfoUrl = "https://oauth2.googleapis.com/tokeninfo?id_token=" + idToken;
ResponseEntity userInfoResponse = restTemplate.getForEntity(userInfoUrl, Map.class);
if(userInfoResponse.getStatusCode() == HttpStatus.OK){
Map userInfo = userInfoResponse.getBody();
String email = (String) userInfo.get("email");
UserDetails userDetails = userDetailsService.loadUserByUsername(email);
if(userDetails == null){
User user = new User();
user.setEmail(email);
user.setName(email);
user.setPassword(passwordEncoder.encode(UUID.randomUUID().toString()));
user.setRole(UserRole.USER);
userRepository.save(user);
userDetails = userDetailsService.loadUserByUsername(email);
}
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

SecurityContextHolder.getContext().setAuthentication(authentication);

return ResponseEntity.status(HttpStatus.OK).build();
}
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}catch (Exception e){
log.error("Exception Occurred while handleGoogleCallback ", e);
System.out.println(e.getCause()+" "+e.getMessage()+" "+ e.getStackTrace());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
< /code>
Я добавил идентификатор клиента и секрет в Application.config.  < /p>
На этом ниже приведен мой SecurityConfig: < /p>
package com.secure.notes.security;
import com.secure.notes.services.impl.AuthFilterService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfiguration {
private final AuthFilterService authFilterService;
private final AuthenticationProvider authenticationProvider;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/v1/auth/**", "/auth/google/callback") // Permit OAuth2 and authentication routes
.permitAll()
.anyRequest()
.permitAll())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(authFilterService, UsernamePasswordAuthenticationFilter.class)
.oauth2Login(oauth2 -> oauth2
.defaultSuccessUrl("/hello", true));

return http.build();
}

}
< /code>
Хотя здесь я добавил /hello as url url только для тестирования.
ошибка была такой же, когда его не было.
Stack Trace: < /p>
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request on POST request for "https://oauth2.googleapis.com/token": "{  "error": "invalid_grant",  "error_description": "Bad Request"}"
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:103) ~[spring-web-6.2.5.jar:6.2.5]
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:186) ~[spring-web-6.2.5.jar:6.2.5]
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:147) ~[spring-web-6.2.5.jar:6.2.5]
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:953) ~[spring-web-6.2.5.jar:6.2.5]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:902) ~[spring-web-6.2.5.jar:6.2.5]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:801) ~[spring-web-6.2.5.jar:6.2.5]
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:549) ~[spring-web-6.2.5.jar:6.2.5]
at com.secure.notes.OAuth.GoogleAuthController.handleGoogleCallback(GoogleAuthController.java:71) ~[classes/:na]
Я попытался изменить URL -адреса, обновить «код», который мы вставляем в URL при нажатии на конечную точку.

Подробнее здесь: https://stackoverflow.com/questions/795 ... -com-token
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»