Currently, I generate a JWT from the SAML response, store it in the JwtResponse DTO, and send it to the frontend as part of the response, along with a redirect URL in the header indicating where the user should be redirected after authentication. However, after authentication, the JwtResponse is visible in the response of the URL (http://localhost:8080/login/saml2/sso/okta
).
What I want instead is to redirect the user to http://localhost:8080/home
and save the JwtResponse in localStorage for further use.How can I do that? I cannot sent the jwt in url query parameter. Kindly ignore that method (and also ignore usage of session cookies) and suggest any other method.
This is what i have tried:
@PostMapping("/auth")
public ResponseEntity<JwtResponse> handleSAMLLogin(Authentication authentication) {
Saml2AuthenticatedPrincipal principal = (Saml2AuthenticatedPrincipal) authentication.getPrincipal();
Map<String, Object> claims = new HashMap<>();
principal.getAttributes().forEach((key, value) -> {
claims.put(key, value.get(0));
});
JwtResponse jwtResponse = new JwtResponse(
samlAuthenticationSuccessHandler.generateSamlJWTToken(principal, claims)
);
return ResponseEntity
.ok()
.header("X-Redirect-URL", "/home")
.body(jwtResponse);
}
}
This is my frontend code which is not saving the response in the localStorage:
import axios from "axios";
export const initiateAuth = () => {
window.location.href = "http://localhost:8080/saml2/authenticate/okta";
};
export const handleAuthCallback = async () => {
try {
const response = await axios.get(
"http://localhost:8080/login/saml2/sso/okta",
{
headers: {
Accept: "application/json",
},
}
);
const { accessToken, tokenType } = response.data;
if (accessToken) {
localStorage.setItem("token", `${tokenType} ${accessToken}`);
localStorage.setItem("expiresIn", response.data.expiresIn);
axios.defaults.headers.common[
"Authorization"
] = `${tokenType} ${accessToken}`;
return true;
}
return false;
} catch (error) {
console.error("Failed to handle authentication callback", error);
return false;
}
};
export const isAuthenticated = () => {
const token = localStorage.getItem("token");
return !!token;
};
export const getToken = () => {
return localStorage.getItem("token");
};
export const logout = () => {
localStorage.removeItem("token");
localStorage.removeItem("expiresIn");
delete axios.defaults.headers.common["Authorization"];
};
axios.interceptors.request.use(
(config) => {
const token = getToken();
if (token) {
config.headers.Authorization = token;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
I am expecting to to redirect the user to http://localhost:8080/home
and save the JwtResponse in localStorage for further use. How can I do that?
Sanjana MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.