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.nuxeo.ecm.platform.oauth2.providers.NuxeoOAuth2ServiceProvider.java
/** * Retrieves or creates a service user./*from ww w . jav a2 s. com*/ * Should be overriden by subclasses wanting to rely on a different field as key. */ protected String getOrCreateServiceUser(HttpServletRequest request, String accessToken) throws IOException { String nuxeoLogin = request.getUserPrincipal().getName(); String userId = getServiceUserId(nuxeoLogin); if (userId == null) { userId = getServiceUserStore().store(nuxeoLogin); } return userId; }
From source file:org.apache.juddi.v3.auth.HTTPContainerAuthenticator.java
@Override public UddiEntityPublisher identify(String authInfoNotused, String authorizedNameNotused, WebServiceContext ctx) throws AuthenticationException, FatalErrorException { int MaxBindingsPerService = -1; int MaxServicesPerBusiness = -1; int MaxTmodels = -1; int MaxBusinesses = -1; try {/*from ww w .j a v a2 s .com*/ MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } catch (Exception ex) { MaxBindingsPerService = -1; MaxServicesPerBusiness = -1; MaxTmodels = -1; MaxBusinesses = -1; log.error("config exception! ", ex); } EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { String user = null; if (ctx == null) throw new UnknownUserException( new ErrorMessage("errors.auth.NoPublisher", "no web service context!")); if (ctx.getUserPrincipal() != null) { user = ctx.getUserPrincipal().getName(); } if (user == null) { MessageContext mc = ctx.getMessageContext(); HttpServletRequest req = null; if (mc != null) { req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); } if (req != null && req.getUserPrincipal() != null) { user = req.getUserPrincipal().getName(); } } if (user == null || user.length() == 0) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher")); } tx.begin(); Publisher publisher = em.find(Publisher.class, user); if (publisher == null) { log.warn("Publisher \"" + user + "\" was not found in the database, adding the publisher in on the fly."); publisher = new Publisher(); publisher.setAuthorizedName(user); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(MaxBindingsPerService); publisher.setMaxBusinesses(MaxBusinesses); publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); publisher.setMaxTmodels(MaxTmodels); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } return publisher; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.nuxeo.ecm.liveconnect.dropbox.DropboxBlobUploader.java
private boolean hasServiceAccount() { HttpServletRequest request = getHttpServletRequest(); String username = request.getUserPrincipal().getName(); DropboxOAuth2ServiceProvider provider = getDropboxBlobProvider().getOAuth2Provider(); return provider != null && provider.getServiceUser(username) != null; }
From source file:org.onehippo.forge.security.support.springsecurity.container.SpringSecurityValve.java
@Override public void invoke(ValveContext context) throws ContainerException { HttpServletRequest request = context.getServletRequest(); Principal userPrincipal = request.getUserPrincipal(); // If user has not been authenticated yet by any mechanism, then simply move to the next valve chain. if (userPrincipal == null) { if (log.isDebugEnabled()) { log.debug("No user principal found. Skipping SpringSecurityValve..."); }// w w w .j a va2 s.co m context.invokeNext(); return; } // Get the current subject from http session if exists. HttpSession session = request.getSession(false); Subject subject = (session != null ? (Subject) session.getAttribute(ContainerConstants.SUBJECT_ATTR_NAME) : null); // If a subject has been established already (normally by HST-2's SecurityValve), then simply move to the next valve chain. if (subject != null) { if (log.isDebugEnabled()) { log.debug("Already subject has been created somewhere before. Skipping SpringSecurityValve..."); } context.invokeNext(); return; } // Get Spring Security Context object from thread local. SecurityContext securityContext = SecurityContextHolder.getContext(); // If there's no Spring Security Context object, then just move to next valve chain. if (securityContext == null) { if (log.isDebugEnabled()) { log.debug("Spring Security hasn't established security context. Skipping SpringSecurityValve..."); } context.invokeNext(); return; } // Get the Authentication object from the Spring Security context object. Authentication authentication = securityContext.getAuthentication(); // If there's no Authentication object, it's really weird, so leave warning logs, and move to next valve chain. if (authentication == null) { if (log.isWarnEnabled()) { log.warn( "Spring Security hasn't establish security context with authentication object. Skipping SpringSecurityValve..."); } context.invokeNext(); return; } // Get principal object from the Spring Security authentication object. Object springSecurityPrincipal = authentication.getPrincipal(); // We expect the principal is instance of UserDetails. Otherwise, let's skip it and leave warning logs. if (!(springSecurityPrincipal instanceof UserDetails)) { if (log.isWarnEnabled()) { log.warn( "Spring Security hasn't establish security context with UserDetails object. We don't support non UserDetails authentication. Skipping SpringSecurityValve..."); } context.invokeNext(); return; } // Cast principal instance to UserDetails UserDetails userDetails = (UserDetails) springSecurityPrincipal; // Create HST-2 TransientUser principal from the user principal. User user = new TransientUser(userPrincipal.getName()); // Add both the existing user principal and new HST-2 user transient user principal // just for the case when HST-2 can inspect the user principals for some reasons. Set<Principal> principals = new HashSet<Principal>(); principals.add(userPrincipal); principals.add(user); // Retrieve all the granted authorities from the UserDetail instance // and convert it into HST-2 TransientRoles. for (GrantedAuthority authority : userDetails.getAuthorities()) { String authorityName = authority.getAuthority(); if (!StringUtils.isEmpty(authorityName)) { principals.add(new TransientRole(authorityName)); } } Set<Object> pubCred = new HashSet<Object>(); Set<Object> privCred = new HashSet<Object>(); // If the flag is turned on, then store JCR credentials as well // just for the case the site is expected to use session stateful JCR sessions per authentication. if (storeSubjectRepositoryCredentials) { Credentials subjectRepoCreds = null; // Note: password should be null by default from some moment after Spring Security version upgraded a while ago. // if password is null, let's store a dummy password instead. if (userDetails.getPassword() != null) { subjectRepoCreds = new SimpleCredentials(userDetails.getUsername(), userDetails.getPassword().toCharArray()); } else { subjectRepoCreds = new SimpleCredentials(userDetails.getUsername(), DUMMY_CHARS); } privCred.add(subjectRepoCreds); } subject = new Subject(true, principals, pubCred, privCred); // Save the created subject as http session attribute which can be read by HST-2 SecurityValve in the next valve chain. request.getSession(true).setAttribute(ContainerConstants.SUBJECT_ATTR_NAME, subject); context.invokeNext(); }
From source file:com.lmco.ddf.ui.Query.java
/** * Gets the CAS proxy ticket that will be used by the STS to get a SAML * assertion.//from w w w . jav a2 s . c om * * @param request The Http servlet request. * @return Returns the CAS proxy ticket that will be used by the STS to get * a SAML assertion. */ private String getProxyTicket(HttpServletRequest request) { AttributePrincipal attributePrincipal = (AttributePrincipal) request.getUserPrincipal(); String proxyTicket = null; if (attributePrincipal != null) { // proxyTicket = attributePrincipal.getProxyTicketFor( // "https://server:8993/ddf/query/sts" ); LOGGER.debug("Getting proxy ticket for " + STS_SERVICE_URL); proxyTicket = attributePrincipal.getProxyTicketFor(STS_SERVICE_URL); LOGGER.info("proxy ticket: " + proxyTicket); } else { LOGGER.error("attribute principal is null!"); } return proxyTicket; }
From source file:pl.fraanek.caspresentation.client.springsecurity.ProxyTicketSampleServlet.java
@Override protected 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 ourself. 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(serviceUrl, "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. "); final PrintWriter writer = response.getWriter(); writer.write(proxyResponse);/* w w w . jav a 2s . co m*/ }
From source file:org.wso2.carbon.identity.application.authenticator.iwa.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(IWAServelet.PRINCIPAL_SESSION_KEY); }/*from www. j a v a2 s . 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:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Principal principal = request.getUserPrincipal(); if (principal == null) { throw new ServletException("Spreadsheet upload attempt: no user associated with the request"); }/*w w w.j a v a 2 s .c o m*/ SubmitJobResponse jobResponse = new SubmitJobResponse(); String value; try { Long jobId = submitJob(request, principal); jobResponse.setJobId(jobId); } catch (ParseException ex) { jobResponse.setMessage("The date range you specified is invalid."); jobResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); jobResponse.setErrorThrown("Bad request"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } catch (ClientException | FileUploadException | IOException ex) { String msg = "Upload failed due to an internal error"; jobResponse.setMessage(msg); jobResponse.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); jobResponse.setErrorThrown("Internal server error"); log("Upload failed for user " + principal.getName(), ex); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } value = MAPPER.writeValueAsString(jobResponse); response.setContentLength(value.length()); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.println(value); }
From source file:org.opendaylight.controller.web.DaylightWebAdmin.java
/** * Is the operation permitted for the given level * * @param level//from w w w .ja va 2 s . c o m */ private boolean authorize(IUserManager userManager, UserLevel level, HttpServletRequest request) { String username = request.getUserPrincipal().getName(); UserLevel userLevel = userManager.getUserLevel(username); return userLevel.toNumber() <= level.toNumber(); }
From source file:org.keycloak.secretstore.boundary.QRCodeServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String tokenIdAsString = req.getParameter("tokenId"); String sizeAsString = req.getParameter("size"); Principal principal = req.getUserPrincipal(); int size = 250; if (null != sizeAsString && !sizeAsString.isEmpty()) { try {//from ww w. j a v a 2s .c o m size = Integer.parseInt(req.getParameter("size")); } catch (Throwable t) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Size is invalid."); return; } } if (null == tokenIdAsString || tokenIdAsString.isEmpty()) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Token key is missing."); return; } UUID tokenId; try { tokenId = UUID.fromString(tokenIdAsString); } catch (Throwable t) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Token key is invalid."); return; } Token token = tokenService.getByIdForDistribution(tokenId); if (null == token) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Token could not be found."); return; } if (!principal.getName().equals(token.getPrincipal())) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Token could not be found for principal."); return; } String response = token.getId().toString() + "," + token.getSecret(); if (null != token.getExpiresAt()) { response += "," + token.getExpiresAt().toString(); } BitMatrix bitMatrix; try { QRCodeWriter writer = new QRCodeWriter(); bitMatrix = writer.encode(response, BarcodeFormat.QR_CODE, size, size); } catch (WriterException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while generating the QR Code."); return; } ByteArrayOutputStream pngOut = new ByteArrayOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOut); byte[] pngData = pngOut.toByteArray(); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("image/png"); resp.getOutputStream().write(pngData); }