Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.astarte.commons.security.apikey;
- import com.astarte.commons.db.model.Device;
- import com.astarte.commons.db.repository.DeviceJpaRepository;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.authentication.AuthenticationProvider;
- import org.springframework.security.authentication.BadCredentialsException;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.AuthenticationException;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.stereotype.Component;
- import java.util.Collection;
- @Component
- public class DeviceApiKeyAuthenticationProvider implements AuthenticationProvider {
- final static Logger logger = LoggerFactory.getLogger(DeviceApiKeyAuthenticationProvider.class);
- @Autowired
- DeviceJpaRepository deviceJpaRepository;
- @Override
- public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- String username = authentication.getName();
- String password = (String) authentication.getCredentials();
- logger.info("Logging in {}, {}", username, password);
- Device device = deviceJpaRepository.findByApiKeyAndHwId(password, username);
- if (device == null) {
- throw new BadCredentialsException("No such ID/ApiKey combination found.");
- }
- Collection<? extends GrantedAuthority> authorities = device.getAuthorities();
- UsernamePasswordAuthenticationToken realAuthentication =
- new UsernamePasswordAuthenticationToken(username, password, authorities);
- // Add device data
- realAuthentication.setDetails(device);
- return realAuthentication;
- }
- @Override
- public boolean supports(Class<?> aClass) {
- return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass));
- }
- }
Add Comment
Please, Sign In to add comment