@PreAuthorize("@roleChecker.hasValidRole(#principal, #companyid)") @RequestMapping(value="/company/{companyid}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<CompanyDTO> getCompany( Principal principal, @PathVariable String companyid) { // Check for SUPERADMIN and COMPANYADMIN role // RoleChecker.hasValidRole(principal, companyid); CompanyDTO companyDTO = companyService.findByName(companyid); if (companyDTO == null) { throw new ResourceNotFoundException(); } return new ResponseEntity<CompanyDTO>(companyDTO, HttpStatus.OK); }
@Test public void testAuthFilter() throws IOException { final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(); when(mockContext.getHeaders()).thenReturn(headers); final AuthFilter<String, Principal> filter = new AnonymousAuthFilter.Builder() .setAuthenticator(new AnonymousAuthenticator()).buildAuthFilter(); filter.filter(mockContext); verify(mockContext).setSecurityContext(securityCaptor.capture()); assertEquals(Trellis.AnonymousAgent.getIRIString(), securityCaptor.getValue().getUserPrincipal().getName()); assertFalse(securityCaptor.getValue().isUserInRole("role")); assertFalse(securityCaptor.getValue().isSecure()); assertEquals("NONE", securityCaptor.getValue().getAuthenticationScheme()); }
private static void checkPrincipal(LoginContext loginContext, boolean principalShouldExist) { if (!principalShouldExist) { if (loginContext.getSubject().getPrincipals().size() != 0) { throw new RuntimeException("Test failed. Principal was not " + "cleared."); } return; } for (Principal p : loginContext.getSubject().getPrincipals()) { if (p instanceof UserPrincipal && USER_NAME.equals(p.getName())) { //Proper principal was found, return. return; } } throw new RuntimeException("Test failed. UserPrincipal " + USER_NAME + " expected."); }
/** * Return any principal objects inside the attribute certificate issuer * object. * * @return an array of Principal objects (usually X500Principal) */ public Principal[] getPrincipals() { Object[] p = this.getNames(); List l = new ArrayList(); for (int i = 0; i != p.length; i++) { if (p[i] instanceof Principal) { l.add(p[i]); } } return (Principal[])l.toArray(new Principal[l.size()]); }
/** * Return the Principal associated with the given user name. */ @Override protected Principal getPrincipal(String username) { Connection dbConnection = open(); if (dbConnection == null) { return new GenericPrincipal(username, null, null); } try { return (new GenericPrincipal(username, getPassword(dbConnection, username), getRoles(dbConnection, username))); } finally { close(dbConnection); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Principal user = req.getUserPrincipal(); String pathInfo = req.getPathInfo(); System.out.printf("pathInfo=%s\n", pathInfo); String result = ""; if(pathInfo.endsWith("/getSubject")) { System.out.printf("Calling getSubject\n"); result = getSubject(resp); } else { System.out.printf("Calling getPrincipalClass\n"); result = getPrincipalClass(user); } resp.getWriter().write(result); }
/** * This method is called if the LoginContext's overall authentication * succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL * LoginModules succeeded). <p> * * If this LoginModule's own authentication attempt succeeded (checked by * retrieving the private state saved by the <code>login</code> method), then * this method associates a number of <code>NTPrincipal</code>s with the * <code>Subject</code> located in the <code>LoginModule</code>. If this * LoginModule's own authentication attempted failed, then this method removes * any state that was originally saved. * * @return true if this LoginModule's own login and commit * attempts succeeded, or false otherwise. * @exception LoginException if the commit fails. */ public boolean commit() throws LoginException { if (pending == null) { return false; } principals = new Vector(); Set s = subject.getPrincipals(); for (int p = 0; p < pending.size(); p++) { putPrincipal(s, (Principal) pending.get(p)); } commitSucceeded = true; prtln("\n COMMITTED (set commitSucceeded to true)"); return true; }
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; }
@RequestMapping("/oauth/confirm_access") public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception { AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest"); ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); model.put("auth_request", clientAuth); model.put("client", client); Map<String, String> scopes = new LinkedHashMap<String, String>(); for (String scope : clientAuth.getScope()) { scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false"); } for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) { if (clientAuth.getScope().contains(approval.getScope())) { scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(), approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false"); } } model.put("scopes", scopes); return new ModelAndView("authorize", model); }
@Test public void testRequestNoneActive() { final AuthenticationContext authCtx = prc.getSubcontext(AuthenticationContext.class); final List<Principal> principals = Arrays.<Principal> asList(new TestPrincipal("test3")); final RequestedPrincipalContext rpc = new RequestedPrincipalContext(); rpc.getPrincipalEvalPredicateFactoryRegistry().register(TestPrincipal.class, "exact", new ExactPrincipalEvalPredicateFactory()); rpc.setOperator("exact"); rpc.setRequestedPrincipals(principals); authCtx.addSubcontext(rpc, true); authCtx.getPotentialFlows().get("test3").setSupportedPrincipals(principals); action.execute(src); Assert.assertNull(authCtx.getAuthenticationResult()); Assert.assertEquals(authCtx.getAttemptedFlow().getId(), "test3"); }
public static long setAuthAttributes(ServerConnection connection) throws Exception { try { logger.debug("setAttributes()"); Object principal = ((HandShake) connection.getHandshake()).verifyCredentials(); long uniqueId; if (principal instanceof Subject) { uniqueId = connection.getClientUserAuths(connection.getProxyID()).putSubject((Subject) principal); } else { // this sets principal in map as well.... uniqueId = getUniqueId(connection, (Principal) principal); connection.setPrincipal((Principal) principal);// TODO:hitesh is this require now ??? } return uniqueId; } catch (Exception ex) { throw ex; } }
/** * @param issuers The list of acceptable CA issuer subject names or null if it does not matter which issuers are used * @return True if certificate matches issuer and key type */ protected boolean matches(final Certificate c, final String[] keyTypes, final Principal[] issuers) { if(!(c instanceof X509Certificate)) { log.warn(String.format("Certificate %s is not of type X509", c)); return false; } if(!Arrays.asList(keyTypes).contains(c.getPublicKey().getAlgorithm())) { log.warn(String.format("Key type %s does not match any of %s", c.getPublicKey().getAlgorithm(), Arrays.toString(keyTypes))); return false; } if(null == issuers || Arrays.asList(issuers).isEmpty()) { // null if it does not matter which issuers are used return true; } final X500Principal issuer = ((X509Certificate) c).getIssuerX500Principal(); if(!Arrays.asList(issuers).contains(issuer)) { log.warn(String.format("Issuer %s does not match", issuer)); return false; } return true; }
@Test public void testAuthenticateWithUserPasswordAndDigest() throws Exception { // GIVEN JNDIRealm realm = buildRealm(ha1(), "MD5"); realm.setUserPassword(USER_PASSWORD_ATTR); // WHEN String expectedResponse = MD5Encoder.encode(md5Helper.digest((ha1() + ":" + NONCE + ":" + HA2).getBytes())); Principal principal = realm.authenticate(USER, expectedResponse, NONCE, null, null, null, REALM, HA2); // THEN Assert.assertTrue(principal instanceof GenericPrincipal); Assert.assertEquals(ha1(), ((GenericPrincipal)principal).getPassword()); }
@RequestMapping(value = "/oauth/tokens/revoke.html", method = RequestMethod.POST) @PreAuthorize("hasRole('ROLE_ADMIN')") public String revokeToken(@RequestParam("user") String user, @RequestParam("token") String token, Principal principal) throws Exception { checkResourceOwner(user, principal); if (tokenServices.revokeToken(token)) { return "redirect:/oauth/tokens.html?revoke-success"; } else { return "redirect:/oauth/tokens.html?revoke-empty"; } }
@Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { if (!StringUtils.isEmpty(this.keyAlias)) { PrivateKey key = this.delegate.getPrivateKey(this.keyAlias); return getKeyAlias(keyType, key); } return this.delegate.chooseServerAlias(keyType, issuers, socket); }
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Authentication auth = baseRequest.getAuthentication(); if (Authentication.UNAUTHENTICATED == auth) { throw new AssertionError("Unauthenticated users should not reach here!"); } baseRequest.setHandled(true); UserAuthentication userAuth = (UserAuthentication) auth; UserIdentity userIdentity = userAuth.getUserIdentity(); Principal userPrincipal = userIdentity.getUserPrincipal(); response.getWriter().print("OK " + userPrincipal.getName()); response.setStatus(200); }
/** * Return the <code>Principal</code> associated with the given user name. */ @Override protected Principal getPrincipal(String username) { return authenticate(username, new JAASCallbackHandler(this, username, null, null, null, null, null, null, null, HttpServletRequest.CLIENT_CERT_AUTH)); }
/** * Check that the principal contained in the Subject is of * type JMXPrincipal and refers to the principalName identity. */ private void checkSubject(String op) { 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(op+": Authenticated subject contains " + "invalid principal type = " + principal.getClass().getName()); String identity = principal.getName(); if (!identity.equals(principalName)) throw new SecurityException(op+": Authenticated subject contains " + "invalid principal name = " + identity); }
@Test public void secureResponseCaching() throws IOException { server.useHttps(sslClient.socketFactory, false); server.enqueue(new MockResponse() .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) .setBody("ABC")); client = client.newBuilder() .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager) .hostnameVerifier(NULL_HOSTNAME_VERIFIER) .build(); Request request = new Request.Builder().url(server.url("/")).build(); Response response1 = client.newCall(request).execute(); BufferedSource in = response1.body().source(); assertEquals("ABC", in.readUtf8()); // OpenJDK 6 fails on this line, complaining that the connection isn't open yet CipherSuite cipherSuite = response1.handshake().cipherSuite(); List<Certificate> localCerts = response1.handshake().localCertificates(); List<Certificate> serverCerts = response1.handshake().peerCertificates(); Principal peerPrincipal = response1.handshake().peerPrincipal(); Principal localPrincipal = response1.handshake().localPrincipal(); Response response2 = client.newCall(request).execute(); // Cached! assertEquals("ABC", response2.body().string()); assertEquals(2, cache.requestCount()); assertEquals(1, cache.networkCount()); assertEquals(1, cache.hitCount()); assertEquals(cipherSuite, response2.handshake().cipherSuite()); assertEquals(localCerts, response2.handshake().localCertificates()); assertEquals(serverCerts, response2.handshake().peerCertificates()); assertEquals(peerPrincipal, response2.handshake().peerPrincipal()); assertEquals(localPrincipal, response2.handshake().localPrincipal()); }
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; }
/** * Return the Principal associated with the specified chain of X509 client * certificates. If there is none, return <code>null</code>. * * @param certs * Array of client certificates, with the first one in the array * being the certificate of the client itself. */ @Override public Principal authenticate(X509Certificate[] certs) { Principal authenticatedUser = null; String username = null; if (certs != null && certs.length > 0) { username = certs[0].getSubjectDN().getName(); } for (Realm realm : realms) { if (log.isDebugEnabled()) { log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo())); } authenticatedUser = realm.authenticate(certs); if (authenticatedUser == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo())); } } else { if (log.isDebugEnabled()) { log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo())); } break; } } return authenticatedUser; }
/** * Returns the principal the client sent to the * server, or null if the client did not authenticate. */ Principal getLocalPrincipal() { if (cachedResponse != null) { return ((SecureCacheResponse)cachedResponse).getLocalPrincipal(); } if (http == null) { throw new IllegalStateException("connection not yet open"); } else { return (((HttpsClient)http).getLocalPrincipal()); } }
@PostMapping("/unregister") public String unregisterStudent(@RequestParam Long course, RedirectAttributes redirectAttributes, Principal principal) { Student student = studentService.findByUsername(principal.getName()); Course courseToUnregister = courseService.unregisterStudentFromCourse(student, course); String successMsg = messages.msg("student.my.courses.unregister.success", courseToUnregister.getSubject().getName()); redirectAttributes.addFlashAttribute("flashMessageNotLocalized", successMsg); return "redirect:/student/myCourses"; }
/** * Retrieves the {@linkplain Subject} principals * @param subject The subject * @return If the {@code Subject} is immutable it will return the principals directly. * If the {@code Subject} is mutable it will create an unmodifiable copy. */ private static Collection<Principal> getSubjectPrincipals(Subject subject) { if (subject.isReadOnly()) { return subject.getPrincipals(); } List<Principal> principals = Arrays.asList(subject.getPrincipals().toArray(new Principal[0])); return Collections.unmodifiableList(principals); }
private void setupSecurity(AgroalConnectionFactoryConfiguration configuration) { Principal principal = configuration.principal(); if ( principal == null ) { // skip! } else if ( principal instanceof NamePrincipal ) { jdbcProperties.put( USER_PROPERTY_NAME, principal.getName() ); } // Add other principal types here else { throw new IllegalArgumentException( "Unknown Principal type: " + principal.getClass().getName() ); } for ( Object credential : configuration.credentials() ) { if ( credential instanceof SimplePassword ) { jdbcProperties.put( PASSWORD_PROPERTY_NAME, ( (SimplePassword) credential ).getWord() ); } // Add other credential types here else { throw new IllegalArgumentException( "Unknown Credential type: " + credential.getClass().getName() ); } } }
@Test public void getServerAliases() { String s = ""; Principal[] principals = new Principal[0]; String alias1 = "alias1"; when(this.keyManager1.getServerAliases(s, principals)).thenReturn(new String[]{alias1}); String alias2 = "alias2"; when(this.keyManager2.getServerAliases(s, principals)).thenReturn(new String[]{alias2}); assertThat(this.delegatingKeyManager.getServerAliases(s, principals)).contains(alias1, alias2); }
public AccessControlContext delegatedContext(AccessControlContext authenticatedACC, Subject delegatedSubject, boolean removeCallerContext) throws SecurityException { if (System.getSecurityManager() != null && authenticatedACC == null) { throw new SecurityException("Illegal AccessControlContext: null"); } // Check if the subject delegation permission allows the // authenticated subject to assume the identity of each // principal in the delegated subject // Collection<Principal> ps = getSubjectPrincipals(delegatedSubject); final Collection<Permission> permissions = new ArrayList<>(ps.size()); for(Principal p : ps) { final String pname = p.getClass().getName() + "." + p.getName(); permissions.add(new SubjectDelegationPermission(pname)); } PrivilegedAction<Void> action = new PrivilegedAction<Void>() { public Void run() { for (Permission sdp : permissions) { AccessController.checkPermission(sdp); } return null; } }; AccessController.doPrivileged(action, authenticatedACC); return getDelegatedAcc(delegatedSubject, removeCallerContext); }
public String chooseServerAlias( final String keyType, final Principal[] issuers, final Socket socket) { final Map<String, PrivateKeyDetails> validAliases = new HashMap<String, PrivateKeyDetails>(); final String[] aliases = this.keyManager.getServerAliases(keyType, issuers); if (aliases != null) { for (final String alias: aliases) { validAliases.put(alias, new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias))); } } return this.aliasStrategy.chooseAlias(validAliases, socket); }
/** * Unknown user triggers NPE. */ @Test public void testBug56246() { MemoryRealm memoryRealm = new MemoryRealm(); Principal p = memoryRealm.authenticate("foo", "bar"); Assert.assertNull(p); }
@GetMapping public String loginPage(ModelMap model, Principal principal, HttpServletRequest request, HttpServletResponse response) { OneTimeCookie.consume(request, response, LOGIN_RETURN_URL) .map(ReturnableLoginUrlAuthenticationEntryPoint::decodeReturnUrl) .ifPresent(returnUrl -> model.addAttribute("login_return_url", returnUrl)); OneTimeCookie.consume(request, response, LOGIN_TOOLTIP) .ifPresent(tooltip -> model.addAttribute("login_tooltip", tooltip)); if (principal != null) return "redirect:/"; return "login"; }
@GetMapping("/login") public String login(Principal principal) { if (principal != null) { return "redirect:/home"; } return "/login"; }
@Test(timeout=60000) public void testDynamicPrincipalDiscovery() throws Exception { String[] keytabUsers = new String[]{ "HTTP/host1", "HTTP/host2", "HTTP2/host1", "XHTTP/host" }; String keytab = KerberosTestUtils.getKeytabFile(); getKdc().createPrincipal(new File(keytab), keytabUsers); // destroy handler created in setUp() handler.destroy(); Properties props = new Properties(); props.setProperty(KerberosAuthenticationHandler.KEYTAB, keytab); props.setProperty(KerberosAuthenticationHandler.PRINCIPAL, "*"); handler = getNewAuthenticationHandler(); handler.init(props); Assert.assertEquals(KerberosTestUtils.getKeytabFile(), handler.getKeytab()); Set<KerberosPrincipal> loginPrincipals = handler.getPrincipals(); for (String user : keytabUsers) { Principal principal = new KerberosPrincipal( user + "@" + KerberosTestUtils.getRealm()); boolean expected = user.startsWith("HTTP/"); Assert.assertEquals("checking for "+user, expected, loginPrincipals.contains(principal)); } }
@Override public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) { if (serverKeyAlias!=null) { return serverKeyAlias; } return super.chooseEngineServerAlias(keyType, issuers, engine); }
public SingleSignOnEntry(Principal principal, String authType, String username, String password) { super(); this.principal = principal; this.authType = authType; this.username = username; this.password = password; }
/** * Does principal name match pattern? * * @param principal the principal * @param pattern the pattern * @return true, if successful */ 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; }
@Override public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) { final javax.net.ssl.X509KeyManager manager; try { manager = this.getKeystore(); } catch(IOException e) { return null; } return manager.chooseServerAlias(keyType, issuers, socket); }
@SubscribeMapping("/topic/activity") @SendTo("/topic/tracker") public ActivityDTO sendActivity(@Payload ActivityDTO activityDTO, StompHeaderAccessor stompHeaderAccessor, Principal principal) { activityDTO.setUserLogin(SecurityUtils.getCurrentUserLogin()); activityDTO.setUserLogin(principal.getName()); activityDTO.setSessionId(stompHeaderAccessor.getSessionId()); activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString()); Instant instant = Instant.ofEpochMilli(Calendar.getInstance().getTimeInMillis()); activityDTO.setTime(dateTimeFormatter.format(ZonedDateTime.ofInstant(instant, ZoneOffset.systemDefault()))); log.debug("Sending user tracking data {}", activityDTO); return activityDTO; }
@Override public Principal getCallerPrincipal() { if (username == null) { return null; } return new Principal() { @Override public String getName() { return username; } }; }
@RequestMapping(path = "/me") public ResponseEntity<User> me(Principal principal) { User user = null; if(principal != null) { user = userService.getUserByUsername(principal.getName()); } return Optional.ofNullable(user) .map(a -> new ResponseEntity<>(a, HttpStatus.OK)) .orElseThrow(() -> new UsernameNotFoundException("Username not found")); }