小编典典

具有Spring Security和Java配置的Custom Authentication Manager

spring-mvc

我将Spring
Security与SpringMVC结合使用来创建一个Web应用程序(为清楚起见,将其称为WebApp),该Web应用程序与现有应用程序(将其称为BackendApp)交谈。

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

为了实现这一点,我希望WebApp(运行Spring
Security)通过REST与用户以表单形式提供的用户名和密码通过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?

    }

}

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

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

在此先感谢您的协助。


阅读 382

收藏
2020-06-01

共1个答案

小编典典

看看下面的示例。您必须返回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 (!encoder.matches(password, user.getPassword())) {
        throw new BadCredentialsException("1000");
    }
    if (user.isDisabled()) {
        throw new DisabledException("1001");
    }
    List<Right> userRights = rightRepo.getUserRights(username);
    return new UsernamePasswordAuthenticationToken(username, null, userRights.stream().map(x -> new SimpleGrantedAuthority(x.getName())).collect(Collectors.toList()));
}

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()));
}

}
2020-06-01