Java Code Examples for java.security.Principal

The following examples show how to use java.security.Principal. These examples are extracted from open source projects. 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 Project: development   Source File: SearchServiceWSTest.java    License: 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 2
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 3
@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 4
Source Project: Alpine   Source File: JwtAuthenticationServiceTest.java    License: 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 5
Source Project: cxf   Source File: UsernameTokenInterceptor.java    License: 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 6
Source Project: teamengine   Source File: PBKDF2Realm.java    License: 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 7
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 8
@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 9
Source Project: datawave   Source File: QueryMetricsBean.java    License: 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 10
Source Project: lams   Source File: SubjectActions.java    License: 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 11
Source Project: spring-boot-samples   Source File: APIController.java    License: 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
@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 13
private RoleGroup getCurrentRoles(Principal principal)
{ 
   //Check that the caller is authenticated to the current thread
   Subject subject = SubjectActions.getActiveSubject();  
   
   //Deal with the security context
   SecurityContext sc = SubjectActions.getSecurityContext(); 
   if(sc == null)
   {
      sc = new JBossSecurityContext(securityDomain); 
      SubjectActions.setSecurityContext(sc);   
   } 
   
   return getCurrentRoles(principal,subject,sc); 
}
 
Example 14
Source Project: trellis   Source File: FederatedJwtAuthenticatorTest.java    License: 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 15
Source Project: ipst   Source File: DDBManagerBean.java    License: 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 16
Source Project: qpid-broker-j   Source File: QpidPrincipal.java    License: 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 17
@PostMapping("del_message")
protected String delMessage(
        @RequestParam String millis, 
        Principal principal) {
    
    if(millis != null) {
    	messageService.deleteMessage(principal.getName(), millis);
    }
    return REDIRECT_MEMBER_PATH;
}
 
Example 18
@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 19
@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 20
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 21
Source Project: openjdk-jdk9   Source File: MBS_Light.java    License: 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 22
Source Project: zeppelin   Source File: YarnClient.java    License: 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 23
@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 24
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 Project: swim   Source File: RemoteHost.java    License: 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 26
Source Project: jobson   Source File: JsonWebTokenConfig.java    License: 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 27
Source Project: Spring-Boot-2.0-Projects   Source File: TweetController.java    License: 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);
                             });
}
 
Example 28
Source Project: cxf   Source File: AbstractSecurityContextInInterceptor.java    License: 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 29
Source Project: gemfirexd-oss   Source File: DummyCredentialGenerator.java    License: 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 30
/**
 * 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());
    }
}