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.
Example 1
Project: development   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
Project: deprecated-security-advanced-modules   File: JaasKrbUtil.java    License: Apache License 2.0 6 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 3
Project: alf.io   File: AdditionalServiceApiController.java    License: 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 4
Project: Alpine   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
Project: cxf   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
Project: teamengine   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
Project: development   File: ServiceProvisioningServiceWSTest.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 8
Project: airsonic-advanced   File: PlaylistWSController.java    License: 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 9
Project: datawave   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
Project: lams   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
Project: spring-boot-samples   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
Project: jdk8u60   File: WildcardPrincipalName.java    License: 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 13
Project: lams   File: JBossAuthorizationManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
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
Project: trellis   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
Project: ipst   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
Project: qpid-broker-j   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
Project: Spring5Tutorial   File: MemberController.java    License: 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 18
Project: jrestless   File: GatewayRequestObjectHandlerIntTest.java    License: 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 19
Project: JDeSurvey   File: DepartmentController.java    License: 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 20
Project: jdk8u_jdk   File: StartTlsResponseImpl.java    License: 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 21
Project: openjdk-jdk9   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
Project: zeppelin   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
Project: activemq-artemis   File: CertificateLoginModuleTest.java    License: 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
Project: swim   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
Project: jobson   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
Project: Spring-Boot-2.0-Projects   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
Project: cxf   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
Project: gemfirexd-oss   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
Project: jdk8u-jdk   File: AbstractDelegateHttpsURLConnection.java    License: 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 31
Project: cas4.0.x-server-wechat   File: X509CredentialsAuthenticationHandler.java    License: 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 32
Project: openhab-core   File: JwtSecurityContext.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Principal getUserPrincipal() {
    return new GenericUser(authentication.getUsername());
}
 
Example 33
Project: building-microservices   File: BasicApplication.java    License: Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/hi")
public Map<String, String> greetings(Principal p) {
    return Collections.singletonMap("content", "Hello, " + p.getName());
}
 
Example 34
Project: gemfirexd-oss   File: ClientAccessor.java    License: Apache License 2.0 4 votes vote down vote up
public void init(Principal principal, DistributedMember remoteMember,
    Cache cache) {
}
 
Example 35
Project: airsonic-advanced   File: MediaFileWSController.java    License: GNU General Public License v3.0 4 votes vote down vote up
@MessageMapping("/directory/get")
@SendToUser(broadcast = false)
public Object get(Principal user, MediaDirectoryRequest req, SimpMessageHeaderAccessor headers) throws Exception {
    List<MediaFile> mediaFiles = getMediaFiles(req.getIds(), req.getPaths());

    if (mediaFiles.isEmpty()) {
        return ImmutableMap.of("contentType", "notFound");
    }

    MediaFile dir = mediaFiles.get(0);
    if (dir.isFile()) {
        dir = mediaFileService.getParentOf(dir);
    }

    // Redirect if root directory.
    if (mediaFileService.isRoot(dir)) {
        return ImmutableMap.of("contentType", "home");
    }

    if (!securityService.isFolderAccessAllowed(dir, user.getName())) {
        return ImmutableMap.of("contentType", "accessDenied");
    }

    List<MediaFile> children = getChildren(mediaFiles);

    List<MediaFile> files = new ArrayList<>();
    List<MediaFile> subDirs = new ArrayList<>();
    for (MediaFile child : children) {
        if (child.isFile()) {
            files.add(child);
        } else {
            subDirs.add(child);
        }
    }
    MediaFileDirectoryEntry entry = new MediaFileDirectoryEntry(mediaFileService.toMediaFileEntryList(Collections.singletonList(dir), user.getName(), true, true, null, null, null).get(0));
    entry.setFiles(mediaFileService.toMediaFileEntryList(files, user.getName(), true, false, null, null, null));
    entry.setSubDirs(mediaFileService.toMediaFileEntryList(subDirs, user.getName(), false, false, null, null, null));
    entry.setAncestors(mediaFileService.toMediaFileEntryList(getAncestors(dir), user.getName(), false, false, null, null, null));
    entry.setLastPlayed(dir.getLastPlayed());
    entry.setPlayCount(dir.getPlayCount());
    entry.setComment(dir.getComment());
    if (dir.isAlbum()) {
        List<MediaFile> siblingAlbums = getSiblingAlbums(dir);
        entry.setSiblingAlbums(mediaFileService.toMediaFileEntryList(siblingAlbums, user.getName(), false, false, null, null, null));
        entry.setAlbum(guessAlbum(children));
        entry.setArtist(guessArtist(children));
        entry.setMusicBrainzReleaseId(guessMusicBrainzReleaseId(children));
    }

    Integer userRating = Optional.ofNullable(ratingService.getRatingForUser(user.getName(), dir)).orElse(0);
    Double averageRating = Optional.ofNullable(ratingService.getAverageRating(dir)).orElse(0.0D);

    entry.setUserRating(10 * userRating);
    entry.setAverageRating(10.0D * averageRating);

    if (isVideoOnly(children)) {
        entry.setContentType("video");
    } else if (dir.isAlbum()) {
        entry.setContentType("album");
    } else {
        entry.setContentType("artist");
    }

    return entry;
}
 
Example 36
Project: cxf-fediz   File: FederationServlet.java    License: Apache License 2.0 4 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head><title>WS Federation Systests Examples</title></head>");
    out.println("<body>");
    out.println("<p>Request url: "); out.println(request.getRequestURL()); out.println("</p>");

    out.print("<p>userPrincipal=");
    Principal p = request.getUserPrincipal();
    if (p != null) {
        out.print(p.getName());
    }
    out.println("</p>");

    List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated");
    for (String item: roleListToCheck) {
        out.println("<p>role:" + item + "=" + ((request.isUserInRole(item)) ? "true" : "false") + "</p>");
    }

    if (p instanceof FedizPrincipal) {
        FedizPrincipal fp = (FedizPrincipal)p;

        ClaimCollection claims = fp.getClaims();
        for (Claim c: claims) {
            out.println("<p>" + c.getClaimType().toString() + "=" + c.getValue() + "</p>");
        }

        Element el = fp.getLoginToken();
        if (el != null) {
            out.println("loginToken=FOUND{FedizPrincipal}<p>");
        }

        el = SecurityTokenThreadLocal.getToken();
        if (el != null) {
            out.println("loginToken=FOUND{SecurityTokenThreadLocal}<p>");
            String token = null;
            try {
                TransformerFactory transFactory = TransformerFactory.newInstance();
                Transformer transformer = transFactory.newTransformer();
                StringWriter buffer = new StringWriter();
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                transformer.transform(new DOMSource(el),
                                  new StreamResult(buffer));
                token = buffer.toString();
                out.println("<p>" + StringEscapeUtils.escapeXml11(token));
            } catch (Exception ex) {
                out.println("<p>Failed to transform cached element to string: " + ex.toString());
            }
        } else {
            out.println("<p>Bootstrap token not cached in thread local storage");
        }

    }

    out.println("</body>");
}
 
Example 37
Project: java-technology-stack   File: DefaultTransportRequest.java    License: MIT License 4 votes vote down vote up
@Override
@Nullable
public Principal getUser() {
	return this.user;
}
 
Example 38
Project: cuba   File: TestVaadinRequest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Principal getUserPrincipal() {
    return null;
}
 
Example 39
Project: openjdk-jdk8u   File: GroupImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns an enumeration which contains the subnet mask.
 *
 * @return an enumeration which contains the subnet mask.
 */
public Enumeration<? extends Principal> members(){
      Vector<Principal> v = new Vector<Principal>(1);
      v.addElement(this);
      return v.elements();
}
 
Example 40
Project: spring-analysis-note   File: ServerRequestWrapper.java    License: MIT License 4 votes vote down vote up
@Override
public Mono<? extends Principal> principal() {
	return this.delegate.principal();
}