问题
I am building a web app with Spring Boot. Post requests can be made by a phone app to upload data in form of xml to the cloud. The phones that are allowed to push data are required to be registered company phones. The way to authenticate the APIs calls is to look up the android ID of the phone in a corporate database. It will accept the data only if the Android ID exists. The idea is to embed the android ID in the header of requests. Since it is not a typical way for authentication, how do I implement it with Spring Security? Or we don't even need Spring Security. Just extract the Android ID from the header and look it up in database. Reject the request if it is not a valid ID. Any advice would help.
回答1:
Nothing prevents you from using Authorization header in a creative way, i.e., by embedding the Android ID into it. Then, in order to add authentication to your endpoints, you can use an AOP interceptor:
Protected operation marker interface:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ProtectedOperation {
}
Interceptor:
@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;
}
}
Make sure to add the spring-boot-starter-aop dependency to your pom.xml, for @Aspect support
EDIT: to protect an endpoint, annotate the endpoint method in your controller with @ProtectedOperation, and add @EnableAspectJAutoProxy to your Spring Boot application
来源:https://stackoverflow.com/questions/47799859/how-to-implement-customized-authentication-in-spring-boot-application