如何将自定义对象从自定义身份验证提供程序传递到控制器?

时间:2017-06-21 14:50:35

标签: spring rest spring-security

在Spring,我想将在我的自定义身份验证提供程序中创建的对象传递给我的控制器。我怎么能这样做?

@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

这是实现我想要的正确方法吗?我该如何解决这个错误?

1 个答案:

答案 0 :(得分:0)

好吧,我找到了解决问题的方法。以下是我所做的修复:

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