4

I would like to authenticate using username + password + domain(just a string).

Instead of having a unique username, it will be a unique combination of username + domain.

What is the best way to do this?

I'm using grails 2.3.7

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
froi
  • 7,268
  • 5
  • 40
  • 78
  • hey @user3025704 check the below link once http://stackoverflow.com/questions/16104228/how-implement-spring-security-when-login-page-having-more-field-apart-from-user – Srinivas Apr 28 '14 at 09:18

1 Answers1

4

Try something like this (code isn't tested):

@Component
public class BasicAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService registerService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String email = authentication.getName();
        String password = (String) authentication.getCredentials();
        String domain = (String) authentication.getDetails();

        User user = registerService.getUserByEmail(email);

        if (user == null) {
            throw new BadCredentialsException("Username not found.");
        }
        if (!password.equals(user.getPassword()) && !domain.equals(user.getDomain())) {
            throw new BadCredentialsException("Wrong password.");
        }

        Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        GrantedAuthority grantedAuthority = new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return user.getAuthority();
            }
        };
        authorities.add(grantedAuthority);

        return new UsernamePasswordAuthenticationToken(email, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}
Mufanu
  • 534
  • 7
  • 18