0
votes

In spring, I would like to pass an object which is created in my custom authentication provider to my controller. How can I do that?

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

}

In my controller, I want to use this custom object:

  @RequestMapping(value = "/user", method = RequestMethod.GET)
        public String test(Object customObject) {
    //use customObject here
}

I tired to extend the UsernamePasswordAuthenticationToken this way, to create a custom token object:

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

When I return this token in my custom authentication provider, I get the following error:

No AuthenticationProvider found for com.example.demo.security.CustomAuthToken

Is this the right approach to achieve what I want? How can I fix this error?

1

1 Answers

0
votes

Well, I found a solution for my problem. Here are the fixed I did:

In CustomAuthToken class, edited constructor for extended class. I need to create the UsernamePasswordAuthenticationToken with 3 parameter, principal, credentials AND authorities :

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

}

In CustomAuthProvider class, return the customAuthToken object with the correct parameter::

... return new CustomAuthToken(email,password, new ArrayList<>(), object); ...

In the controller, set the correct parameter of type Authentication:

@RequestMapping(value = "/user", method = RequestMethod.GET)
    public String test(CustomAuthToken auth) {
System.out.println(auth.object.ToString());
}