【问题标题】:How to implement customized authentication in Spring Boot Application如何在 Spring Boot Application 中实现自定义身份验证
【发布时间】:2018-05-27 17:54:49
【问题描述】:

我正在使用 Spring Boot 构建一个 Web 应用程序。可以通过手机应用程序发出发布请求,以将 xml 形式的数据上传到云端。允许推送数据的手机必须是注册的公司手机。验证 API 调用的方法是在公司数据库中查找手机的 android ID。仅当 Android ID 存在时,它才会接受数据。这个想法是将android ID嵌入到请求的标头中。由于它不是一种典型的身份验证方式,我如何使用 Spring Security 来实现它?或者我们甚至不需要 Spring Security。只需从标头中提取 Android ID 并在数据库中查找即可。如果它不是有效的 ID,则拒绝该请求。任何建议都会有所帮助。

【问题讨论】:

    标签: authentication spring-boot spring-security http-headers


    【解决方案1】:

    没有什么可以阻止您以创造性的方式使用 Authorization 标头,即将 Android ID 嵌入其中。然后,为了向端点添加身份验证,您可以使用 AOP 拦截器:

    受保护的操作标记接口:

    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ProtectedOperation {
    }
    

    拦截器:

    @Aspect
    @Component
    public class SecurityAspect {
        private CorporateService corpService; // this is your custom service to check Android IDs
        @Autowired
        public SecurityAspect(CorporateService corpService) {
            this.corpService = corpService;
        }
        @Around("@annotation(operation)")
        public Object protectedOperationPermissionCheck(final ProceedingJoinPoint pjp, final ProtectedOperation operation) throws Throwable {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            String header = requestAttributes.getRequest().getHeader("Authorization");
            String androidId = // get the ID from header - try not to use existing authorization header formats like Bearer, Negotiate etc. to avoid collision with other authentication systems
            if (corpService.isAuthorized(androidId)) {
                return pjp.proceed();
            }
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.flushBuffer();
            return null;
        }
    }
    

    确保将 spring-boot-starter-aop 依赖项添加到您的 pom.xml,以获得 @Aspect 支持

    编辑:要保护端点,请在控制器中使用 @ProtectedOperation 注释端点方法,并将 @EnableAspectJAutoProxy 添加到 Spring Boot 应用程序

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 2020-12-05
      • 2013-08-15
      • 2017-03-17
      • 2021-04-21
      • 2018-04-09
      • 2015-09-18
      • 2017-11-02
      • 2014-12-04
      相关资源
      最近更新 更多