将授权 Header 承载身份验证添加到 Spring 引导控制器
Add Authorization Header Bearer Authentication to Spring Boot Controller
我想在授权中添加一个令牌 header 作为不记名令牌。但我不想拥有自定义拦截器 class,我只想在我的 Controller 端点中包含逻辑。我尝试了很多东西,但它对我不起作用任何人都可以帮助我吗?这是我的代码:
@PostMapping("/signIn")
public String signIn(HttpServletResponse response, HttpServletRequest request,
@RequestParam String username, @RequestParam String password,
@RequestHeader HttpHeaders headers) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
= new UsernamePasswordAuthenticationToken(username, password);
String bearerToken = request.getHeader("Authorization");
String token = "hardcodedToken";
// headers.getFirst(HttpHeaders.AUTHORIZATION);
//headers.setBearerAuth(token);
//response.setHeader("Authorization", token);
//response.addHeader("Authorization", token);
headers.set("Authorization", bearerToken);
return token;
}
为了我的缘故,我刚刚创建了一个硬编码令牌,我想在 Auth Header 中将其作为 Bearer 令牌,正如您在我的评论中看到的那样,我尝试了几种方法来解决这个问题,但没有奏效。
也许你可以试试这个:
@GetMapping("/response-builder-with-http-headers")
public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Baeldung-Example-Header",
"Value-ResponseEntityBuilderWithHttpHeaders");
return ResponseEntity.ok()
.headers(responseHeaders)
.body("Response with header using ResponseEntity");
}
我想在授权中添加一个令牌 header 作为不记名令牌。但我不想拥有自定义拦截器 class,我只想在我的 Controller 端点中包含逻辑。我尝试了很多东西,但它对我不起作用任何人都可以帮助我吗?这是我的代码:
@PostMapping("/signIn")
public String signIn(HttpServletResponse response, HttpServletRequest request,
@RequestParam String username, @RequestParam String password,
@RequestHeader HttpHeaders headers) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
= new UsernamePasswordAuthenticationToken(username, password);
String bearerToken = request.getHeader("Authorization");
String token = "hardcodedToken";
// headers.getFirst(HttpHeaders.AUTHORIZATION);
//headers.setBearerAuth(token);
//response.setHeader("Authorization", token);
//response.addHeader("Authorization", token);
headers.set("Authorization", bearerToken);
return token;
}
为了我的缘故,我刚刚创建了一个硬编码令牌,我想在 Auth Header 中将其作为 Bearer 令牌,正如您在我的评论中看到的那样,我尝试了几种方法来解决这个问题,但没有奏效。
也许你可以试试这个:
@GetMapping("/response-builder-with-http-headers")
public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Baeldung-Example-Header",
"Value-ResponseEntityBuilderWithHttpHeaders");
return ResponseEntity.ok()
.headers(responseHeaders)
.body("Response with header using ResponseEntity");
}