简体   繁体   中英

Spring Boot two ways for Authentication: Combine LDAP and token based auth

For my RESTfulll application, we need to have two kinds of authentications. One is based on LDAP for all internal employees. This is recently implemented and working fine. For all external employees we need some token based authentication.

What do I mean with that? These employees will get send a generated token via email, this token is stored with an expiry date in our database. The employees should be able to “login” with that token. So what would be the best way to implement something like that?

My first thought was to build an additional ExternalAuthenticationProvider and add this to the security conf. This works, the users can login with the token as their username , they get the JWT. But when they like to access any resources, the response is a HTTP 403 -error. For me this implementation looks like a dirty hack, I don't like the approach, maybe there is better one.

Thanks for any advices.

@Component
public class ExternalAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private ExternalEffortLinkManagementRepository externalEffortLinkManagementRepository;

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        Collection<GrantedAuthority> gas = new HashSet<GrantedAuthority>();
        String userToken = auth.getName();

        ExternalEffortLinkManagement token = externalEffortLinkManagementRepository.getByLink(userToken);

        if (token != null && token.isActive()) {
            gas.add(new SimpleGrantedAuthority(SecurityConstants.ROLE_EXTERNAL));
            return new UsernamePasswordAuthenticationToken(userToken, null, gas);
        } else {
            throw new
                    BadCredentialsException("External system authentication failed");
        }
    }

    @Override
    public boolean supports(Class<?> auth) {
        return auth.equals(UsernamePasswordAuthenticationToken.class);
    }
}

I found the error:

Snippet 1:

gas.add(new SimpleGrantedAuthority(SecurityConstants.ROLE_EXTERNAL)); // ROLE_EXTERNAL = "EXTERNAL"

was replaced with

Snippet 2:

gas.add(new SimpleGrantedAuthority("ROLE_" + SecurityConstants.ROLE_EXTERNAL));

I have used the same code (Snippet 1) for the LDAP authentication, so I just passed the string "EXTERNAL" to the SimpleGrantedAuthority constructor. But I did this within my CustomLdapAuthoritiesPopulator , seems like spring adds the ROLE_ -prefix somehow in the hidden code. But this did not work with my ExternalAuthenticationProvider , there it was necessary to add ROLE_ to the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM