Ich habe gelesen, dass das Speichern des Tokens in localStorage keine gute Idee ist, da es mit Javascript zugänglich und daher anfällig für Angriffe ist. Deshalb möchte ich JWT in einem Cookie mit den Flags httponly und secure speichern.
Das Problem besteht jedoch darin, dass die Angular-App und die Spring Boot-App auf unterschiedlichen Ursprüngen ausgeführt werden und daher die von Spring erhaltene Antwort kein Cookie setzen kann.
Ich möchte wissen, wie ich erreichen kann, dass meine API bei erfolgreicher Anmeldung ein Cookie für eine Angular-Anwendung setzt, die möglicherweise in einer anderen Domäne läuft.
Hier ist meine Authentifizierungsressource:
Code: Select all
@PostMapping("/login")
public ResponseEntity loginUser(@RequestBody LoginRequest request, HttpServletResponse res) {
LoginResponse response = new LoginResponse("this_is_my_token");
Cookie cookie = new Cookie("token", "this_is_my_token");
cookie.setPath("/");
cookie.setSecure(true);
cookie.setHttpOnly(true);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.addCookie(cookie);
return ResponseEntity.ok().body(response);
}
Code: Select all
@Bean
public WebMvcConfigurer cors() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:4200") //current angular host, later will be changed
.allowCredentials(true)
.allowedHeaders("*");
}
};
}
Code: Select all
@Injectable()
export class LoginSerivce {
private headers: HttpHeaders;
constructor(private http: HttpClient) {
this.headers = new HttpHeaders({
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": "true"
});
}
public getToken() {
const data = JSON.stringify({
email: "test",
geslo: "Test"
});
this.http.post("http://localhost:8080/v1/auth/login",
data, {headers: this.headers, withCredentials: true})
.toPromise()
.then(
(resp) => {
console.log(resp);
},
(err) => {
console.log("error: ", err);
}
);
}
}
Mobile version