Home > Net >  Add Authorization Header Bearer Authentication to Spring Boot Controller
Add Authorization Header Bearer Authentication to Spring Boot Controller

Time:01-21

I want to add a token in the Authorization header as a Bearer token. But I dont want to have a custom interceptor class, I just want to have the logic in my Controller endpoint. i tried many things but it just didnt work for me anyone can help me? Here my code:

@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;
    }

for my sake i just created a hardcoded token that I want to have in the Auth Header as Bearer token, as you can see in my comments I tried several ways to solve this but it didnt work.

CodePudding user response:

Maybe you can try this:

@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");
}
  •  Tags:  
  • Related