io.lsn.spring.auth.service.UserProviderService Maven / Gradle / Ivy
package io.lsn.spring.auth.service;
import io.lsn.spring.auth.authentication.strategy.AuthenticationStrategy;
import io.lsn.spring.auth.configuration.properties.SecurityProperties;
import io.lsn.spring.auth.entity.User;
import io.lsn.spring.utilities.configuration.condition.ConditionalOnConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Patryk Szlagowski
*/
@ConditionalOnConfiguration(name = "io.lsn.spring.auth", type = ConditionalOnConfiguration.Type.SERVICE)
@Service
public class UserProviderService implements UserProvider {
@Autowired
private AbstractUserService service;
@Autowired
private SecurityProperties properties;
@Autowired
private List authenticationStrategies;
@Autowired
private AuthenticationManager authenticationManager;
@Override
public User findByApiToken(String token) throws Exception {
return service.findByApiToken(token);
}
@Override
public User findByUsername(String username) throws Exception {
return service.findByUsername(username);
}
@Override
public void terminateApiToken(User user) throws Exception {
service.terminateApiToken(user);
}
@Override
public void authenticate(User user, String password) throws Exception {
boolean match = authenticationStrategies
.stream()
.filter(strategy -> strategy.supports(user.getAuthenticationStrategy()))
.map(strategy -> strategy.authenticate(user, password))
.collect(Collectors.toList())
.get(0);
if (!match) {
throw new BadCredentialsException("");
}
assignNewApiToken(user);
authenticateIntoContext(user);
}
/**
* Authenticate into spring context
*
* @param user
*/
private void authenticateIntoContext(User user) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, user.getApiToken().getToken());
Authentication auth = authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(auth);
}
@Override
public void assignNewApiToken(User user) throws Exception {
service.assignNewApiToken(user);
}
@Override
public void extendExistingApiToken(User user) throws Exception {
user.getApiToken().calculateDate(properties.getToken().getTtlForRenewal());
service.updateApiToken(user);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy