While i am try to implement response.redirect in jersey by using Response.temporaryRedirect(location) and Response.seeOther(location), But both are not working as like Servlet response.sendRedirect.
As i tried,
Java script :-
function loginFunction(){
var password=$("#password").val();
var username=$("#emailId").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax({
url:'/test/login/filter',
type:'GET',
crossDomain: true,
beforeSend : function(req) {
req.setRequestHeader('Authorization', make_base_auth(username, password));
},
success:function(res,status,xhr){
userToken=xhr.getResponseHeader("Authorization");
localStorage.setItem("userToken", userToken);
if(userToken != undefined || userToken != null){
window.location.href = "./index.html";
}else{
$('.errmsg').html('please provide a valid credentials.')
$(this).load();
}
},
error : function(jqXHR, textStatus, errorThrown) {
console.log("textStatus is:"+textStatus);
}
});
}
Jersey Code:-
@Path("/login")
public class UserLogin {
private static Map<String ,Token> tokTable=new HashMap<String ,Token>();
@GET
@Path("/filter")
public void filter(@Context ContainerRequestContext context){
String authentication = filterContext.getHeaderString(HttpHeaders.AUTHORIZATION);
if (authentication == null) {
throw new AuthenticationException("Authentication credentials are required");
}
if (!authentication.startsWith("Basic ")) {
return null;
}
authentication = authentication.substring("Basic ".length());
String[] values = new String(DatatypeConverter.parseBase64Binary(authentication), Charset.forName("ASCII")).split(":");
String username=null,givenPass=null;
try{
username = values[0];
givenPass=org.glassfish.jersey.internal.util.Base64.encodeAsString( values[1]);
}catch(Exception e){
throw new AuthenticationException("User name and password can't be empty\r\n");
}
}
User user = AuthLookUpTables.userTable.get(username);
// Validate the extracted credentials
if ( user == null ) {
logger.info("USER NOT AUTHENTICATED");
throw new AuthenticationException("Invalid username");
}
String password=org.glassfish.jersey.internal.util.Base64.encodeAsString(givenPass.concat(user.getSalt()));
if ((username == null) || (password == null)) {
throw new WebApplicationException(400);
}
String dbPass=org.glassfish.jersey.internal.util.Base64.encodeAsString(user.getHashedPassword().concat(user.getSalt()));
if ( dbPass.equals(password) ) {
logger.info("USER AUTHENTICATED");
//SOme code using for main sever.
} else {
logger.info("USER NOT AUTHENTICATED");
throw new AuthenticationException("Invalid username or password\r\n");
}
return user;
}
POJO (USER):-
public class User {
public String username;
public String roles;
public String salt;
public String hashedPassword;
//and below getter and setter methods
}
Custom Exception:-
public class AuthenticationException extends RuntimeException {
public AuthenticationException() {
super();
}
public AuthenticationException(String message) {
super(message);
}
}
Exception Mapper:-
@Provider
public class AuthenticationExceptionMapper implements ExceptionMapper<AuthenticationException> {
private Logger logger=Logger.getLogger(AuthenticationExceptionMapper.class);
@Context
UriInfo uriInfo;
public Response toResponse(AuthenticationException e) {
UriBuilder builder=null;
if (e.getMessage() != null) {
builder=UriBuilder.fromPath(uriInfo.getBaseUriBuilder().toString()).path("..");
return Response.temporaryRedirect(builder.build()).build();
} else {
return Response
.status(Status.UNAUTHORIZED)
.type("text/plain")
.entity(e.getMessage())
.build();
}
}
}
this is what i get in developer tool,
But, i am expecting server redirect to login page, how do i do that, kindly same one help me to do this. thank you