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

新手上路,请多包涵

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

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

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

我知道我需要编写一个自定义身份验证管理器来执行此操作,但是我对 spring 还很陌生,找不到有关如何实现它的任何信息。

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

 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 ,仅此而已?

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

在此先感谢您的帮助。

原文由 nbdy_ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 432
2 个回答

看看我下面的示例。您必须返回一个 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 是 Spring-Data-JPA 存储库,它访问我的自定义用户数据库

SpringSecurity Java配置:

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

}

原文由 Halko Karr-Sajtarevic 发布,翻译遵循 CC BY-SA 4.0 许可协议

最简单的:

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

原文由 mel3kings 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题