List of usage examples for javax.servlet.http HttpServletRequest getUserPrincipal
public java.security.Principal getUserPrincipal();
java.security.Principal
object containing the name of the current authenticated user. From source file:org.wso2.carbon.identity.application.authenticator.iwa.ntlm.IWAAuthenticator.java
@Override protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { //Get the authenticated user principle Principal principal = request.getUserPrincipal(); if (principal == null) { HttpSession session = request.getSession(false); if (session != null) { principal = (Principal) session.getAttribute(IWAServlet.PRINCIPAL_SESSION_KEY); invalidateSession(request);/*from w w w . j a v a 2s . c o m*/ } } if (principal == null || principal.getName() == null) { if (log.isDebugEnabled()) { log.debug("Authenticated principal is null. Therefore authentication is failed."); } throw new AuthenticationFailedException("Authentication Failed"); } String username = principal.getName(); username = username.substring(username.indexOf("\\") + 1); if (log.isDebugEnabled()) { log.debug( "Authenticate request received : AuthType - " + request.getAuthType() + ", User - " + username); } boolean isAuthenticated; UserStoreManager userStoreManager; // Check the authentication try { userStoreManager = (UserStoreManager) CarbonContext.getThreadLocalCarbonContext().getUserRealm() .getUserStoreManager(); isAuthenticated = userStoreManager.isExistingUser(MultitenantUtils.getTenantAwareUsername(username)); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new AuthenticationFailedException("IWAAuthenticator failed while trying to find user existence", e); } if (!isAuthenticated) { if (log.isDebugEnabled()) { log.debug("user authentication failed, user:" + username + " is not in the user store"); } throw new AuthenticationFailedException("Authentication Failed"); } username = FrameworkUtils.prependUserStoreDomainToName(username); context.setSubject(AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(username)); }
From source file:com.xinlei.core.app.cas.web.ProxyTicketSampleServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // NOTE: The CasAuthenticationToken can also be obtained using // SecurityContextHolder.getContext().getAuthentication() final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal(); // proxyTicket could be reused to make calls to to the CAS service even if the // target url differs final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl); // Make a remote call to ourselves. This is a bit silly, but it works well to // demonstrate how to use proxy tickets. final String serviceUrl = targetUrl + "?ticket=" + URLEncoder.encode(proxyTicket, "UTF-8"); String proxyResponse = CommonUtils.getResponseFromServer(new URL(serviceUrl), new HttpsURLConnectionFactory(), "UTF-8"); // modify the response and write it out to inform the user that it was obtained // using a proxy ticket. proxyResponse = proxyResponse.replaceFirst("Secure Page", "Secure Page using a Proxy Ticket"); proxyResponse = proxyResponse.replaceFirst("<p>", "<p>This page is rendered by " + getClass().getSimpleName() + " by making a remote call to the Secure Page using a proxy ticket (" + proxyTicket + ") and inserts this message. "); response.setContentType("text/html;charset=UTF-8"); final PrintWriter writer = response.getWriter(); writer.write(proxyResponse);//from w w w . ja va 2 s . c o m }
From source file:org.duracloud.duradmin.spaces.controller.SnapshotController.java
protected String getUsername(HttpServletRequest request) { String username = request.getUserPrincipal().getName(); return username; }
From source file:com.pararede.alfresco.security.AlfrescoContainerSecurityFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession httpSession = httpRequest.getSession(); String userName = httpRequest.getUserPrincipal().getName(); User userAuth = AuthenticationHelper.getUser(httpRequest, httpResponse); if ((userAuth == null) || !userName.equals(userAuth.getUserName())) { try {//from w ww . j ava 2s .c om TransactionService transactionService = this.registry.getTransactionService(); UserTransaction tx = transactionService.getUserTransaction(); try { tx.begin(); // remove the session invalidated flag (used to remove last username cookie by // AuthenticationFilter) httpSession.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED); if (logger.isDebugEnabled()) { logger.debug("Authenticating user " + userName); } AuthenticationService authenticationService = getAuthenticationService(); authenticationService.authenticate(userName, null); PersonService personService = this.registry.getPersonService(); userAuth = new User(userName, authenticationService.getCurrentTicket(), personService.getPerson(userName)); NodeService nodeService = this.registry.getNodeService(); NodeRef homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName), ContentModel.PROP_HOMEFOLDER); if (!nodeService.exists(homeSpaceRef)) { throw new InvalidNodeRefException(homeSpaceRef); } userAuth.setHomeSpaceId(homeSpaceRef.getId()); httpSession.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, userAuth); httpSession.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, true); tx.commit(); } catch (Throwable e) { tx.rollback(); throw new ServletException(e); } } catch (SystemException e) { throw new ServletException(e); } } else { if (logger.isDebugEnabled()) { logger.debug("User " + userName + " already authenticated"); } AuthenticationStatus status = AuthenticationHelper.authenticate(httpSession.getServletContext(), httpRequest, httpResponse, false); if (status != AuthenticationStatus.Success) { throw new ServletException("User not correctly autheticated"); } } chain.doFilter(request, response); }
From source file:org.rti.zcore.dar.struts.action.PatientItemListAction.java
/** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * Return an <code>ActionForward</code> instance describing where and how * control should be forwarded, or <code>null</code> if the response has * already been completed.//ww w . ja v a2s .c o m * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return Action to forward to * @throws Exception if an input/output error or servlet exception occurs */ protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Extract attributes we will need HttpSession session = request.getSession(); Principal user = request.getUserPrincipal(); String username = user.getName(); Connection conn = null; try { conn = DatabaseUtils.getZEPRSConnection(username); SessionSubject sessionPatient = null; try { sessionPatient = (SessionSubject) SessionUtil.getInstance(session).getSessionPatient(); } catch (SessionUtil.AttributeNotFoundException e) { log.error("Unable to get TimsSessionSubject"); } Long patientId = null; //Long eventId = null; String eventUuid = null; Long currentFlowId = null; try { assert sessionPatient != null; patientId = sessionPatient.getId(); //eventId = sessionPatient.getCurrentEventId(); eventUuid = sessionPatient.getCurrentEventUuid(); currentFlowId = sessionPatient.getCurrentFlowId(); } catch (Exception e) { log.error("Unable to get TimsSessionSubject field" + e); } if (eventUuid == null) { String forwardString = "/listEvents.do?patientId=" + patientId; ActionForward forwardForm = new ActionForward(forwardString); forwardForm.setRedirect(true); return forwardForm; } Long viewFlowId = null; // if flowId is in the request, set sessionPatient's flowId if (request.getParameter("flowId") != null) { viewFlowId = Long.decode(request.getParameter("flowId")); } else if (request.getAttribute("flowId") != null) { viewFlowId = Long.decode(request.getAttribute("flowId").toString()); } else { try { viewFlowId = currentFlowId; assert viewFlowId != null; if (viewFlowId.intValue() == 9) { // if it's new patient registration viewFlowId = new Long("132"); // send to history } } catch (Exception e) { // a test user w/ no flo - send to history. viewFlowId = new Long("132"); } } List items = null; Long formId = (Long) DynaSiteObjects.getFormNameMap().get("PatientItem"); Long flowId = Long.valueOf(2); items = PatientItemDAO.getPatientItemList(conn, patientId, eventUuid, flowId, formId); request.setAttribute("items", items); Boolean status = Boolean.valueOf(true); List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("activeProblems", activeProblems); // now get inactive problems status = Boolean.valueOf(false); List inactiveProblems = PatientRecordUtils.assembleProblemTaskList(conn, patientId, eventUuid, status, sessionPatient); request.setAttribute("inactiveProblems", inactiveProblems); conn.close(); } catch (ServletException e) { log.error(e); } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } return mapping.findForward("success"); }
From source file:se.nrm.dina.data.service.DinaService.java
private int getAgentIdToken(HttpServletRequest req) { Principal userPrincipal = req.getUserPrincipal(); if (userPrincipal instanceof KeycloakPrincipal) { KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) userPrincipal; Map<String, Object> map = kp.getKeycloakSecurityContext().getToken().getOtherClaims(); try {//from w ww . j a va2s . co m String strId = (String) map.get("agentId"); return Integer.parseInt(strId); } catch (NumberFormatException e) { throw new DinaException("Wrong agent id", 400); } } else { throw new RuntimeException(); } }
From source file:AuthenticationSnoop.java
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML><BODY>"); out.println("<H1>This is a password protected resource</H1>"); out.println("<PRE>"); out.println("User Name: " + req.getRemoteUser()); String name = (req.getUserPrincipal() == null) ? null : req.getUserPrincipal().getName(); out.println("Principal Name: " + name); out.println("Authentication Type: " + req.getAuthType()); out.println("Is a Manager: " + req.isUserInRole("manager")); out.println("</PRE>"); out.println("</BODY></HTML>"); }
From source file:org.opendaylight.controller.web.DaylightWebAdmin.java
@RequestMapping(value = "/users/{username}", method = RequestMethod.POST) @ResponseBody/*from w w w. j av a 2s. co m*/ public Status removeLocalUser(@PathVariable("username") String userName, HttpServletRequest request) { String loggedInUser = request.getUserPrincipal().getName(); if (loggedInUser.equals(userName)) { String msg = "Invalid Request: User cannot delete itself"; return new Status(StatusCode.NOTALLOWED, msg); } IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); if (userManager == null) { return new Status(StatusCode.NOSERVICE, "User Manager unavailable"); } if (!authorize(userManager, UserLevel.NETWORKADMIN, request)) { return new Status(StatusCode.UNAUTHORIZED, "Operation not permitted"); } Status status = userManager.removeLocalUser(userName); if (status.isSuccess()) { DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), "removed", userName); return status; } return status; }
From source file:photosharing.api.LoginServlet.java
/** * Manages the authorization for a given user, creates a session or returns session invalid * // w ww . j a va2 s. co m * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * Checks to see if the User is logged in forces logout for any existing user, you wouldn't actually do this in production */ Principal user = request.getUserPrincipal(); if (user != null) { HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } request.logout(); } /* * Authorizes the User */ String auth = request.getHeader("Authorization"); if (auth != null && !auth.isEmpty()) { auth = auth.replace("Basic ", ""); String authDecoded = new String(Base64.decodeBase64(auth)); String[] creds = authDecoded.split(":"); String username = creds[0]; String password = creds[1]; try { request.login(username, password); request.getSession(true); } catch (Exception e) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } } else { response.setStatus(HttpStatus.SC_BAD_REQUEST); } }