Java Code Examples for java.security.Principal#getName()

The following examples show how to use java.security.Principal#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DesignTacoController.java    From spring-in-action-5-samples with Apache License 2.0 8 votes vote down vote up
@GetMapping
public String showDesignForm(Model model, Principal principal) {
  log.info("   --- Designing taco");
  List<Ingredient> ingredients = new ArrayList<>();
  ingredientRepo.findAll().forEach(i -> ingredients.add(i));
  
  Type[] types = Ingredient.Type.values();
  for (Type type : types) {
    model.addAttribute(type.toString().toLowerCase(), 
        filterByType(ingredients, type));      
  }
  
  String username = principal.getName();
  User user = userRepo.findByUsername(username);
  model.addAttribute("user", user);

  return "design";
}
 
Example 2
Source File: Krb5ProxyImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String getPrincipalHostName(Principal principal) {
    if (principal == null) {
       return null;
    }
    String hostName = null;
    try {
        PrincipalName princName =
            new PrincipalName(principal.getName(),
                    PrincipalName.KRB_NT_SRV_HST);
        String[] nameParts = princName.getNameStrings();
        if (nameParts.length >= 2) {
            hostName = nameParts[1];
        }
    } catch (Exception e) {
        // ignore
    }
    return hostName;
}
 
Example 3
Source File: PrivateCredentialPermission.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Create a new {@code PrivateCredentialPermission}
 * with the specified {@code credentialClass} and Principals.
 */
PrivateCredentialPermission(String credentialClass,
                    Set<Principal> principals) {

    super(credentialClass);
    this.credentialClass = credentialClass;

    synchronized(principals) {
        if (principals.size() == 0) {
            this.credOwners = EMPTY_PRINCIPALS;
        } else {
            this.credOwners = new CredOwner[principals.size()];
            int index = 0;
            Iterator<Principal> i = principals.iterator();
            while (i.hasNext()) {
                Principal p = i.next();
                this.credOwners[index++] = new CredOwner
                                            (p.getClass().getName(),
                                            p.getName());
            }
        }
    }
}
 
Example 4
Source File: AccumuloConnectionRequestBean.java    From datawave with Apache License 2.0 6 votes vote down vote up
public boolean cancelConnectionRequest(String id, Principal principal) {
    // this call checks that the Principal used for the connection request and th connection cancel are the same
    // if query is waiting for an accumulo connection in create or reset, then interrupt it
    boolean connectionRequestCanceled = false;
    try {
        Pair<Principal,Thread> connectionRequestPair = getConnectionThreadMap.get(id);
        if (connectionRequestPair != null) {
            String connectionRequestPrincipalName = principal.getName();
            String connectionCancelPrincipalName = connectionRequestPair.getFirst().getName();
            if (connectionRequestPrincipalName.equals(connectionCancelPrincipalName)) {
                connectionRequestPair.getSecond().interrupt();
                connectionRequestCanceled = true;
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return connectionRequestCanceled;
}
 
Example 5
Source File: SubjectExposingResource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@GET
@Path("unsecured")
@PermitAll
public String getSubjectUnsecured(@Context SecurityContext sec) {
    Principal user = sec.getUserPrincipal();
    String name = user != null ? user.getName() : "anonymous";
    return name;
}
 
Example 6
Source File: RolesEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * This endpoint requires a role that is mapped to the group1 role
 * @return principal name
 */
@GET
@Path("/needsGroup1Mapping")
@RolesAllowed("Group1MappedRole")
public String needsGroup1Mapping(@Context SecurityContext sec) {
    Principal user = sec.getUserPrincipal();
    sec.isUserInRole("group1");
    return user.getName();
}
 
Example 7
Source File: TokenSecuredResourceV4.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@GET()
@Path("roles-allowed")
@RolesAllowed({ "Echoer", "Subscriber" })
@Produces(MediaType.TEXT_PLAIN)
public String helloRolesAllowed(@Context SecurityContext ctx) {
    Principal caller = ctx.getUserPrincipal();
    String name = caller == null ? "anonymous" : caller.getName();
    boolean hasJWT = jwt.getClaimNames() != null;
    String helloReply = String.format("hello + %s, isSecure: %s, authScheme: %s, hasJWT: %s", name, ctx.isSecure(),
            ctx.getAuthenticationScheme(), hasJWT);
    return helloReply;
}
 
Example 8
Source File: UiWebSocketServlet.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Object createWebSocket(ServletUpgradeRequest request, ServletUpgradeResponse response) {
    if (!isStopped) {
        // FIXME: Replace this with globally shared opaque token to allow secure failover
        Principal p = request.getUserPrincipal();
        String userName = p != null ? p.getName() : FAKE_USERNAME;

        UiWebSocket socket = new UiWebSocket(directory, userName);
        sockets.add(socket);
        return socket;
    }
    return null;
}
 
Example 9
Source File: ClientAuthenticator.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
static Optional<String> getClientName(Principal principal) {
  X500Name name = new X500Name(principal.getName());
  RDN[] rdns = name.getRDNs(BCStyle.CN);
  if (rdns.length == 0) {
    logger.warn("Certificate does not contain CN=xxx,...: {}", principal.getName());
    return Optional.empty();
  }
  return Optional.of(IETFUtils.valueToString(rdns[0].getFirst().getValue()));
}
 
Example 10
Source File: ClusterController.java    From ankush with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, value = "{clusterId}/removenode")
@ResponseBody
public ResponseEntity<ResponseWrapper<Object>> removeNodes(
		@PathVariable("clusterId") Long clusterId,
		@RequestBody Map<String, Object> parameterMap, Principal principal)
		throws Exception {
	String userName = principal.getName();
	String error = "Given password doesn't match.You are not authorized to remove nodes.";
	try {
		if (parameterMap.get("password") == null
				|| ((String) parameterMap.get("password")).isEmpty()) {
			error = "Please provide a valid password to delete these nodes.";
		} else {
			if (userManager.doesPasswordMatch(userName,
					parameterMap.get("password").toString())) {
				// Remove Nodes from Cluster
				com.impetus.ankush2.framework.manager.ClusterManager manager = new com.impetus.ankush2.framework.manager.ClusterManager(principal.getName());
				Object objectret = manager.removeNodes(clusterId,
						(List<String>) parameterMap.get("nodes"));
				// Object objectret = null;
				return wrapResponse(objectret, HttpStatus.OK,
						HttpStatus.OK.toString(),
						"Node removal activity in progress");
			}
		}
	} catch (Exception e) {
		error = e.getMessage() != null ? e.getMessage()
				: "Couldn't remove node. ";
	}
	Map<String, Object> returnMap = new HashMap<String, Object>();
	returnMap.put(com.impetus.ankush2.constant.Constant.Keys.STATUS, false);
	returnMap.put(com.impetus.ankush2.constant.Constant.Keys.ERROR, error);
	return wrapResponse((Object) returnMap, HttpStatus.OK,
			HttpStatus.OK.toString(), "Node deletion failed.");
}
 
Example 11
Source File: QuestionRowLabelController.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
@Secured({"ROLE_ADMIN","ROLE_SURVEY_ADMIN"})
@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
public String updateForm(@PathVariable("id") Long questionId, 
						Principal principal,	
						Model uiModel,
						HttpServletRequest httpServletRequest) {
	try{
		String login = principal.getName();
		User user = userService.user_findByLogin(login);
		Question question = surveySettingsService.question_findById(questionId);
		//Check if the user is authorized
		if(!securityService.userIsAuthorizedToManageSurvey(question.getPage().getSurveyDefinition().getId(), user) &&
	       !securityService.userBelongsToDepartment(question.getPage().getSurveyDefinition().getDepartment().getId(), user)	) {
			log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr());
			return "accessDenied";	
		}
		
		SortedSet<QuestionRowLabel> RowLabels =  question.getRowLabels();
		log.info("initial set size" + RowLabels.size());
		for (int i =1; i<=EMPTY_OPTIONS_COUNT; i++){
			
			log.info("adding to set" + i); 
			RowLabels.add(new QuestionRowLabel(question,(short) (question.getRowLabels().size() + i)));
		}
		question.setRowLabels(RowLabels);
		uiModel.addAttribute("question", question);
		return "settings/questionRows/update";
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 12
Source File: DummyCredentialGenerator.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public Properties getValidCredentials(Principal principal) {

    String userName = principal.getName();
    if (DummyAuthenticator.testValidName(userName)) {
      Properties props = new Properties();
      props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
      props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
      return props;
    }
    else {
      throw new IllegalArgumentException("Dummy: [" + userName
          + "] is not a valid user");
    }
  }
 
Example 13
Source File: DataServiceBean.java    From development with Apache License 2.0 5 votes vote down vote up
private boolean mayBeWebServiceSSLContext() {
    if (webServiceContext == null) {
        return false;
    }

    try {
        final Principal principal = webServiceContext.getUserPrincipal();
        return principal != null && principal.getName() != null
                && principal.getName().indexOf('=') > 0;
    } catch (Exception e) {
        return false;
    }
}
 
Example 14
Source File: UserController.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Deletes the user
 * @param id
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({"ROLE_ADMIN"})
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
public String delete(@PathVariable("id") Long id, 
					Principal principal,
					Model uiModel, 
					HttpServletRequest httpServletRequest) {

	log.info("delete(): id=" + id);
	try {
		String login = principal.getName();
		User loggedUser = userService.user_findByLogin(login);
		User user = userService.user_findById(id);

		if (user == loggedUser ){
			uiModel.addAttribute("hasErrors", true);
			return "security/";
		}else{
			User otherUsers = userService.user_findById(id);
			userService.user_remove(otherUsers);
			uiModel.asMap().clear();

			if (user.getType().equals(SecurityType.I)){
				return "redirect:/security/users/internal" ;
			}

			if (user.getType().equals(SecurityType.E)){
				return "redirect:/security/users/external" ;	
			}

		}
		return "redirect:/security/";			

	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}

}
 
Example 15
Source File: DataServiceBean.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * @param lookupOnly
 * @return
 * @throws ObjectNotFoundException
 */
private PlatformUser loadUserFromSessionContext(boolean lookupOnly)
        throws ObjectNotFoundException {
    String name = CURRENT_ASYNC_USER.get() == null ? null
            : CURRENT_ASYNC_USER.get().toString();
    if (name == null) {
        // determine the caller
        Principal callerPrincipal = sessionCtx.getCallerPrincipal();
        if (callerPrincipal == null) {
            return null;
        }
        name = callerPrincipal.getName();
    }
    // try to parse the name to long - must work if it is a user key
    long parseLong = Long.parseLong(name);
    // determine the user object of the caller
    PlatformUser user = getReference(PlatformUser.class, parseLong);
    Organization org = user.getOrganization();
    if (checkOrgDeregistration(org, lookupOnly)) {
        // org still valid => return user
        Tenant tenant = org.getTenant();
        if (tenant != null) {
            assignTenantId(user, org);
        }
        return user;
    }
    // lookup case => org not valid => no user
    return null;
}
 
Example 16
Source File: SimpleStandard.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check that the principal contained in the Subject is of
 * type JMXPrincipal and refers to the "monitorRole" identity.
 */
private void checkSubject() {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set principals = subject.getPrincipals();
    Principal principal = (Principal) principals.iterator().next();
    if (!(principal instanceof JMXPrincipal))
        throw new SecurityException("Authenticated subject contains " +
                                    "invalid principal type = " +
                                    principal.getClass().getName());
    String identity = principal.getName();
    if (!identity.equals("monitorRole"))
        throw new SecurityException("Authenticated subject contains " +
                                    "invalid principal name = " + identity);
}
 
Example 17
Source File: ResourceController.java    From tutorials with MIT License 4 votes vote down vote up
@GetMapping("/user")
public String user(Principal principal) {
    return principal.getName();
}
 
Example 18
Source File: OAuthPostFilter.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    // Only apply filter if there is an OAuth implementation and a valid OAuth request
    if (oAuthHttpService == null || !oAuthHttpService.isEnabled()
            || !oAuthHttpService.isValidOAuthRequest(req, res)) {
        chain.doFilter(req, response);
        return;
    }

    Principal principal = req.getUserPrincipal();
    // Do not log the user in if there is already an opened session
    if (principal != null && sessionManager.getCurrentSessionUserId() == null) {
        try {
            // Force the authentication/login with the user Eid
            final String eid = userDirectoryService.getUserEid(principal.getName());
            final String uid = principal.getName();

            // TODO This is a hack and we should go through the AuthenticationManager API.
            Authentication authentication = new Authentication() {

                @Override
                public String getUid() {
                    return uid;
                }

                @Override
                public String getEid() {
                    return eid;
                }
            };

            // Authentication authentication = authenticationManager.authenticate(new ExternalTrustedEvidence() {
            //    public String getIdentifier() {
            //        return eid;
            //    }
            // });
            usageSessionService.login(authentication, req);
        } catch (UserNotDefinedException e) {
            log.warn("Failed to find user \"" + principal.getName() + "\". This shouldn't happen", e);
        }
    }
    chain.doFilter(req, res);
}
 
Example 19
Source File: AuthResource.java    From dropwizard-java8 with Apache License 2.0 4 votes vote down vote up
@GET
@Path("implicit-permitall")
public String implicitPermitAllAuthorization(@Auth Principal principal) {
    return "'" + principal.getName() + "' has user privileges";
}
 
Example 20
Source File: AuthResource.java    From dropwizard-auth-jwt with Apache License 2.0 4 votes vote down vote up
@GET
@RolesAllowed({"ADMIN"})
@Path("admin")
public String show(@Auth Principal principal) {
    return "'" + principal.getName() + "' has admin privileges";
}