Spring安全认证包含3个字段,而不仅仅是用户名和密码

时间:2014-04-28 09:01:09

标签: java grails spring-security multi-tenant

我想使用username + password + domain进行身份验证(只是一个字符串)。

它不是唯一的username,而是username + domain的唯一组合。

这样做的最佳方式是什么?

我正在使用grails 2.3.7

1 个答案:

答案 0 :(得分:4)

尝试这样的事情(代码未经过测试):

@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;
    }
}