具有Spring Security和Java配置的自定义验证管理器
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了具有Spring Security和Java配置的自定义验证管理器,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2305字,纯文字阅读大概需要4分钟。
内容图文
![具有Spring Security和Java配置的自定义验证管理器](/upload/InfoBanner/zyjiaocheng/712/d5d3f778a4944b45816789a37677edc2.jpg)
我正在使用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?
}
}
如果成功,我是否设置authentication.setAuthenticated(true),否则设置为false,那就是它?
编写完成后,如何配置spring security以使用java配置文件来使用此身份验证管理器?
在此先感谢您的任何帮助.
解决方法:
看看下面的示例.您必须返回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()));
}
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()));
}
}
内容总结
以上是互联网集市为您收集整理的具有Spring Security和Java配置的自定义验证管理器全部内容,希望文章能够帮你解决具有Spring Security和Java配置的自定义验证管理器所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。