private void setAnonymousRoles(final Request request) { final List<String> roles = new ArrayList<String>(); roles.add("anonymous"); roles.add("islandora"); final String name = "anonymous"; final GenericPrincipal principal = new GenericPrincipal(name, null, roles); request.setUserPrincipal(principal); }
private void setUserRolesFromStaticToken(final Request request, final Token token) { final List<String> roles = token.getRoles(); roles.add("islandora"); final String name = token.getUser(); final GenericPrincipal principal = new GenericPrincipal(name, null, roles); request.setUserPrincipal(principal); }
private void setUserRolesFromToken(final Request request, final Verifier verifier) { final List<String> roles = verifier.getRoles(); roles.add("islandora"); roles.add(verifier.getUrl()); final String name = verifier.getName(); final GenericPrincipal principal = new GenericPrincipal(name, null, roles); request.setUserPrincipal(principal); }
@Test public void shouldPassAuthToken() throws Exception { final ArgumentCaptor<GenericPrincipal> argument = ArgumentCaptor.forClass(GenericPrincipal.class); final String token = "Bearer 1337"; final SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setAuthConstraint(true); when(realm.findSecurityConstraints(request, request.getContext())) .thenReturn(new SecurityConstraint[] { securityConstraint }); when(request.getHeader("Authorization")) .thenReturn(token); synValve.start(); synValve.invoke(request, response); final InOrder inOrder = inOrder(request, nextValve); inOrder.verify(request).getHeader("Authorization"); inOrder.verify(request).setUserPrincipal(argument.capture()); inOrder.verify(request).setAuthType("SYN"); inOrder.verify(nextValve).invoke(request, response); assertEquals("islandoraAdmin", argument.getValue().getName()); final List<String> roles = Arrays.asList(argument.getValue().getRoles()); assertEquals(1, roles.size()); assertTrue(roles.contains("islandora")); assertNull(argument.getValue().getPassword()); }
/** * Add a new user to the map * * @param username User's username * @param password User's password (clear text) * @param roles Comma-delimited set of roles associated with * this user */ private void addUser(final String username, final String password, final String roles) { // Accumulate the list of roles for this user String rolesToProcess = roles + ','; final ArrayList list = new ArrayList(1); while (true) { final int comma = rolesToProcess.indexOf(','); if (comma < 0) break; final String role = rolesToProcess.substring(0, comma).trim(); list.add(role); rolesToProcess = rolesToProcess.substring(comma + 1); } // Construct and cache the Principal for this user final GenericPrincipal principal = new GenericPrincipal(this, username, password, list); principals.put(username, principal); }
public static void writePrincipal(GenericPrincipal p, ObjectOutput out) throws IOException { out.writeUTF(p.getName()); out.writeBoolean(p.getPassword() != null); if (p.getPassword() != null) out.writeUTF(p.getPassword()); String[] roles = p.getRoles(); if (roles == null) roles = new String[0]; out.writeInt(roles.length); for (int i = 0; i < roles.length; i++) out.writeUTF(roles[i]); boolean hasUserPrincipal = (p != p.getUserPrincipal() && p.getUserPrincipal() instanceof Serializable); out.writeBoolean(hasUserPrincipal); if (hasUserPrincipal) out.writeObject(p.getUserPrincipal()); }
@Override public void logout(Request request) throws ServletException { Principal p = request.getPrincipal(); if (p instanceof GenericPrincipal) { try { ((GenericPrincipal) p).logout(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("authenticator.tomcatPrincipalLogoutFail"), t); } } register(request, request.getResponse(), null, null, null, null); }
public static GenericPrincipal readPrincipal(ObjectInput in) throws IOException, ClassNotFoundException { String name = in.readUTF(); boolean hasPwd = in.readBoolean(); String pwd = null; if ( hasPwd ) pwd = in.readUTF(); int size = in.readInt(); String[] roles = new String[size]; for ( int i=0; i<size; i++ ) roles[i] = in.readUTF(); Principal userPrincipal = null; boolean hasUserPrincipal = in.readBoolean(); if (hasUserPrincipal) { try { userPrincipal = (Principal) in.readObject(); } catch (ClassNotFoundException e) { log.error(sm.getString( "serializablePrincipal.readPrincipal.cnfe"), e); throw e; } } return new GenericPrincipal(name,pwd,Arrays.asList(roles), userPrincipal); }
@Override public boolean isCallerInRole(final String role) { final Principal principal = getCallerPrincipal(); if (TomcatUser.class.isInstance(principal)) { if ("**".equals(role)) { return true; // ie logged in through tomcat } final TomcatUser tomcatUser = (TomcatUser) principal; final GenericPrincipal genericPrincipal = (GenericPrincipal) tomcatUser.getTomcatPrincipal(); final String[] roles = genericPrincipal.getRoles(); if (roles != null) { for (final String userRole : roles) { if (userRole.equals(role)) { return true; } } } return false; } return super.isCallerInRole(role); }
/** * 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; }
@Test public void shouldPassAuthDefaultSite() throws Exception { final String host = "http://test2.com"; final String token = JWT .create() .withClaim("uid", 1) .withClaim("name", "normalUser") .withClaim("url", host) .withArrayClaim("roles", new String[] {}) .withIssuedAt(Date.from(LocalDateTime.now().toInstant(offset))) .withExpiresAt(Date.from(LocalDateTime.now().plusHours(2).toInstant(offset))) .sign(Algorithm.HMAC256("secret2")); final ArgumentCaptor<GenericPrincipal> argument = ArgumentCaptor.forClass(GenericPrincipal.class); final SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setAuthConstraint(true); when(realm.findSecurityConstraints(request, request.getContext())) .thenReturn(new SecurityConstraint[] { securityConstraint }); when(request.getHeader("Authorization")) .thenReturn("Bearer " + token); synValve.start(); synValve.invoke(request, response); final InOrder inOrder = inOrder(request, nextValve); inOrder.verify(request).getHeader("Authorization"); inOrder.verify(request).setUserPrincipal(argument.capture()); inOrder.verify(request).setAuthType("SYN"); inOrder.verify(nextValve).invoke(request, response); assertEquals("normalUser", argument.getValue().getName()); final List<String> roles = Arrays.asList(argument.getValue().getRoles()); assertEquals(2, roles.size()); assertTrue(roles.contains("islandora")); assertTrue(roles.contains("http://test2.com")); assertNull(argument.getValue().getPassword()); }
@Test public void allowGetWithoutToken() throws Exception { final String host = "http://anon-test.com"; final SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setAuthConstraint(true); when(realm.findSecurityConstraints(request, request.getContext())) .thenReturn(new SecurityConstraint[] { securityConstraint }); when(request.getMethod()).thenReturn("GET"); when(mockHost.toString()).thenReturn(host); when(request.getHost()).thenReturn(mockHost); final ArgumentCaptor<GenericPrincipal> argument = ArgumentCaptor.forClass(GenericPrincipal.class); final String testXml = String.join("\n" , "<config version='1'>" , " <site url='" + host + "' algorithm='HS256' encoding='plain' anonymous='true'>" , "secretFool" , " </site>" , "</config>" ); Files.write(Paths.get(this.settings.getAbsolutePath()), testXml.getBytes()); synValve.start(); synValve.invoke(request, response); final InOrder inOrder = inOrder(request, nextValve); inOrder.verify(request).setUserPrincipal(argument.capture()); inOrder.verify(nextValve).invoke(request, response); assertEquals("anonymous", argument.getValue().getName()); final List<String> roles = Arrays.asList(argument.getValue().getRoles()); assertEquals(2, roles.size()); assertTrue(roles.contains("anonymous")); assertTrue(roles.contains("islandora")); assertNull(argument.getValue().getPassword()); }
@Test public void allowHeadWithoutToken() throws Exception { final String host = "http://anon-test.com"; final SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setAuthConstraint(true); when(realm.findSecurityConstraints(request, request.getContext())) .thenReturn(new SecurityConstraint[] { securityConstraint }); when(request.getMethod()).thenReturn("HEAD"); when(mockHost.toString()).thenReturn(host); when(request.getHost()).thenReturn(mockHost); final ArgumentCaptor<GenericPrincipal> argument = ArgumentCaptor.forClass(GenericPrincipal.class); final String testXml = String.join("\n" , "<config version='1'>" , " <site url='" + host + "' algorithm='HS256' encoding='plain' anonymous='true'>" , "secretFool" , " </site>" , "</config>" ); Files.write(Paths.get(this.settings.getAbsolutePath()), testXml.getBytes()); synValve.start(); synValve.invoke(request, response); final InOrder inOrder = inOrder(request, nextValve); inOrder.verify(request).setUserPrincipal(argument.capture()); inOrder.verify(nextValve).invoke(request, response); assertEquals("anonymous", argument.getValue().getName()); final List<String> roles = Arrays.asList(argument.getValue().getRoles()); assertEquals(2, roles.size()); assertTrue(roles.contains("anonymous")); assertTrue(roles.contains("islandora")); assertNull(argument.getValue().getPassword()); }
@Test public void overrideDefaultDeny() throws Exception { final String host = "http://anon-test.com"; final SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setAuthConstraint(true); when(realm.findSecurityConstraints(request, request.getContext())) .thenReturn(new SecurityConstraint[] { securityConstraint }); when(request.getMethod()).thenReturn("GET"); when(mockHost.toString()).thenReturn(host); when(request.getHost()).thenReturn(mockHost); final ArgumentCaptor<GenericPrincipal> argument = ArgumentCaptor.forClass(GenericPrincipal.class); final String testXml = String.join("\n" , "<config version='1'>" , " <site url='" + host + "' algorithm='HS256' encoding='plain' anonymous='true'>" , "secretFool" , " </site>" , " <site algorithm='RS256' encoding='plain' anonymous='true' default='false'/>" , "</config>" ); Files.write(Paths.get(this.settings.getAbsolutePath()), testXml.getBytes()); synValve.start(); synValve.invoke(request, response); final InOrder inOrder = inOrder(request, nextValve); inOrder.verify(request).setUserPrincipal(argument.capture()); inOrder.verify(nextValve).invoke(request, response); assertEquals("anonymous", argument.getValue().getName()); final List<String> roles = Arrays.asList(argument.getValue().getRoles()); assertEquals(2, roles.size()); assertTrue(roles.contains("anonymous")); assertTrue(roles.contains("islandora")); assertNull(argument.getValue().getPassword()); }
@Test public void defaultAndSiteAllowed() throws Exception { final String host = "http://anon-test.com"; final SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setAuthConstraint(true); when(realm.findSecurityConstraints(request, request.getContext())) .thenReturn(new SecurityConstraint[] { securityConstraint }); when(request.getMethod()).thenReturn("GET"); when(mockHost.toString()).thenReturn(host); when(request.getHost()).thenReturn(mockHost); final ArgumentCaptor<GenericPrincipal> argument = ArgumentCaptor.forClass(GenericPrincipal.class); final String testXml = String.join("\n" , "<config version='1'>" , " <site algorithm='RS256' encoding='plain' anonymous='true' default='true'/>" , "</config>" ); Files.write(Paths.get(this.settings.getAbsolutePath()), testXml.getBytes()); synValve.start(); synValve.invoke(request, response); final InOrder inOrder = inOrder(request, nextValve); inOrder.verify(request).setUserPrincipal(argument.capture()); inOrder.verify(nextValve).invoke(request, response); assertEquals("anonymous", argument.getValue().getName()); final List<String> roles = Arrays.asList(argument.getValue().getRoles()); assertEquals(2, roles.size()); assertTrue(roles.contains("anonymous")); assertTrue(roles.contains("islandora")); assertNull(argument.getValue().getPassword()); }
public static SerializablePrincipal createPrincipal(GenericPrincipal principal) { if ( principal==null) return null; return new SerializablePrincipal(principal.getName(), principal.getPassword(), principal.getRoles()!=null?Arrays.asList(principal.getRoles()):null, principal.getUserPrincipal()!=principal?principal.getUserPrincipal():null); }
public static void writePrincipal(GenericPrincipal p, ObjectOutput out) throws IOException { out.writeUTF(p.getName()); out.writeBoolean(p.getPassword()!=null); if ( p.getPassword()!= null ) out.writeUTF(p.getPassword()); String[] roles = p.getRoles(); if ( roles == null ) roles = new String[0]; out.writeInt(roles.length); for ( int i=0; i<roles.length; i++ ) out.writeUTF(roles[i]); boolean hasUserPrincipal = (p != p.getUserPrincipal() && p.getUserPrincipal() instanceof Serializable); out.writeBoolean(hasUserPrincipal); if (hasUserPrincipal) out.writeObject(p.getUserPrincipal()); }
/** * convert principal at SerializablePrincipal for backup nodes. * Only support principals from type {@link GenericPrincipal GenericPrincipal} * @param p Session principal * @see GenericPrincipal */ public void setPrincipal(Principal p) { int action = (p==null)?ACTION_REMOVE:ACTION_SET; SerializablePrincipal sp = null; if ( p != null ) { if(p instanceof GenericPrincipal) { sp = SerializablePrincipal.createPrincipal((GenericPrincipal)p); if(log.isDebugEnabled()) log.debug(sm.getString("deltaRequest.showPrincipal", p.getName() , getSessionId())); } else log.error(sm.getString("deltaRequest.wrongPrincipalClass",p.getClass().getName())); } addAction(TYPE_PRINCIPAL,action,NAME_PRINCIPAL,sp); }
@Override public Object get(Request request, String name) { if (request.userPrincipal instanceof GenericPrincipal) { return ((GenericPrincipal) request.userPrincipal) .getGssCredential(); } return null; }
/** * Return the principal that has been authenticated for this Request. */ public Principal getUserPrincipal() { if (userPrincipal instanceof GenericPrincipal) { return ((GenericPrincipal) userPrincipal).getUserPrincipal(); } else { return (userPrincipal); } }
/** * Return the password associated with the given principal's * user name. */ protected String getPassword(final String username) { final GenericPrincipal principal = (GenericPrincipal) principals.get(username); if (principal != null) { return principal.getPassword(); } else { return null; } }
/** * * @param authentication * @return Authentication */ @Override public Authentication authenticate(Authentication authentication) { Realm realm; Set<GrantedAuthority> auths = new HashSet<>(); try { realm = getTomcatContextRealm(); if(realm instanceof NullRealm) { throw new ProviderNotFoundException("No Realms configured for Jwala to Authenticate"); } Principal principal = realm.authenticate(authentication.getName(), authentication.getCredentials().toString()); if (principal == null) { throw new BadCredentialsException("Username or Password not found."); } else { if (principal instanceof GenericPrincipal) { String[] roles = ((GenericPrincipal) principal).getRoles(); for (String role : roles) { auths.add(new SimpleGrantedAuthority(role)); } } GrantedAuthoritiesMapperImpl grantedAuthoritiesMapper = new GrantedAuthoritiesMapperImpl(); return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), grantedAuthoritiesMapper.mapAuthorities(auths)); } } catch (AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException e) { LOGGER.error("Error getting realms", e); throw new ProviderNotFoundException(e.getMessage()); } }
public static SerializablePrincipal createPrincipal(GenericPrincipal principal) { if (principal == null) return null; return new SerializablePrincipal(principal.getName(), principal.getPassword(), principal.getRoles() != null ? Arrays.asList(principal.getRoles()) : null, principal.getUserPrincipal() != principal ? principal.getUserPrincipal() : null); }
/** * convert principal at SerializablePrincipal for backup nodes. Only support * principals from type {@link GenericPrincipal GenericPrincipal} * * @param p * Session principal * @see GenericPrincipal */ public void setPrincipal(Principal p) { int action = (p == null) ? ACTION_REMOVE : ACTION_SET; SerializablePrincipal sp = null; if (p != null) { if (p instanceof GenericPrincipal) { sp = SerializablePrincipal.createPrincipal((GenericPrincipal) p); if (log.isDebugEnabled()) log.debug(sm.getString("deltaRequest.showPrincipal", p.getName(), getSessionId())); } else log.error(sm.getString("deltaRequest.wrongPrincipalClass", p.getClass().getName())); } addAction(TYPE_PRINCIPAL, action, NAME_PRINCIPAL, sp); }
@Override public Object get(Request request, String name) { if (request.userPrincipal instanceof GenericPrincipal) { return ((GenericPrincipal) request.userPrincipal).getGssCredential(); } return null; }
protected void createPrincipalAndRoles(HttpServletRequest request, org.jboss.resteasy.auth.oauth.OAuthConsumer consumer, OAuthToken accessToken) { Set<String> roles = oauthProvider.convertPermissionsToRoles(accessToken.getPermissions()); Realm realm = new OAuthRealm(roles); context.setRealm(realm); final Principal principal = new GenericPrincipal(realm, consumer.getKey(), "", new ArrayList<String>(roles)); ((Request)request).setUserPrincipal(principal); ((Request)request).setAuthType("OAuth"); }
@Override public void invoke(Request request, Response response) throws IOException, ServletException { Principal principal = request.getUserPrincipal(); if (principal == null) { Cookie[] cookies = request.getCookies(); Cookie ltpa2Cookie = null; for(int i=0;cookies!=null && i<cookies.length;i++){ if (cookies[i].getName().equals("LtpaToken2")){ ltpa2Cookie = cookies[i]; break; } } if(ltpa2Cookie == null){ log.info("LtpaToken2 cookie not found"); }else{ try { String tokenDecrypted = ltpaUtils.decrypt(ltpa2Cookie.getValue()); String userName = ltpaUtils.extractUserName(tokenDecrypted, dnPrefix); Principal p = new GenericPrincipal(userName,null,roles); request.setAuthType("LTPA"); request.setUserPrincipal(p); } catch (GeneralSecurityException ex) { log.error("Error obtaining username from ltpatoken2", ex); } } }else{ log.info("User already authenticated " + principal); } getNext().invoke(request, response); }
/** {@inheritDoc} */ public Principal convertPrincipal(Principal principal) { if (principal instanceof GenericPrincipal) { return principal; } else { // We need to do the converting if (principal instanceof AbstractUser) { AbstractUser abstractUser = (AbstractUser) principal; List<String> roles = new ArrayList<String> (); Iterator roleIterator = abstractUser.getRoles(); while (roleIterator.hasNext()) { Role role = (Role) roleIterator.next(); roles.add(role.getName()); } String userName = abstractUser.getUsername(); String password = abstractUser.getPassword(); return new GenericPrincipal(userName, password, roles); } else { // no return principal; } } }
/** * Notifies the cluster of the creation of a new SSO entry * and register the specified Principal as being associated * with the specified value for the single sign on identifier. * * @param ssoId Single sign on identifier to register * @param principal Associated user principal that is identified * @param authType Authentication type used to authenticate this * user principal * @param username Username used to authenticate this user * @param password Password used to authenticate this user */ @Override protected void register(String ssoId, Principal principal, String authType, String username, String password) { if (cluster != null && cluster.getMembers().length > 0) { messageNumber++; SingleSignOnMessage msg = new SingleSignOnMessage(cluster.getLocalMember(), ssoId, null); msg.setAction(SingleSignOnMessage.REGISTER_SESSION); msg.setAuthType(authType); msg.setUsername(username); msg.setPassword(password); SerializablePrincipal sp = null; if (principal instanceof GenericPrincipal) { sp = SerializablePrincipal.createPrincipal((GenericPrincipal) principal); msg.setPrincipal(sp); } cluster.send(msg); if (containerLog.isDebugEnabled()) containerLog.debug("SingleSignOnMessage Send with action " + msg.getAction()); } registerLocal(ssoId, principal, authType, username, password); }
/** * Notifies the cluster of an update of the security credentials * associated with an SSO session. Updates any <code>SingleSignOnEntry</code> * found under key <code>ssoId</code> with the given authentication data. * <p> * The purpose of this method is to allow an SSO entry that was * established without a username/password combination (i.e. established * following DIGEST or CLIENT-CERT authentication) to be updated with * a username and password if one becomes available through a subsequent * BASIC or FORM authentication. The SSO entry will then be usable for * reauthentication. * <p> * <b>NOTE:</b> Only updates the SSO entry if a call to * <code>SingleSignOnEntry.getCanReauthenticate()</code> returns * <code>false</code>; otherwise, it is assumed that the SSO entry already * has sufficient information to allow reauthentication and that no update * is needed. * * @param ssoId identifier of Single sign to be updated * @param principal the <code>Principal</code> returned by the latest * call to <code>Realm.authenticate</code>. * @param authType the type of authenticator used (BASIC, CLIENT-CERT, * DIGEST or FORM) * @param username the username (if any) used for the authentication * @param password the password (if any) used for the authentication */ @Override protected void update(String ssoId, Principal principal, String authType, String username, String password) { if (cluster != null && cluster.getMembers().length > 0) { messageNumber++; SingleSignOnMessage msg = new SingleSignOnMessage(cluster.getLocalMember(), ssoId, null); msg.setAction(SingleSignOnMessage.UPDATE_SESSION); msg.setAuthType(authType); msg.setUsername(username); msg.setPassword(password); SerializablePrincipal sp = null; if (principal instanceof GenericPrincipal) { sp = SerializablePrincipal.createPrincipal((GenericPrincipal) principal); msg.setPrincipal(sp); } cluster.send(msg); if (containerLog.isDebugEnabled()) containerLog.debug("SingleSignOnMessage Send with action " + msg.getAction()); } updateLocal(ssoId, principal, authType, username, password); }