Spring Security OAuth2 | InsufficientAuthenticationException



Я пытаюсь построить сервер авторизации OAuth2 с помощью Spring Security OAuth2 (2.0.6.ОСВОБОЖДАТЬ).



Вот как выглядит моя соответствующая конфигурация: -



@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends
AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;

/*
* (non-Javadoc)
*
* @see
* org.springframework.security.oauth2.config.annotation.web.configuration
* .AuthorizationServerConfigurerAdapter
* #configure(org.springframework.security
* .oauth2.config.annotation.web.configurers
* .AuthorizationServerEndpointsConfigurer)
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints.authenticationManager(authenticationManager);
}

/*
* (non-Javadoc)
*
* @see
* org.springframework.security.oauth2.config.annotation.web.configuration
* .AuthorizationServerConfigurerAdapter
* #configure(org.springframework.security
* .oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer)
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {

// OAuth2 CLIENT CONFIGURATION !!!!!
clients.inMemory().withClient("sambhav").secret("sambhav")
.authorizedGrantTypes("authorization_code")
.scopes("openid", "all").redirectUris("http:localhost:9001");
}

/*
* (non-Javadoc)
*
* @see
* org.springframework.security.oauth2.config.annotation.web.configuration
* .AuthorizationServerConfigurerAdapter
* #configure(org.springframework.security
* .oauth2.config.annotation.web.configurers
* .AuthorizationServerSecurityConfigurer)
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security)
throws Exception {
super.configure(security);
}
}


Используя Spring Boot embedded jetty, во время запуска я вижу, что конечные точки OAuth2 регистрируются в моих журналах.



При попытке попасть (используя Postman) в конечную точку /oauth/authorize POST с помощью client_id=sambhav,response_type=code,redirect_uri=http://localhost:9001,scope=all, я получаю 500 ошибок в ответ на следующую ошибку: -



{"timestamp":1423055109697,"status":500,"error":"Internal Server Error","exception":"org.springframework.security.authentication.InsufficientAuthenticationException","message":"User must be authenticated with Spring Security before authorization can be completed.","path":"/oauth/authorize"}


Глядя на журналы, я вижу, что существует проверка подлинности в методе класса org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpointauthorize:-



@RequestMapping(value = "/oauth/authorize")
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
SessionStatus sessionStatus, Principal principal) {

// Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
// query off of the authorization request instead of referring back to the parameters map. The contents of the
// parameters map will be stored without change in the AuthorizationRequest object once it is created.
AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);

Set<String> responseTypes = authorizationRequest.getResponseTypes();

if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
}

if (authorizationRequest.getClientId() == null) {
throw new InvalidClientException("A client id must be provided");
}

try {
// THIS check causes the problem
if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
throw new InsufficientAuthenticationException(
"User must be authenticated with Spring Security before authorization can be completed.");
}


Задача



Почему для этапа авторизации требуется уже установленная аутентификация?



Чья авторизация (пользователя или клиента) требуется? Как мне это сделать? Используя комбинацию client_id/client_secret?

451   1  

1 ответ:

Грант authorization_code предоставляет клиенту доступ к ресурсному серверу, если это позволяет пользователь (он же владелец ресурса).

Вы пытаетесь получить доступ к странице, на которой пользователь может предоставить клиенту авторизацию, но вы не вошли в систему как пользователь, поэтому Spring Security не может знать , Кто должен авторизовать клиента (sambhav) в вашем примере.

Comments

    Ничего не найдено.