Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Java to return the 401 Unauthorized response code explicitly

I am working on a web service. I want to return the 401: Unauthorized response to the user for invalid credentials.

How do I manually return this response code?

like image 643
Patan Avatar asked Jan 18 '13 06:01

Patan


People also ask

How do I return a 401k in Java?

For error status codes like 401, use the more specific sendError(): httpResponse. sendError(HttpServletResponse. SC_UNAUTHORIZED, "your message goes here");

What kind of HTTP response code is 401 unauthorized )?

The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.

Why is 401 unauthorized instead of unauthenticated?

If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. 403 Forbidden: The server understood the request, but is refusing to fulfill it. From your use case, it appears that the user is not authenticated.


1 Answers

assuming you are using servlets, you would set the http status to 401 using the setStatus method:

httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

HttpServletResponse info

like image 106
Austin Greco Avatar answered Oct 06 '22 15:10

Austin Greco