java.security.Principal Java Examples

The following examples show how to use java.security.Principal. 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: JaasKrbUtil.java    From deprecated-security-advanced-modules with Apache License 2.0 8 votes vote down vote up
public static Subject loginUsingKeytab(final Set<String> principalAsStrings, final Path keytabPath, final boolean initiator) throws LoginException {
    final Set<Principal> principals = new HashSet<Principal>();

    for(String p: principalAsStrings) {
        principals.add(new KerberosPrincipal(p));
    }


    final Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

    final Configuration conf = useKeytab("*", keytabPath, initiator);
    final String confName = "KeytabConf";
    final LoginContext loginContext = new LoginContext(confName, subject, null, conf);
    loginContext.login();
    return loginContext.getSubject();
}
 
Example #2
Source File: QueryMetricsBean.java    From datawave with Apache License 2.0 6 votes vote down vote up
/**
 * Returns metrics for the current users queries that are identified by the id
 *
 * @param id
 *
 * @return datawave.webservice.result.QueryMetricListResponse
 *
 * @RequestHeader X-ProxiedEntitiesChain use when proxying request for user, by specifying a chain of DNs of the identities to proxy
 * @RequestHeader X-ProxiedIssuersChain required when using X-ProxiedEntitiesChain, specify one issuer DN per subject DN listed in X-ProxiedEntitiesChain
 * @HTTP 200 success
 * @HTTP 500 internal server error
 */
@GET
@POST
@Path("/id/{id}")
@Interceptors({RequiredInterceptor.class, ResponseInterceptor.class})
public BaseQueryMetricListResponse query(@PathParam("id") @Required("id") String id) {
    
    // Find out who/what called this method
    DatawavePrincipal dp = null;
    Principal p = ctx.getCallerPrincipal();
    String user = p.getName();
    if (p instanceof DatawavePrincipal) {
        dp = (DatawavePrincipal) p;
        user = dp.getShortName();
    }
    return queryHandler.query(user, id, dp);
}
 
Example #3
Source File: SearchServiceWSTest.java    From development with Apache License 2.0 6 votes vote down vote up
private WebServiceContext createWebServiceContextMock(String expectedIP,
        String expectedUser) {
    requestMock = mock(HttpServletRequest.class);
    when(requestMock.getRemoteAddr()).thenReturn(expectedIP);

    Principal principalMock = mock(Principal.class);
    when(principalMock.getName()).thenReturn(expectedUser);

    MessageContext msgContextMock = mock(MessageContext.class);
    when(msgContextMock.get(anyString())).thenReturn(requestMock);

    WebServiceContext wsContextMock = mock(WebServiceContext.class);
    when(wsContextMock.getUserPrincipal()).thenReturn(principalMock);
    when(wsContextMock.getMessageContext()).thenReturn(msgContextMock);

    return wsContextMock;
}
 
Example #4
Source File: AdditionalServiceApiController.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@DeleteMapping("/event/{eventId}/additional-services/{additionalServiceId}")
@Transactional
public ResponseEntity<String> remove(@PathVariable("eventId") int eventId, @PathVariable("additionalServiceId") int additionalServiceId, Principal principal) {
    return eventRepository.findOptionalById(eventId)
        .map(event -> additionalServiceRepository.getOptionalById(additionalServiceId, eventId)
            .map(as -> {
                log.debug("{} is deleting additional service #{}", principal.getName(), additionalServiceId);
                int deletedTexts = additionalServiceTextRepository.deleteAdditionalServiceTexts(additionalServiceId);
                log.debug("deleted {} texts", deletedTexts);
                //TODO add configuration fields and values
                additionalServiceRepository.delete(additionalServiceId, eventId);
                log.debug("additional service #{} successfully deleted", additionalServiceId);
                return ResponseEntity.ok("OK");
            })
            .orElseGet(() -> new ResponseEntity<>("additional service not found", HttpStatus.NOT_FOUND)))
        .orElseGet(() -> new ResponseEntity<>("event not found", HttpStatus.NOT_FOUND));
}
 
Example #5
Source File: JwtAuthenticationServiceTest.java    From Alpine with Apache License 2.0 6 votes vote down vote up
@Test
public void authenticateShouldReturnNullWhenNoMatchingUserExists() throws AuthenticationException {
    final Principal principalMock = mock(Principal.class);
    when(principalMock.getName())
            .thenReturn("username");

    final String token = new JsonWebToken().createToken(principalMock, null, IdentityProvider.LOCAL);

    final ContainerRequest containerRequestMock = mock(ContainerRequest.class);
    when(containerRequestMock.getRequestHeader(eq(HttpHeaders.AUTHORIZATION)))
            .thenReturn(Collections.singletonList("Bearer " + token));

    final JwtAuthenticationService authService = new JwtAuthenticationService(containerRequestMock);

    assertThat(authService.authenticate()).isNull();
}
 
Example #6
Source File: UsernameTokenInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private SecurityContext createSecurityContext(Message msg,
                                              SamlAssertionWrapper samlAssertion) {
    String roleAttributeName =
        (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.SAML_ROLE_ATTRIBUTENAME, msg);
    if (roleAttributeName == null || roleAttributeName.length() == 0) {
        roleAttributeName = WSS4JInInterceptor.SAML_ROLE_ATTRIBUTENAME_DEFAULT;
    }

    ClaimCollection claims =
        SAMLUtils.getClaims(samlAssertion);
    Set<Principal> roles =
        SAMLUtils.parseRolesFromClaims(claims, roleAttributeName, null);

    SAMLSecurityContext context =
        new SAMLSecurityContext(new SAMLTokenPrincipalImpl(samlAssertion), roles, claims);
    context.setIssuer(SAMLUtils.getIssuer(samlAssertion));
    context.setAssertionElement(SAMLUtils.getAssertionElement(samlAssertion));
    return context;
}
 
Example #7
Source File: PBKDF2Realm.java    From teamengine with Apache License 2.0 6 votes vote down vote up
/**
 * Return the Principal associated with the specified username and
 * credentials, if one exists in the user data store; otherwise return null.
 */
@Override
public Principal authenticate(String username, String credentials) {
    GenericPrincipal principal = (GenericPrincipal) getPrincipal(username);
    if (null != principal) {
        try {
            if (!PasswordStorage.verifyPassword(credentials, principal.getPassword())) {
                principal = null;
            }
        } catch (CannotPerformOperationException | InvalidHashException e) {
            LOGR.log(Level.WARNING, e.getMessage());
            principal = null;
        }
    }
    return principal;
}
 
Example #8
Source File: ServiceProvisioningServiceWSTest.java    From development with Apache License 2.0 6 votes vote down vote up
private WebServiceContext createWebServiceContextMock(String expectedIP,
        String expectedUser) {
    requestMock = mock(HttpServletRequest.class);
    when(requestMock.getRemoteAddr()).thenReturn(expectedIP);

    Principal principalMock = mock(Principal.class);
    when(principalMock.getName()).thenReturn(expectedUser);

    MessageContext msgContextMock = mock(MessageContext.class);
    when(msgContextMock.get(anyString())).thenReturn(requestMock);

    WebServiceContext wsContextMock = mock(WebServiceContext.class);
    when(wsContextMock.getUserPrincipal()).thenReturn(principalMock);
    when(wsContextMock.getMessageContext()).thenReturn(msgContextMock);

    return wsContextMock;
}
 
Example #9
Source File: PlaylistWSController.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
@MessageMapping("/create/playqueue")
@SendToUser(broadcast = false)
public int createPlaylistForPlayQueue(Principal p, Integer playerId) throws Exception {
    Player player = playerService.getPlayerById(playerId);
    Locale locale = localeResolver.resolveLocale(p.getName());
    DateTimeFormatter dateFormat = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withLocale(locale);

    Instant now = Instant.now();
    Playlist playlist = new Playlist();
    playlist.setUsername(p.getName());
    playlist.setCreated(now);
    playlist.setChanged(now);
    playlist.setShared(false);
    playlist.setName(dateFormat.format(now.atZone(ZoneId.systemDefault())));

    playlistService.createPlaylist(playlist);
    playlistService.setFilesInPlaylist(playlist.getId(), player.getPlayQueue().getFiles());

    return playlist.getId();
}
 
Example #10
Source File: AbstractDelegateHttpsURLConnection.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the server's principal, or throws SSLPeerUnverifiedException
 * if the server did not authenticate.
 */
Principal getPeerPrincipal()
        throws SSLPeerUnverifiedException
{
    if (cachedResponse != null) {
        return ((SecureCacheResponse)cachedResponse).getPeerPrincipal();
    }

    if (http == null) {
        throw new IllegalStateException("connection not yet open");
    } else {
        return (((HttpsClient)http).getPeerPrincipal());
    }
}
 
Example #11
Source File: APIController.java    From spring-boot-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Receives the messages from clients and sends them to ActiveMQ.
 * 
 * @param message the message to send, encapsulated in a wrapper
 */
@RequestMapping(value = "/send", method = RequestMethod.POST, consumes = "application/json")
public void sendMessage(@RequestBody MessageDTO message, Principal currentUser) {
    // send any message sent by clients to a queue called rt_messages
    message.from = currentUser.getName();
    camelContext.createProducerTemplate().sendBody("activemq:rt_messages", message);
}
 
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: DDBManagerBean.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
@WebMethod(operationName = "findParametersInternal")
public Parameters findParameters(Internal internal, SimulatorInst simulator) {
    Principal cPrincipal = getCallerPrincipal();
    ParametersContainer pc1 = internal.getParametersContainer();
    List<Parameters> plist = pc1.getParameters();
    for (Parameters parameters : plist) {
        if (parameters.getSimulator().getId() == simulator.getId()) {
            return parameters;
        }
    }
    return null;
}
 
Example #14
Source File: MemberController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
@PostMapping("del_message")
protected String delMessage(
        @RequestParam String millis, 
        Principal principal) {
    
    if(millis != null) {
    	messageService.deleteMessage(principal.getName(), millis);
    }
    return REDIRECT_MEMBER_PATH;
}
 
Example #15
Source File: QpidPrincipal.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
static <P extends Principal> P getSingletonPrincipal(final Subject authSubject,
                                                     final boolean isPrincipalOptional,
                                                     final Class<P> principalClazz)
{
    if (authSubject == null)
    {
        throw new IllegalArgumentException("No authenticated subject.");
    }

    final Set<P> principals = authSubject.getPrincipals(principalClazz);
    int numberOfAuthenticatedPrincipals = principals.size();

    if(numberOfAuthenticatedPrincipals == 0 && isPrincipalOptional)
    {
        return null;
    }
    else
    {
        if (numberOfAuthenticatedPrincipals != 1)
        {
            throw new IllegalArgumentException(
                    String.format(
                            "Can't find single %s in the authenticated subject. There were %d "
                            + "%s principals out of a total number of principals of: %s",
                            principalClazz.getSimpleName(),
                            numberOfAuthenticatedPrincipals,
                            principalClazz.getSimpleName(),
                            authSubject.getPrincipals()));
        }
        return principals.iterator().next();
    }
}
 
Example #16
Source File: WildcardPrincipalName.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override public Void run() {
    Set<Principal> principals = new HashSet<>();
    Set<Object> publicCredentials = new HashSet<>();
    Set<Object> privateCredentials = new HashSet<>();

    principals.add(principal);
    Subject subject = new Subject(true,
                                  principals,
                                  publicCredentials,
                                  privateCredentials);

    Subject.doAsPrivileged(subject, action, null);
    return null;
}
 
Example #17
Source File: FederatedJwtAuthenticatorTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAuthenticateKeystoreEC() throws Exception {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(getClass().getResourceAsStream("/keystore.jks"), passphrase);

    final String token = buildEcToken(ks.getKey("trellis-ec", passphrase), "trellis-ec");
    final Authenticator authenticator = new FederatedJwtAuthenticator(ks,
            singletonList("trellis-ec"));

    final Principal p = authenticator.authenticate(token);
    assertNotNull(p, "Missing principal!");
    assertEquals("https://people.apache.org/~acoburn/#i", p.getName(), "Incorrect webid!");
}
 
Example #18
Source File: AbstractSecurityContextInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Principal getPrincipal(Principal originalPrincipal, Subject subject) {
    Principal[] ps = subject.getPrincipals().toArray(new Principal[subject.getPrincipals().size()]);
    if (ps != null && ps.length > 0 
        && !DefaultSecurityContext.isGroupPrincipal(ps[0])) {
        return ps[0];
    }
    return originalPrincipal;
}
 
Example #19
Source File: SubjectActions.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void push(final Principal principal, final Object credential,
   final Subject subject, final String securityDomain) 
{
   AccessController.doPrivileged(
      new PrivilegedAction<Object>()
      {
         public Object run()
         {
            //SecurityAssociation.pushSubjectContext(subject, principal, credential);
            SecurityContext sc = SecurityContextAssociation.getSecurityContext();
            if(sc == null)
            {
               try
               {
                  sc = SecurityContextFactory.createSecurityContext(principal, credential,
                        subject, securityDomain);
               }
               catch (Exception e)
               {
                  throw new RuntimeException(e);
               }
            }
            SecurityContextAssociation.setSecurityContext(sc);
            return null;
         }
      }
   );
}
 
Example #20
Source File: GatewayRequestObjectHandlerIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void testCognitoCustomAuthorizerPrincipal() {
	Map<String, Object> authorizerDate = new HashMap<>();
	authorizerDate.put("principalId", "123");
	authorizerDate.put("custom:value", "blub");
	Principal principal = testPrincipal(authorizerDate);
	assertTrue(principal instanceof CustomAuthorizerPrincipal);
	CustomAuthorizerPrincipal cognitoCustomPrincipal = (CustomAuthorizerPrincipal) principal;
	assertEquals("123", cognitoCustomPrincipal.getName());
	assertEquals("123", cognitoCustomPrincipal.getClaims().getPrincipalId());
	assertEquals("blub", cognitoCustomPrincipal.getClaims().getAllClaims().get("custom:value"));
}
 
Example #21
Source File: DepartmentController.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
@Secured({"ROLE_ADMIN"})
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
					 @Valid Department department, 
					 BindingResult bindingResult, 
					 Principal principal,
					 Model uiModel, 
					 HttpServletRequest httpServletRequest) {
	log.info("update(): handles PUT");
	try{
		User user = userService.user_findByLogin(principal.getName());	
		if(proceed != null){


			if (bindingResult.hasErrors()) {
				populateEditForm(uiModel, department,user);
				return "security/departments/update";
			}
			if (surveySettingsService.department_findByName(department.getName()) != null &&
					!surveySettingsService.department_findByName(department.getName()).getId().equals(department.getId())) {
				bindingResult.rejectValue("name", "field_unique");
				populateEditForm(uiModel, department,user);
				return "security/departments/update";
			}
			uiModel.asMap().clear();
			department = surveySettingsService.department_merge(department);
			return "redirect:/security/departments/" + encodeUrlPathSegment(department.getId().toString(), httpServletRequest);

		}else{

			return "redirect:/security/departments?page=1&size=10";

		}


	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example #22
Source File: JsonWebTokenConfig.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Override
public AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap) {
    final byte[] decodedSecretKey = Base64.getDecoder().decode(secretKey);
    final Key secretKeyKey = new SecretKeySpec(decodedSecretKey, 0, decodedSecretKey.length, this.getSignatureAlgorithm().toString());

    return new JsonWebTokenAuthFilter.Builder<>()
            .setAuthenticator(new JsonWebTokenAuthenticator(secretKeyKey, this.getSignatureAlgorithm()))
            .setAuthorizer(new PermitAllAuthorizer())
            .buildAuthFilter();
}
 
Example #23
Source File: RemoteHost.java    From swim with Apache License 2.0 5 votes vote down vote up
public Principal remotePrincipal() {
  final WarpSocketContext warpSocketContext = this.warpSocketContext;
  if (warpSocketContext != null) {
    return warpSocketContext.remotePrincipal();
  } else {
    return null;
  }
}
 
Example #24
Source File: CertificateLoginModuleTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void checkPrincipalsMatch(Subject subject) {
   boolean nameFound = false;
   boolean[] rolesFound = new boolean[ROLE_NAMES.size()];
   for (int i = 0; i < rolesFound.length; ++i) {
      rolesFound[i] = false;
   }

   for (Principal currentPrincipal : subject.getPrincipals()) {
      if (currentPrincipal instanceof UserPrincipal) {
         if (currentPrincipal.getName().equals(USER_NAME)) {
            if (!nameFound) {
               nameFound = true;
            } else {
               fail("UserPrincipal found twice.");
            }

         } else {
            fail("Unknown UserPrincipal found.");
         }

      } else if (currentPrincipal instanceof RolePrincipal) {
         int principalIdx = ROLE_NAMES.indexOf(((RolePrincipal) currentPrincipal).getName());

         if (principalIdx < 0) {
            fail("Unknown RolePrincipal found.");
         }

         if (!rolesFound[principalIdx]) {
            rolesFound[principalIdx] = true;
         } else {
            fail("RolePrincipal found twice.");
         }
      } else {
         fail("Unknown Principal type found.");
      }
   }
}
 
Example #25
Source File: X509CredentialsAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private boolean doesNameMatchPattern(final Principal principal,
        final Pattern pattern) {
    final String name = principal.getName();
    final boolean result = pattern.matcher(name).matches();
    logger.debug(String.format("%s matches %s == %s", pattern.pattern(), name, result));
    return result;
}
 
Example #26
Source File: QuestionColumnLabelController.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,
						HttpServletRequest httpServletRequest,
						Model uiModel) {
	log.info("updateForm(): questionId=" + questionId);
	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<QuestionColumnLabel> ColumnLabels =  question.getColumnLabels();
		log.info("initial set size" + ColumnLabels.size());
		for (int i =1; i<=EMPTY_OPTIONS_COUNT; i++){
			
			log.info("adding to set" + i); 
			ColumnLabels.add(new QuestionColumnLabel(question,(short) (question.getColumnLabels().size() + i)));
		}
		question.setColumnLabels(ColumnLabels);
		uiModel.addAttribute("question", question);
		return "settings/questionCols/update";
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example #27
Source File: YarnClient.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static HttpClient buildSpengoHttpClient() {
  HttpClientBuilder builder = HttpClientBuilder.create();
  Lookup<AuthSchemeProvider> authSchemeRegistry
      = RegistryBuilder.<AuthSchemeProvider>create().register(
          AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
  builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
    @Override
    public Principal getUserPrincipal() {
      return null;
    }

    @Override
    public String getPassword() {
      return null;
    }
  });
  builder.setDefaultCredentialsProvider(credentialsProvider);

  // Avoid output WARN: Cookie rejected
  RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
      .build();
  builder.setDefaultRequestConfig(globalConfig);

  CloseableHttpClient httpClient = builder.build();

  return httpClient;
}
 
Example #28
Source File: StartTlsResponseImpl.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static Principal getPeerPrincipal(SSLSession session)
        throws SSLPeerUnverifiedException {
    Principal principal;
    try {
        principal = session.getPeerPrincipal();
    } catch (AbstractMethodError e) {
        // if the JSSE provider does not support it, return null, since
        // we need it only for Kerberos.
        principal = null;
    }
    return principal;
}
 
Example #29
Source File: MBS_Light.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public String getAuthorizationId() {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set<Principal> principals = subject.getPrincipals();
    Iterator<Principal> i = principals.iterator();
    StringBuffer buffer = new StringBuffer();
    while(i.hasNext()) {
        Principal p = i.next();
        buffer.append(p.getName());
        if(i.hasNext())
            buffer.append(" ");
    }

    return buffer.toString();
}
 
Example #30
Source File: TweetController.java    From Spring-Boot-2.0-Projects with MIT License 5 votes vote down vote up
@PostMapping
public Mono<Tweet> save(Principal principal, @RequestBody Tweet tweet) {
    Mono<User> user = userService.getUserByScreenName(principal.getName());
    return user.flatMap(u -> {
                               tweet.setTweetUser(u);
                               return tweetService.save(tweet);
                             });
}