具有Spring Security和Java配置的自定义验证管理器

Jef*_*f I 22 java spring spring-mvc spring-security

我正在使用Spring Security与SpringMVC创建一个Web应用程序(为了清楚起见,我将其称为WebApp),它与现有应用程序相对应(我将其称为BackendApp).

我想将身份验证职责委托给BackendApp(这样我就不需要同步这两个应用程序).

为了实现这一点,我希望WebApp(运行spring security)通过REST与用户在表单中提供的用户名和密码进行BackendApp通信,并根据BackendApp的响应是200 OK还是401 Unauthorized进行身份验证.

我知道我需要编写一个自定义的身份验证管理器来执行此操作,但我是一个很新的春天,无法找到有关如何实现它的任何信息.

我相信我需要做这样的事情:

public class CustomAuthenticationManager implements AuthenticationManager{

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

        String username = authentication.getName();
        String pw       = authentication.getCredentials().toString();

        // Code to make rest call here and check for OK or Unauthorised.
        // What do I return?

    }

}
Run Code Online (Sandbox Code Playgroud)

如果成功,我是否设置authentication.setAuthenticated(true),否则设置为false,那就是它?

编写完成后,如何配置spring security以使用java配置文件来使用此身份验证管理器?

在此先感谢您的任何帮助.

Hal*_*vic 33

看看下面的示例.您必须返回UsernamePasswordAuthenticationToken.它包含主体和GrantedAuthorities.希望我能帮忙:)

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getPrincipal() + "";
    String password = authentication.getCredentials() + "";

    User user = userRepo.findOne(username);
    if (user == null) {
        throw new BadCredentialsException("1000");
    }
    if (user.isDisabled()) {
        throw new DisabledException("1001");
    }
    if (!encoder.matches(password, user.getPassword())) {
        throw new BadCredentialsException("1000");
    }
    List<Right> userRights = rightRepo.getUserRights(username);
    return new UsernamePasswordAuthenticationToken(username, password, userRights.stream().map(x -> new SimpleGrantedAuthority(x.getName())).collect(Collectors.toList()));
}
Run Code Online (Sandbox Code Playgroud)

PS:userRepo和rightRepo是访问我的自定义User-DB的Spring-Data-JPA存储库

SpringSecurity JavaConfig:

@Configuration
@EnableWebMvcSecurity
public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {

public MySecurityConfiguration() {
    super(false);
}

@Override
protected AuthenticationManager authenticationManager() throws Exception {
    return new ProviderManager(Arrays.asList((AuthenticationProvider) new AuthProvider()));
}

}
Run Code Online (Sandbox Code Playgroud)


mel*_*ngs 5

最简单的:

@Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        String username = auth.getName();
        String password = auth.getCredentials().toString();
        // to add more logic
        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        return new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
    }
Run Code Online (Sandbox Code Playgroud)