Example of a servlet using multiple authentication types
The following Gosu servlet runs in the context of the PolicyCenter application, and uses either Guidewire authentication or HTTP basic authentication. This example servlet responds to URL substrings that start with the string /test. If an incoming URL matches that pattern, the servlet displays information from properties of the response object.
The following code demonstrates this technique in the service method, which calls a separate method to do the main work of the servlet. Optionally, to check the HTTP request type, call the getMethod method on the servlet request object.
package mycompany.test
uses gw.servlet.Servlet
uses javax.servlet.http.HttpServletRequest
uses javax.servlet.http.HttpServletResponse
uses javax.servlet.http.HttpServlet
@Servlet( \ path : String ->path.matches("/test(/.*)?"))
class TestingServlet extends HttpServlet {
override function service(req: HttpServletRequest, response: HttpServletResponse) {
//print("Beginning call to service()...")
// SESSION AUTH : Get user from session if the client is already signed in.
var user = gw.servlet.ServletUtils.getAuthenticatedUser(req, true)
//print("Session user result = " + user?.DisplayName)
// HTTP BASIC AUTH : If the session user cannot be authenticated, try HTTP Basic
if (user == null) {
try {
user = gw.servlet.ServletUtils.getBasicAuthenticatedUser(req)
//print("HTTP Basic user result = " + user?.DisplayName)
} catch (e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Unauthorized. HTTP Basic authentication error.")
return // Be sure to RETURN early because authentication failed!
}
}
if (user == null) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Unauthorized. No valid user with session context or HTTP Basic.")
return // Be sure to RETURN early because authentication failed!
}
// IMPORTANT: Execution reaches here only if a user succeeds with authentication.
// Insert main servlet code here before end of function, which ends servlet request
doMain(req, response, user )
}
// This method is called by our servlet AFTER successful authentication
private function doMain(req: HttpServletRequest, response: HttpServletResponse, user : User) {
assert(user != null)
var responseText = "REQUEST SUCCEEDED\n" +
"req.RequestURI: '${req.RequestURI}'\n" +
"req.PathInfo: '${req.PathInfo}'\n" +
"req.RequestURL: '${req.RequestURL}'\n" +
"authenticated user name: '${user.DisplayName}'\n"
// Debugging message to the console
//print(responseText)
// For output response
response.ContentType = "text/plain"
response.setStatus(HttpServletResponse.SC_OK)
response.Writer.append(responseText)
}
}
