У меня есть случай, когда мне нужно получить токен доступа без http-вызова к предварительно определенной конечной точке Oauth Spring Security /oauth/token, но вместо этого мне нужно вызвать какой-то API, доступный для анонимного пользователя, и среди других бизнес-данных принести токен доступа. назад.
Я пробую этот код:
String username = "username";
String password = "2134";
//
AccountInitSetting accountSetting = accountService.getInitSetting(username);
try {
agentService.createTempCredentials(username, accountSetting.getAccountType(),
null, accountSetting.getRoleId(), accountSetting.getGroupId(),
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("x-forwarded-for"),
null, false);
} catch (UserInterfaceException e) {
throw new RuntimeException(e);
}
Map<String, String> parameters = new HashMap<>();
parameters.put("grant_type","password");
parameters.put("username", username);
parameters.put("password", password);
parameters.put("scope","all");
try {
return tokenEndpoint.postAccessToken(principal, parameters).getBody().getValue();
} catch (HttpRequestMethodNotSupportedException e) {
throw new OAuth2Exception(e.getMessage(), e);
}
}
обратите внимание, что Principal берется из параметра метода конечной точки @RestController и, таким образом, передается этому методу.
И я получаю следующее исключение:
22:40:33.007 [http-bio-9090-exec-2] ERROR com.openpayment.site.web.service.init.WebServiceExceptionHandler - There is no client authentication. Try adding an appropriate authentication filter.
org.springframework.security.authentication.InsufficientAuthenticationException: There is no client authentication. Try adding an appropriate authentication filter.
Что мне не хватает?




Мне пришлось явно добавить новый Authentication с isAuthenticated() true и getName() в соответствии с ожиданиями приложения.
String username = "username";
String password = "2134";
Map<String, String> parameters = new HashMap<>();
parameters.put("grant_type","password");
parameters.put("username", username);
parameters.put("password", password);
//parameters.put("clientId","clientId4");
parameters.put("scope","all");
Principal principal1 = new Authentication() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getDetails() {
return null;
}
@Override
public Object getPrincipal() {
return null;
}
@Override
public boolean isAuthenticated() {
return true;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
@Override
public String getName() {
return "clientId4";
}
};
try {
return tokenEndpoint.postAccessToken(principal1, parameters).getBody().getValue();
} catch (HttpRequestMethodNotSupportedException e) {
throw new OAuth2Exception(e.getMessage(), e);
}
}