ApiTokenDetailsServiceImpl.java
/*
* Copyright 2023 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.spring.security.service;
import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.service.OAuthClientService;
import org.genesys.blocks.security.model.AclSid;
import org.genesys.blocks.tokenauth.service.ApiTokenService;
import org.genesys.blocks.tokenauth.spring.ApiTokenAuthenticationToken;
import org.genesys.blocks.tokenauth.spring.ApiTokenDetailsService;
import org.genesys.server.model.impl.User;
import org.genesys.server.service.UserService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class ApiTokenDetailsServiceImpl implements ApiTokenDetailsService {
private final ApiTokenService apiTokenService;
private final UserService userService;
private final OAuthClientService clientService;
public ApiTokenDetailsServiceImpl(ApiTokenService apiTokenService, UserService userService, OAuthClientService clientService) {
this.apiTokenService = apiTokenService;
this.userService = userService;
this.clientService = clientService;
}
@Override
public ApiTokenDetails<? extends AclSid> loadUserDetails(ApiTokenAuthenticationToken token) throws UsernameNotFoundException {
var apiToken = apiTokenService.getToken(apiTokenService.encodeToken(String.valueOf(token.getCredentials())));
if (apiToken == null) {
throw new UsernameNotFoundException("API Token not found");
}
var sid = apiToken.getSid();
if (sid instanceof User) {
User user = (User) userService.loadUserByUsername(((User) sid).getUsername());
return new ApiTokenUserDetails(user, apiToken);
} else if (sid instanceof OAuthClient) {
OAuthClient client = clientService.loadClientByClientId(((OAuthClient) sid).getClientId());
return new ApiTokenClientDetails(client, apiToken);
} else {
return null;
}
}
}