2017-06-21 78 views
0

在春天,我想將我的自定義身份驗證提供程序中創建的對象傳遞給我的控制器。我怎樣才能做到這一點?如何將自定義對象從自定義身份驗證提供程序傳遞到控制器?

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

當我在我的自定義身份驗證提供程序中返回此令牌,出現以下錯誤:

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

這是實現我想要的正確方法嗎?我該如何解決這個錯誤?

回答

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()); 
} 
相關問題