在春天,我想将在我的自定义身份验证提供程序中创建的对象传递给我的控制器。我怎样才能做到这一点?
@Component
public class CustomAuthProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String email = authentication.getName();
String password = authentication.getCredentials().toString();
// check authentication here....
// create custom object
Object customObject = ...
return new UsernamePasswordAuthenticationToken(email,password, customObject);
}
在我的控制器中,我想使用这个自定义对象:
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String test(Object customObject) {
//use customObject here
}
我厌倦了以这种方式扩展 UsernamePasswordAuthenticationToken 来创建自定义令牌对象:
public class CustomAuthToken extends
UsernamePasswordAuthenticationToken {
//object of any class
private Object customObject;
public CustomAuthToken(Object principal, Object credentials) {
super(principal, credentials);
this.customObject = null;
}
public CustomAuthToken(Object principal, Object credentials, Object customObject) {
super(principal, credentials);
this.customObject = customObject;
}
当我在自定义身份验证提供程序中返回此令牌时,出现以下错误:
未找到 com.example.demo.security.CustomAuthToken 的 AuthenticationProvider
这是实现我想要的正确方法吗?我该如何解决这个错误?
好吧,我找到了解决我的问题的方法。这是我所做的修复:
在 CustomAuthToken 类中,编辑了扩展类的构造函数。我需要使用 3 个参数、主体、凭据和权限创建 UsernamePasswordAuthenticationToken :
public class CustomAuthToken extends UsernamePasswordAuthenticationToken {
private Object object;
public CustomAuthToken(String principal, String credentials, Collection<? extends GrantedAuthority> authorities, Object object) {
super(principal, credentials, authorities);
this.object = object;
}
}
在 CustomAuthProvider 类中,返回带有正确参数的 customAuthToken 对象:
... return new CustomAuthToken(email,password, new ArrayList<>(), object); ...
在控制器中,设置正确的身份验证类型参数:
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String test(CustomAuthToken auth) {
System.out.println(auth.object.ToString());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句