All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.lsn.spring.auth.provider.AuthenticationProvider Maven / Gradle / Ivy

There is a newer version: 2.2.0
Show newest version
package io.lsn.spring.auth.provider;

import io.lsn.spring.auth.entity.User;
import io.lsn.spring.auth.event.AuthenticatedEvent;
import io.lsn.spring.auth.service.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
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.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Patryk Szlagowski 
 */
@Component
public class AuthenticationProvider implements org.springframework.security.authentication.AuthenticationProvider {

    private UserProvider service;
    private ApplicationEventPublisher publisher;

    @Autowired
    public AuthenticationProvider(UserProvider service, ApplicationEventPublisher publisher) {
        this.service = service;
        this.publisher = publisher;
    }

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        User user = null;
        try {
            user = service.findByApiToken((String) authentication.getCredentials());
        } catch (Exception e) {
            throw new BadCredentialsException("unable to authenticate with given API TOKEN", e);
        }

        if (user == null) {
            throw new UnauthorizedException("There are no token such as given");
        }

        this.publisher.publishEvent(new AuthenticatedEvent(this, user));
        List authorities = null;
        if (user.getRoles() != null) {
            authorities = user.getRoles().stream().map(role -> new SimpleGrantedAuthority(role)).collect(Collectors.toList());
        }

        return new UsernamePasswordAuthenticationToken(user, null, authorities);
    }

    public boolean supports(Class authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy