我有一个案例,我需要获取访问令牌,而不需要对 Oauth Spring Security 预定义的 http 调用
/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);
}
}