【问题标题】:Spring Boot - Get controller method nameSpring Boot - 获取控制器方法名称
【发布时间】:2017-12-10 14:10:38
【问题描述】:

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

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(....));

【问题讨论】:

  • 你能分享一些代码吗?
  • 你在哪里打电话给你的authenticationManager.authenticate(....)
  • AuthenticationProvider 也可以是HandlerInterceptorAdapter 吗?我知道你能够告诉控制器和方法试图用HandlerMethod 调用
  • @Leffchik 这是我的自定义身份验证提供程序。当用户要对服务进行身份验证时调用此提供程序。这是由扩展 WebSecurityConfigurerAdapter 的类配置的。
  • 一般来说,这里的目标是从@DarrenForsythe 提到的某个地方获取HandlerMethod。但问题是,如果你在 servlet 过滤器的某个地方调用 authenticationManager.authenticate(....),那么我认为这是不可能的,因为在调用 DispatcherServlet 之前你不会调用 HandlerMetod(并且在所有过滤器之后调用 servlet.service()

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


【解决方案1】:

扩展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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2020-11-11
    • 2013-11-01
    • 1970-01-01
    • 2010-12-30
    相关资源
    最近更新 更多