Recently, the custom ClientDetails of Spring Security OAuth2 has been implemented in two ways.
- Implement ClientDetailsService and pass the value to BaseClientDetails and return
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
AuthClient authClient = authClientService.loadClientByClientId(clientId);
BaseClientDetails details = new BaseClientDetails(authClient.getClientId(),
authClient.getResourceIds(),
authClient.getScopes(),
authClient.getAuthorizedGrantTypes(),
authClient.getAuthorities(),
authClient.getRedirectUris());
details.setClientSecret(authClient.getClientSecret());
return details;
}
- Implement ClientDetails first and then ClientDetailsService
ClientDetails
public class MyClientDetails implements ClientDetails {
private AuthClientDetails client;
public MyClientDetails(AuthClientDetails client) {
this.client = client;
}
public MyClientDetails() {
}
/**
* The client id.
*
* @return The client id.
*/
@Override
public String getClientId() {
return client.getClientId();
}
......
ClientDetailsService
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
AuthClientDetails clientDetails = authClientDetailsMapper.selectClientDetailsByClientId(clientId);
if (clientDetails == null) {
throw new ClientRegistrationException("该客户端不存在");
}
MyClientDetails details = new MyClientDetails(clientDetails);
return details;
}
Relatively speaking, the flexibility of the second method will be much higher. In the process of use, there is a problem that the custom ClientDetails with the simplest dependency cannot return the token, and the returned value is null. The loadUserByUsername method of ClientDetailsUserDetailsService reports an error
After debug analysis, the problem is the return value of the custom ClientDetails permission set.
misspelling
@Override
public Collection<GrantedAuthority> getAuthorities() {
return (client.getAuthorities() != null && client.getAuthorities().trim().length() > 0) ?
AuthorityUtils.commaSeparatedStringToAuthorityList(client.getAuthorities()) : null;
}
This writing method will result in a Cannot pass a null GrantedAuthority collection error, the token cannot survive but there will be no error reporting
Correct spelling
@Override
public Collection<GrantedAuthority> getAuthorities() {
return (client.getAuthorities() != null && client.getAuthorities().trim().length() > 0) ?
AuthorityUtils.commaSeparatedStringToAuthorityList(client.getAuthorities()) : Collections.emptyList();
}
{{o.name}}
{{m.name}}