1 22 package org.jboss.test.web.servlets; 23 24 import java.io.IOException ; 25 import java.io.PrintWriter ; 26 import java.security.Principal ; 27 import java.util.Set ; 28 import javax.naming.InitialContext ; 29 import javax.naming.NamingException ; 30 import javax.security.auth.Subject ; 31 import javax.servlet.ServletException ; 32 import javax.servlet.http.HttpServlet ; 33 import javax.servlet.http.HttpServletRequest ; 34 import javax.servlet.http.HttpServletResponse ; 35 import javax.servlet.http.HttpSession ; 36 37 import org.jboss.logging.Logger; 38 39 43 public class SubjectServlet extends HttpServlet 44 { 45 static Logger log = Logger.getLogger(SubjectServlet.class); 46 47 protected void processRequest(HttpServletRequest request, HttpServletResponse response) 48 throws ServletException , IOException 49 { 50 Principal user = request.getUserPrincipal(); 51 HttpSession session = request.getSession(false); 52 Subject userSubject = null; 53 try 54 { 55 userSubject = getActiveSubject(); 56 if( userSubject == null ) 57 throw new ServletException ("Active subject was null"); 58 response.addHeader("X-SubjectServlet", userSubject.toString()); 59 } 60 catch(NamingException e) 61 { 62 throw new ServletException ("Failed to lookup active subject", e); 63 } 64 response.setContentType("text/html"); 65 PrintWriter out = response.getWriter(); 66 out.println("<html>"); 67 out.println("<head><title>SecureServlet</title></head>"); 68 out.println("<h1>SecureServlet Accessed</h1>"); 69 out.println("<body>"); 70 out.println("You have accessed this servlet as user:"+user); 71 if( session != null ) 72 out.println("<br>The session id is: "+session.getId()); 73 else 74 out.println("<br>There is no session"); 75 out.println("<br>Subject: "+userSubject); 76 out.println("</body></html>"); 77 out.close(); 78 } 79 80 protected void doGet(HttpServletRequest request, HttpServletResponse response) 81 throws ServletException , IOException 82 { 83 processRequest(request, response); 84 } 85 86 protected void doPost(HttpServletRequest request, HttpServletResponse response) 87 throws ServletException , IOException 88 { 89 processRequest(request, response); 90 } 91 92 protected Subject getActiveSubject() throws NamingException 93 { 94 InitialContext ctx = new InitialContext (); 95 Subject s = (Subject ) ctx.lookup("java:comp/env/security/subject"); 96 return s; 97 } 98 } 99 | Popular Tags |