JWT和表单身份验证都在一个SpringBoot应用程序中?



我有一个使用弹簧安全性的 spring 启动应用程序。我实现了基于表单的身份验证,效果很好。我希望该应用程序充当我构建的角度应用程序的后端。我知道 CORS,但我如何将 JWT 身份验证添加到现有的 Spring 启动应用程序中,是否推荐。

我会推荐AOP概念来验证/验证您的JWT令牌。

首先,您需要创建自定义注释。将其命名为 JWTsecured

@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface JwtSecured {
}

现在,您有一个控制器,其中需要对 API 进行 JWT 保护。

@RestController
public class YourController {
@GetMapping(value="/testApi")
@JWTsecured
public void isTestApi() {
}
}

现在你必须编写一个方面来验证你的令牌......


@Component
@Aspect
public class JWTsecuredAspect {
@Around(value =" @within(com.JWTSecured) || @annotation(com.JWTSecured)")
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {  
String token = request.getHeader("Authorization");
if(!isTokenValidated(token)){
throw CustomException("Invalid Token.")
}
}
}

这就是您可以将其与身份验证一起使用的方式。 还有其他几种方法。 随时联系

相关内容

最新更新