如何在Spring Boot Application中实现自定义身份验证

时间:2017-12-13 18:28:24

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

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

1 个答案:

答案 0 :(得分:0)

没有什么能阻止您以创造性方式使用授权标头,即通过将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应用程序