Spring Boot - 获取控制器方法名称

时间:2017-07-06 14:00:36

标签: java spring spring-mvc spring-boot spring-security

如何在自定义身份验证提供程序中获取控制器类的被调用方法名称?

REST请求正在调用控制器方法,此请求在自定义身份验证提供程序中进行身份验证。如何在提供程序中获取控制器类的方法名称?

这是我的控制器方法:

@RequestMapping(value = "/customer", method = RequestMethod.GET)
@ResponseBody
public String getAllCustomers() {
    return "Get customers...";
}

这是我的自定义身份验证提供程序,我想在这里获取被调用控制器方法的名称:

@Component
public class CustomAuthProvider implements AuthenticationProvider {

@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

// ...
// get controller method here... -> getAllCustomers

return UsernamePasswordToken(username, password)
}

我的身份验证提供程序由一个类配置,该类扩展了WebSecurityConfigurerAdapter类。

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private CustomAuthProvider customAuthProvider;


    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(this.customAuthProvider);

    }

自定义身份验证提供程序返回CustomAuthToken类的对象,该对象退出UsernamePasswordAuthenticationToken。我没有打电话给authenticationManager.authenticate(new MyCustomAuthenticationToken(....));

1 个答案:

答案 0 :(得分:0)

扩展RequestMappingHandlerMapping并跟踪方法

protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
    RequestMappingInfo info = super.getMappingForMethod(method, handlerType);

    return info;
}

RequestMappingInfo保留方法的路径。只需将信息存储在地图中即可在您的提供商中使用。 RequestMappingHandlerMapping可以自动装配。

请参阅How to optimize my code in Spring MVC Controller using @RequestMapping?