【发布时间】:2021-11-19 19:33:02
【问题描述】:
我是 Spring Boot 应用程序开发的新手。 我需要将基本身份验证标头添加到 Spring Boot 中的所有 api 请求中。 任何人都可以分享我如何进行的有效文件
【问题讨论】:
标签: spring-boot spring-security
我是 Spring Boot 应用程序开发的新手。 我需要将基本身份验证标头添加到 Spring Boot 中的所有 api 请求中。 任何人都可以分享我如何进行的有效文件
【问题讨论】:
标签: spring-boot spring-security
这取决于你需要什么样的身份验证 对于自我身份验证令牌之类的东西,它看起来像
public String controllerFunction(@RequestHeader("Auth-header") String authToken){
if (authToken == null) {
log.error("Self token authentication failed");
throw new Exception(TOKEN_NOT_FOUND);
}
if (!"auth_password".equals(authToken)) {
log.error("Self token authentication failed");
throw new Exception(AUTH_FAILED);
}
log.info("Self token authentication successful");
}
如果它对单个用户来说是唯一的,你必须从你的数据库中为那个特定用户获取“auth_password”并验证它
要在全局范围内使用它,您可以像这样构建注释
@Before("@annotation(tokenValidation)")
public void beforeAdvice(TokenValidation tokenValidation) {
String authToken = request.getHeader("Auth-header");
if (authToken == null) {
log.error("Self token authentication failed");
throw new Exception(TOKEN_NOT_FOUND);
}
if (!"auth_password".equals(authToken)) {
log.error("Self token authentication failed");
throw new Exception(AUTH_FAILED);
}
log.info("Self token authentication successful");
}
你可能需要查看如何在spring boot中实现注释,但这是一个基本概念。
在控制器中,你只需要这样做
@tokenValidation
public String controllerFunction(String authToken){
//your code;
}
【讨论】: