Java Code Examples for java.security.Principal

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project gatein-sso, under directory /saml/gatein-saml-plugin/src/main/java/org/gatein/sso/saml/plugin/valve/.

Source file: PortalIDPWebBrowserSSOValve.java

  42 
vote

protected boolean skipProcessingByNextValves(Session session){
  Principal principal=(Principal)session.getNote(Constants.FORM_PRINCIPAL_NOTE);
  String samlRequest=(String)session.getNote(GeneralConstants.SAML_REQUEST_KEY);
  String samlResponse=(String)session.getNote(GeneralConstants.SAML_RESPONSE_KEY);
  return (principal != null && (samlRequest != null || samlResponse != null));
}
 

Example 2

From project candlepin, under directory /src/test/java/org/candlepin/resteasy/interceptor/.

Source file: SSLAuthTest.java

  33 
vote

private void mockCert(String dn){
  X509Certificate idCert=mock(X509Certificate.class);
  Principal principal=mock(Principal.class);
  when(principal.getName()).thenReturn(dn);
  when(idCert.getSubjectDN()).thenReturn(principal);
  when(this.request.getAttribute("javax.servlet.request.X509Certificate")).thenReturn(new X509Certificate[]{idCert});
}
 

Example 3

From project Carolina-Digital-Repository, under directory /access-security/src/main/java/edu/unc/lib/dl/security/access/.

Source file: SpoofShibbolethHeadersValve.java

  33 
vote

@Override public void invoke(Request request,Response response) throws IOException, ServletException {
  MessageBytes memb=request.getCoyoteRequest().getMimeHeaders().addValue("isMemberOf");
  memb.setString(this.getIsMemberOf());
  final String credentials="credentials";
  final List<String> roles=new ArrayList<String>();
  final Principal principal=new GenericPrincipal(this.getRemoteUser(),credentials,roles);
  request.setUserPrincipal(principal);
  getNext().invoke(request,response);
}
 

Example 4

From project dev-examples, under directory /misc-demo/src/main/java/org/richfaces/demo/.

Source file: UserBean.java

  33 
vote

public boolean isUserInRole(String role){
  Principal principal=getPrincipal();
  if (principal != null) {
    return principal.getName().equals(role);
  }
  return false;
}
 

Example 5

From project JavaEe6WebApp, under directory /src/main/java/uk/me/doitto/webapp/model/.

Source file: TemplateController.java

  33 
vote

public String getLoggedInUser(){
  Principal principal=FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
  if (principal != null) {
    return principal.getName();
  }
  return "No User";
}
 

Example 6

From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.

Source file: GAEListener.java

  32 
vote

private void initUserData(JBossEnvironment environment,HttpServletRequest request){
  Principal principal=request.getUserPrincipal();
  if (principal != null) {
    environment.setEmail(principal.getName());
  }
}
 

Example 7

From project core_1, under directory /security/src/main/java/org/switchyard/security/credential/extract/.

Source file: WebServiceContextCredentialsExtractor.java

  32 
vote

/** 
 * {@inheritDoc}
 */
@Override public Set<Credential> extractCredentials(WebServiceContext source){
  Set<Credential> credentials=new HashSet<Credential>();
  if (source != null) {
    Principal userPrincipal=source.getUserPrincipal();
    if (userPrincipal != null) {
      credentials.add(new PrincipalCredential(userPrincipal,true));
    }
  }
  return credentials;
}
 

Example 8

From project core_5, under directory /exo.core.component.security.core/src/main/java/org/exoplatform/services/security/jaas/.

Source file: JAASGroup.java

  32 
vote

/** 
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked") public boolean isMember(Principal principal){
  Enumeration en=members();
  while (en.hasMoreElements()) {
    Principal principal1=(Principal)en.nextElement();
    if (principal1.getName().equals(principal.getName()))     return true;
  }
  return false;
}
 

Example 9

From project exanpe-t5-lib, under directory /src/main/java/fr/exanpe/t5/lib/internal/authorize/.

Source file: AuthorizePageFilter.java

  32 
vote

private String getUsername(){
  Principal p=requestGlobals.getHTTPServletRequest().getUserPrincipal();
  if (p == null) {
    return "-";
  }
  return p.getName();
}
 

Example 10

From project glimpse, under directory /glimpse-server/src/main/java/br/com/tecsinapse/glimpse/server/sunhttp/.

Source file: AuthenticationHandler.java

  32 
vote

public void handle(HttpExchange exchange) throws IOException {
  Principal principal=exchange.getPrincipal();
  String username=principal.getName();
  try {
    AuthManager.setCurrentUser(username);
    delegate.handle(exchange);
  }
  finally {
    AuthManager.releaseCurrentUser();
  }
}
 

Example 11

From project gmc, under directory /src/org.gluster.storage.management.gateway/src/org/gluster/storage/management/gateway/filters/.

Source file: AuditFilter.java

  32 
vote

@Override public ContainerRequest filter(ContainerRequest req){
  Principal principal=req.getUserPrincipal();
  if (principal != null) {
    logger.info("REQUEST from [" + principal.getName() + "] : ["+ req.getMethod()+ "]["+ req.getPath()+ "]");
  }
 else {
    logger.info("REQUEST [" + req.getMethod() + "]["+ req.getPath()+ "]");
  }
  return req;
}
 

Example 12

From project Ivory, under directory /common/src/main/java/org/apache/ivory/security/.

Source file: IvoryLoginModule.java

  32 
vote

@Override public boolean commit() throws LoginException {
  if (!subject.getPrincipals(SecurityConstants.OS_PRINCIPAL_CLASS).isEmpty()) {
    return true;
  }
  Principal user=getCanonicalUser(SecurityConstants.OS_PRINCIPAL_CLASS);
  if (user != null) {
    subject.getPrincipals().add(new UnixPrincipal(user.getName()));
    return true;
  }
  LOG.error("No such user " + subject);
  throw new LoginException("No such user " + subject);
}
 

Example 13

From project jackrabbit-oak, under directory /oak-core/src/main/java/org/apache/jackrabbit/oak/security/principal/.

Source file: PrincipalManagerImpl.java

  32 
vote

@Override public Principal getEveryone(){
  Principal everyone=getPrincipal(EveryonePrincipal.NAME);
  if (everyone == null) {
    everyone=EveryonePrincipal.getInstance();
  }
  return everyone;
}
 

Example 14

From project java-cas-client, under directory /cas-client-integration-atlassian/src/main/java/org/jasig/cas/client/integration/atlassian/.

Source file: ConfluenceCasAuthenticator.java

  32 
vote

public boolean logout(final HttpServletRequest request,final HttpServletResponse response) throws AuthenticatorException {
  final HttpSession session=request.getSession();
  final Principal principal=(Principal)session.getAttribute(LOGGED_IN_KEY);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Logging out [" + principal.getName() + "] from CAS.");
  }
  session.setAttribute(LOGGED_OUT_KEY,principal);
  session.setAttribute(LOGGED_IN_KEY,null);
  session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION,null);
  return true;
}
 

Example 15

From project jboss-as-quickstart, under directory /tasks-rs/src/main/java/org/jboss/as/quickstarts/tasksrs/service/.

Source file: TaskResource.java

  32 
vote

private User getUser(SecurityContext context){
  Principal principal=null;
  if (context != null)   principal=context.getUserPrincipal();
  if (principal == null)   throw new WebApplicationException(Response.Status.UNAUTHORIZED);
  return getUser(principal.getName());
}
 

Example 16

From project jboss-remoting, under directory /src/main/java/org/jboss/remoting3/security/.

Source file: SimpleUserInfo.java

  32 
vote

public SimpleUserInfo(Collection<Principal> remotingPrincipals){
  String userName=null;
  Iterator<Principal> principals=remotingPrincipals.iterator();
  while (userName == null && principals.hasNext()) {
    Principal next=principals.next();
    if (next instanceof UserPrincipal) {
      userName=((UserPrincipal)next).getName();
    }
  }
  this.userName=userName;
}
 

Example 17

From project jbossportletbridge, under directory /core/portletbridge-impl/src/main/java/org/jboss/portletbridge/context/.

Source file: PortletExternalContextImpl.java

  32 
vote

public String getRemoteUser(){
  String user=getPortletRequest().getRemoteUser();
  if (user == null) {
    Principal userPrincipal=getUserPrincipal();
    if (null != userPrincipal) {
      user=userPrincipal.getName();
    }
  }
  return user;
}
 

Example 18

From project jdonframework, under directory /JdonAccessory/src/com/jdon/security/ejb/.

Source file: LoginClientUtil.java

  32 
vote

private static CallbackHandler getJBossCallbackHandler(String username,String password){
  SecurityAssociationHandler pch=new SecurityAssociationHandler();
  Principal user=getJBossPrincipal(username);
  pch.setSecurityInfo(user,password.toCharArray());
  return pch;
}
 

Example 19

From project jetty-project, under directory /jetty-integration-tests/src/test/java/org/mortbay/jetty/integration/jaas/.

Source file: TestJAASUserRealm.java

  32 
vote

public void SKIPtestItPropertyFile() throws Exception {
  JAASLoginService loginService=new JAASLoginService("props");
  loginService.setLoginModuleName("props");
  LoginCallback loginCallback=new LoginCallbackImpl(new Subject(),"user","wrong".toCharArray());
  assertFalse(loginCallback.isSuccess());
  loginCallback=new LoginCallbackImpl(new Subject(),"user","user".toCharArray());
  assertTrue(loginCallback.isSuccess());
  Principal userPrincipal=loginCallback.getUserPrincipal();
  assertNotNull("principal expected",userPrincipal);
  assertEquals(userPrincipal.getName(),"user");
}
 

Example 20

From project jspwiki, under directory /src/org/apache/wiki/auth/acl/.

Source file: AclEntryImpl.java

  32 
vote

/** 
 * Returns a string representation of the contents of this ACL entry.
 * @return a string representation of the contents.
 */
public String toString(){
  StringBuffer sb=new StringBuffer();
  Principal p=getPrincipal();
  sb.append("[AclEntry ALLOW " + (p != null ? p.getName() : "null"));
  sb.append(" ");
  for (  Permission pp : m_permissions) {
    sb.append(pp.toString());
    sb.append(",");
  }
  sb.append("]");
  return sb.toString();
}
 

Example 21

From project amber, under directory /oauth-2.0/resourceserver-filter/src/main/java/org/apache/amber/oauth2/rsfilter/.

Source file: OAuthFilter.java

  31 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest req=(HttpServletRequest)request;
  HttpServletResponse res=(HttpServletResponse)response;
  try {
    OAuthAccessResourceRequest oauthRequest=new OAuthAccessResourceRequest(req,parameterStyles);
    String accessToken=oauthRequest.getAccessToken();
    final OAuthDecision decision=provider.validateRequest(realm,accessToken,req);
    final Principal principal=decision.getPrincipal();
    request=new HttpServletRequestWrapper((HttpServletRequest)request){
      @Override public String getRemoteUser(){
        return principal != null ? principal.getName() : null;
      }
      @Override public Principal getUserPrincipal(){
        return principal;
      }
    }
;
    request.setAttribute(OAuth.OAUTH_CLIENT_ID,decision.getOAuthClient().getClientId());
    chain.doFilter(request,response);
    return;
  }
 catch (  OAuthSystemException e1) {
    throw new ServletException(e1);
  }
catch (  OAuthProblemException e) {
    respondWithError(res,e);
    return;
  }
}
 

Example 22

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/.

Source file: DefaultUserTokenHandler.java

  31 
vote

public Object getUserToken(final HttpContext context){
  Principal userPrincipal=null;
  AuthState targetAuthState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  if (targetAuthState != null) {
    userPrincipal=getAuthPrincipal(targetAuthState);
    if (userPrincipal == null) {
      AuthState proxyAuthState=(AuthState)context.getAttribute(ClientContext.PROXY_AUTH_STATE);
      userPrincipal=getAuthPrincipal(proxyAuthState);
    }
  }
  if (userPrincipal == null) {
    HttpRoutedConnection conn=(HttpRoutedConnection)context.getAttribute(ExecutionContext.HTTP_CONNECTION);
    if (conn.isOpen()) {
      SSLSession sslsession=conn.getSSLSession();
      if (sslsession != null) {
        userPrincipal=sslsession.getLocalPrincipal();
      }
    }
  }
  return userPrincipal;
}
 

Example 23

From project arquillian-container-weld, under directory /weld-ee-embedded-1.1/src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockSecurityServices.java

  31 
vote

public Principal getPrincipal(){
  return new Principal(){
    public String getName(){
      return null;
    }
  }
;
}
 

Example 24

From project arquillian-weld-embedded-1.1, under directory /src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockSecurityServices.java

  31 
vote

public Principal getPrincipal(){
  return new Principal(){
    public String getName(){
      return null;
    }
  }
;
}
 

Example 25

From project arquillian_deprecated, under directory /containers/weld-ee-embedded-1.1/src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockSecurityServices.java

  31 
vote

public Principal getPrincipal(){
  return new Principal(){
    public String getName(){
      return null;
    }
  }
;
}
 

Example 26

From project cas, under directory /cas-server-support-spnego/src/main/java/org/jasig/cas/support/spnego/authentication/handler/support/.

Source file: JCIFSSpnegoAuthenticationHandler.java

  31 
vote

protected boolean doAuthentication(final Credentials credentials) throws AuthenticationException {
  final SpnegoCredentials spnegoCredentials=(SpnegoCredentials)credentials;
  Principal principal;
  byte[] nextToken;
  try {
synchronized (this) {
      this.authentication.reset();
      this.authentication.process(spnegoCredentials.getInitToken());
      principal=this.authentication.getPrincipal();
      nextToken=this.authentication.getNextToken();
    }
  }
 catch (  jcifs.spnego.AuthenticationException e) {
    throw new BadCredentialsAuthenticationException(e);
  }
  if (nextToken != null) {
    logger.debug("Setting nextToken in credentials");
    spnegoCredentials.setNextToken(nextToken);
  }
 else {
    logger.debug("nextToken is null");
  }
  if (principal != null) {
    if (spnegoCredentials.isNtlm()) {
      if (logger.isDebugEnabled()) {
        logger.debug("NTLM Credentials is valid for user [" + principal.getName() + "]");
      }
      spnegoCredentials.setPrincipal(getSimplePrincipal(principal.getName(),true));
      return this.isNTLMallowed;
    }
    if (logger.isDebugEnabled()) {
      logger.debug("Kerberos Credentials is valid for user [" + principal.getName() + "]");
    }
    spnegoCredentials.setPrincipal(getSimplePrincipal(principal.getName(),false));
    return true;
  }
  logger.debug("Principal is null, the processing of the SPNEGO Token failed");
  return false;
}
 

Example 27

From project cipango, under directory /cipango-console/src/main/java/org/cipango/console/.

Source file: VelocityConsoleServlet.java

  31 
vote

@Override protected void doRequest(HttpServletRequest request,HttpServletResponse response) throws IOException {
  JmxConnection connection=getConnection(request);
  if (!connection.isConnectionValid() && !_localConnection.isConnectionValid()) {
    response.sendError(503,"JMX is not enabled, unable to use cipango console. Please start Cipango with:\n" + "\tjava -jar start.jar --ini=start-cipango.ini --pre=etc/cipango-jmx.xml");
    return;
  }
  HttpSession session=request.getSession();
  Principal principal=request.getUserPrincipal();
  if (principal != null && !principal.equals(session.getAttribute(Principal.class.getName()))) {
    _logger.info("User " + principal.getName() + " has logged in console");
    session.setAttribute(Principal.class.getName(),principal);
  }
  String command=request.getServletPath();
  int index=command.lastIndexOf('/');
  if (index != -1)   command=command.substring(index + 1);
  Menu menu=getMenuFactory().getMenu(command,connection.getMbsc());
  request.setAttribute(Attributes.MENU,menu);
  Page currentPage=menu.getCurrentPage();
  if (currentPage != null && request.getAttribute(Attributes.FATAL) == null) {
    registerActions();
    Action action=getAction(currentPage,request);
    if (action != null) {
      action.process(request);
      if (action.isAjax(request)) {
        action.setAjaxContent(request,response);
      }
 else       response.sendRedirect(command);
      return;
    }
  }
  super.doRequest(request,response);
}
 

Example 28

From project components-ness-config, under directory /src/test/java/com/nesscomputing/config/util/.

Source file: LocalHttpService.java

  31 
vote

@Override public UserIdentity login(String username,Object credentials){
  if (StringUtils.equals(login,username) && StringUtils.equals(password,String.valueOf(credentials))) {
    final Credential c=new Password(String.valueOf(credentials));
    final Principal p=new KnownUser(username,c);
    final Subject subject=new Subject();
    subject.getPrincipals().add(p);
    subject.getPrivateCredentials().add(c);
    return new UserIdentity(){
      @Override public Subject getSubject(){
        return subject;
      }
      @Override public Principal getUserPrincipal(){
        return p;
      }
      @Override public boolean isUserInRole(      String role,      Scope scope){
        return true;
      }
    }
;
  }
 else {
    return null;
  }
}
 

Example 29

From project components-ness-httpclient, under directory /client/src/test/java/com/nesscomputing/httpclient/testsupport/.

Source file: LocalHttpService.java

  31 
vote

@Override public UserIdentity login(String username,Object credentials){
  if (StringUtils.equals(login,username) && StringUtils.equals(password,String.valueOf(credentials))) {
    final Credential c=new Password(String.valueOf(credentials));
    final Principal p=new KnownUser(username,c);
    final Subject subject=new Subject();
    subject.getPrincipals().add(p);
    subject.getPrivateCredentials().add(c);
    return new UserIdentity(){
      @Override public Subject getSubject(){
        return subject;
      }
      @Override public Principal getUserPrincipal(){
        return p;
      }
      @Override public boolean isUserInRole(      String role,      Scope scope){
        return true;
      }
    }
;
  }
 else {
    return null;
  }
}
 

Example 30

From project components-ness-httpserver_1, under directory /src/main/java/com/nesscomputing/httpserver/testing/.

Source file: LocalHttpService.java

  31 
vote

@Override public UserIdentity login(String username,Object credentials){
  if (StringUtils.equals(login,username) && StringUtils.equals(password,String.valueOf(credentials))) {
    final Credential c=new Password(String.valueOf(credentials));
    final Principal p=new KnownUser(username,c);
    final Subject subject=new Subject();
    subject.getPrincipals().add(p);
    subject.getPrivateCredentials().add(c);
    return new UserIdentity(){
      @Override public Subject getSubject(){
        return subject;
      }
      @Override public Principal getUserPrincipal(){
        return p;
      }
      @Override public boolean isUserInRole(      String role,      Scope scope){
        return true;
      }
    }
;
  }
 else {
    return null;
  }
}
 

Example 31

From project crash, under directory /shell/ssh/src/main/java/org/crsh/ssh/term/.

Source file: CRaSHCommand.java

  31 
vote

public void run(){
  try {
    final String userName=session.getAttribute(SSHLifeCycle.USERNAME);
    Principal user=new Principal(){
      public String getName(){
        return userName;
      }
    }
;
    factory.handler.handle(io,user);
  }
  finally {
    callback.onExit(0);
  }
}
 

Example 32

From project dci-examples, under directory /moneytransfer/java/ant-kutschera/OOPSOADCI_COMMON/src/ch/maxant/oopsoadci_common/bankingexample/ccc/.

Source file: SecurityDomainMock.java

  31 
vote

/** 
 * @return  the logged in user, or null, if they are not logged in
 */
public Principal getUser(){
  return new Principal(){
    public String getName(){
      return "maxant@maxant.co.uk";
    }
  }
;
}
 

Example 33

From project echo2, under directory /src/testapp/interactive/java/nextapp/echo2/testapp/auth/.

Source file: AuthApp.java

  31 
vote

/** 
 * @see nextapp.echo2.app.ApplicationInstance#init()
 */
public Window init(){
  if (InteractiveApp.LIVE_DEMO_SERVER) {
    throw new RuntimeException("Authentication test disabled on live demo server.");
  }
  Window mainWindow=new Window();
  mainWindow.setTitle("NextApp Echo2 Authentication Test Application");
  ContentPane content=new ContentPane();
  mainWindow.setContent(content);
  Column mainColumn=new Column();
  mainColumn.setBorder(new Border(new Extent(4),Color.BLUE,Border.STYLE_OUTSET));
  mainColumn.setInsets(new Insets(40));
  mainColumn.setCellSpacing(new Extent(20));
  content.add(mainColumn);
  ContainerContext containerContext=(ContainerContext)getContextProperty(ContainerContext.CONTEXT_PROPERTY_NAME);
  Principal principal=containerContext.getUserPrincipal();
  mainColumn.add(new Label("getUserPrincipal(): " + (principal == null ? "null" : principal.getName())));
  mainColumn.add(new Label("isUserInRole(\"role1\"): " + containerContext.isUserInRole("role1")));
  return mainWindow;
}
 

Example 34

From project flatpack-java, under directory /core/src/main/java/com/getperka/flatpack/ext/.

Source file: DeserializationContext.java

  31 
vote

/** 
 * Apply a principal-based security check for entities that were resolved from the backing store. This code will follow one or more property paths for the entity and resolve the object at the end of the path into one or more principals. The test passes if the current principal is in the list. Otherwise, a warning is added to the context.
 */
public boolean checkAccess(HasUuid object){
  if (!wasResolved(object)) {
    return true;
  }
  if (getRoles().isEmpty()) {
    return true;
  }
  Principal principal=getPrincipal();
  if (!principalMapper.isAccessEnforced(principal,object)) {
    return true;
  }
  List<PropertyPath> paths=typeContext.getPrincipalPaths(object.getClass());
  PropertyPathChecker checker=checkers.get();
  for (  PropertyPath path : paths) {
    path.evaluate(object,checker);
    if (checker.getResult()) {
      return true;
    }
  }
  addWarning(object,"User %s does not have permission to edit this %s",principal,typeContext.getPayloadName(object.getClass()));
  return false;
}
 

Example 35

From project hoop, under directory /hoop-server/src/main/java/com/cloudera/lib/servlet/.

Source file: MDCFilter.java

  31 
vote

/** 
 * Sets the slf4j <code>MDC</code> and delegates the request to the chain.
 * @param request servlet request.
 * @param response servlet response.
 * @param chain filter chain.
 * @throws IOException thrown if an IO error occurrs.
 * @throws ServletException thrown if a servet error occurrs.
 */
@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  try {
    MDC.clear();
    String hostname=HostnameFilter.get();
    if (hostname != null) {
      MDC.put("hostname",HostnameFilter.get());
    }
    Principal principal=((HttpServletRequest)request).getUserPrincipal();
    String user=(principal != null) ? principal.getName() : null;
    if (user != null) {
      MDC.put("user",user);
    }
    MDC.put("method",((HttpServletRequest)request).getMethod());
    MDC.put("path",((HttpServletRequest)request).getPathInfo());
    chain.doFilter(request,response);
  }
  finally {
    MDC.clear();
  }
}
 

Example 36

From project httpClient, under directory /httpclient/src/main/java/org/apache/http/impl/client/.

Source file: DefaultUserTokenHandler.java

  31 
vote

public Object getUserToken(final HttpContext context){
  Principal userPrincipal=null;
  AuthState targetAuthState=(AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
  if (targetAuthState != null) {
    userPrincipal=getAuthPrincipal(targetAuthState);
    if (userPrincipal == null) {
      AuthState proxyAuthState=(AuthState)context.getAttribute(ClientContext.PROXY_AUTH_STATE);
      userPrincipal=getAuthPrincipal(proxyAuthState);
    }
  }
  if (userPrincipal == null) {
    HttpConnection conn=(HttpConnection)context.getAttribute(ExecutionContext.HTTP_CONNECTION);
    if (conn instanceof HttpSSLConnection) {
      SSLSession sslsession=((HttpSSLConnection)conn).getSSLSession();
      if (sslsession != null) {
        userPrincipal=sslsession.getLocalPrincipal();
      }
    }
  }
  return userPrincipal;
}
 

Example 37

From project integration-tests, under directory /picketlink-sts-tests/src/test/java/org/picketlink/test/integration/sts/.

Source file: PicketLinkSTSIntegrationUnitTestCase.java

  31 
vote

/** 
 * <p> This test requests a SAMLV1.1 assertion on behalf of another identity. The STS must issue an assertion for the identity contained in the  {@code OnBehalfOf} section of the WS-Trust request (and not for the identity that sentthe request). </p>
 * @throws Exception if an error occurs while running the test.
 */
@Test public void testIssueSAML11OnBehalfOf() throws Exception {
  Element assertionElement=client.issueTokenOnBehalfOf(null,SAMLUtil.SAML11_TOKEN_TYPE,new Principal(){
    @Override public String getName(){
      return "jduke";
    }
  }
);
  Assert.assertNotNull("Invalid null assertion element",assertionElement);
  SAML11AssertionType assertion=this.validateSAML11Assertion(assertionElement,"jduke",SAMLUtil.SAML11_SENDER_VOUCHES_URI);
  SAML11ConditionsType conditions=assertion.getConditions();
  Assert.assertEquals("Unexpected restriction list size",0,conditions.get().size());
}
 

Example 38

From project ipdburt, under directory /iddb-web/src/main/java/jipdbs/web/processors/.

Source file: ContactProcessor.java

  31 
vote

@Override public String doProcess(ResolverContext context) throws ProcessorException {
  if (context.isPost()) {
    HttpServletRequest req=context.getRequest();
    String mail=req.getParameter("m");
    String text=req.getParameter("text");
    if (StringUtils.isEmpty(mail) || StringUtils.isEmpty(text)) {
      Flash.error(req,MessageResource.getMessage("fields_required"));
      return null;
    }
    if (!Validator.isValidEmail(mail)) {
      Flash.error(req,MessageResource.getMessage("invalid_email"));
      return null;
    }
    IDDBService app=(IDDBService)context.getServletContext().getAttribute("jipdbs");
    if (!app.isRecaptchaValid(req.getRemoteAddr(),req.getParameter("recaptcha_challenge_field"),req.getParameter("recaptcha_response_field"))) {
      Flash.error(req,MessageResource.getMessage("invalid_captcha"));
      return null;
    }
    Principal user=req.getUserPrincipal();
    app.sendAdminMail(user != null ? user.getName() : null,mail,text);
    Flash.ok(req,MessageResource.getMessage("mail_sent"));
  }
  return null;
}
 

Example 39

From project iserve, under directory /iserve-parent/iserve-sal-rest/src/main/java/uk/ac/open/kmi/iserve/sal/rest/auth/.

Source file: SecurityFilter.java

  31 
vote

public Authorizer(final User user){
  this.principal=new Principal(){
    public String getName(){
      return user.getFoafId().toString();
    }
  }
;
}
 

Example 40

From project jbpm-plugin, under directory /jbpm/src/main/java/hudson/jbpm/.

Source file: JbpmContextFilter.java

  31 
vote

public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
  String actorId=null;
  if (servletRequest instanceof HttpServletRequest) {
    HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
    Principal userPrincipal=httpServletRequest.getUserPrincipal();
    if (userPrincipal != null) {
      actorId=userPrincipal.getName();
    }
  }
  if (actorId == null) {
    Authentication auth=Hudson.getAuthentication();
    if (auth != null) {
      actorId=auth.getName();
    }
  }
  JbpmContext jbpmContext=getJbpmConfiguration().createJbpmContext(jbpmContextName);
  try {
    if (isAuthenticationEnabled) {
      jbpmContext.setActorId(actorId);
    }
    filterChain.doFilter(servletRequest,servletResponse);
  }
  finally {
    jbpmContext.close();
  }
}
 

Example 41

From project jsecurity, under directory /web/src/main/java/org/apache/ki/web/servlet/.

Source file: KiHttpServletRequest.java

  31 
vote

public Principal getUserPrincipal(){
  Principal userPrincipal;
  Object scPrincipal=getSubjectPrincipal();
  if (scPrincipal != null) {
    if (scPrincipal instanceof Principal) {
      userPrincipal=(Principal)scPrincipal;
    }
 else {
      userPrincipal=new ObjectPrincipal(scPrincipal);
    }
  }
 else {
    userPrincipal=super.getUserPrincipal();
  }
  return userPrincipal;
}
 

Example 42

From project jsf-test, under directory /mock/src/main/java/org/jboss/test/faces/stub/servlet/.

Source file: StubHttpServletRequest.java

  31 
vote

public Principal getUserPrincipal(){
  return principalName == null ? null : new Principal(){
    public String getName(){
      return principalName;
    }
  }
;
}
 

Example 43

From project alfredo, under directory /alfredo/src/main/java/com/cloudera/alfredo/server/.

Source file: KerberosAuthenticationHandler.java

  29 
vote

/** 
 * Initializes the authentication handler instance. <p/> It creates a Kerberos context using the principal and keytab specified in the configuration. <p/> This method is invoked by the  {@link AuthenticationFilter#init} method.
 * @param config configuration properties to initialize the handler.
 * @throws ServletException thrown if the handler could not be initialized.
 */
@Override public void init(Properties config) throws ServletException {
  try {
    principal=config.getProperty(PRINCIPAL,principal);
    if (principal == null || principal.trim().length() == 0) {
      throw new ServletException("Principal not defined in configuration");
    }
    keytab=config.getProperty(KEYTAB,keytab);
    if (keytab == null || keytab.trim().length() == 0) {
      throw new ServletException("Keytab not defined in configuration");
    }
    if (!new File(keytab).exists()) {
      throw new ServletException("Keytab does not exist: " + keytab);
    }
    Set<Principal> principals=new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));
    Subject subject=new Subject(false,principals,new HashSet<Object>(),new HashSet<Object>());
    KerberosConfiguration kerberosConfiguration=new KerberosConfiguration(keytab,principal);
    loginContext=new LoginContext("",subject,null,kerberosConfiguration);
    loginContext.login();
    Subject serverSubject=loginContext.getSubject();
    try {
      gssManager=Subject.doAs(serverSubject,new PrivilegedExceptionAction<GSSManager>(){
        @Override public GSSManager run() throws Exception {
          return GSSManager.getInstance();
        }
      }
);
    }
 catch (    PrivilegedActionException ex) {
      throw ex.getException();
    }
    LOG.info("Initialized, principal [{}] from keytab [{}]",principal,keytab);
  }
 catch (  Exception ex) {
    throw new ServletException(ex);
  }
}
 

Example 44

From project android-client_1, under directory /src/org/apache/harmony/javax/security/auth/.

Source file: PrivateCredentialPermission.java

  29 
vote

/** 
 * Creates a  {@code PrivateCredentialPermission} from the {@code Credential}class and set of principals.
 * @param credentialClass the credential class name.
 * @param principals the set of principals.
 */
PrivateCredentialPermission(String credentialClass,Set<Principal> principals){
  super(credentialClass);
  this.credentialClass=credentialClass;
  set=new CredOwner[principals.size()];
  for (  Principal p : principals) {
    CredOwner element=new CredOwner(p.getClass().getName(),p.getName());
    boolean found=false;
    for (int ii=0; ii < offset; ii++) {
      if (set[ii].equals(element)) {
        found=true;
        break;
      }
    }
    if (!found) {
      set[offset++]=element;
    }
  }
}
 

Example 45

From project AsmackService, under directory /src/org/apache/harmony/javax/security/auth/.

Source file: PrivateCredentialPermission.java

  29 
vote

/** 
 * Creates a  {@code PrivateCredentialPermission} from the {@code Credential}class and set of principals.
 * @param credentialClass the credential class name.
 * @param principals the set of principals.
 */
PrivateCredentialPermission(String credentialClass,Set<Principal> principals){
  super(credentialClass);
  this.credentialClass=credentialClass;
  set=new CredOwner[principals.size()];
  for (  Principal p : principals) {
    CredOwner element=new CredOwner(p.getClass().getName(),p.getName());
    boolean found=false;
    for (int ii=0; ii < offset; ii++) {
      if (set[ii].equals(element)) {
        found=true;
        break;
      }
    }
    if (!found) {
      set[offset++]=element;
    }
  }
}
 

Example 46

From project chililog-server, under directory /src/main/java/org/chililog/server/engine/.

Source file: JAASLoginModule.java

  29 
vote

/** 
 * <p> We check the credentials against the repository. By convention, the username is the repository name and the password is either the publisher or subscriber password. The role assigned to the user is constructed from the combination of username and publisher password. </p>
 * @return Returns true if this method succeeded, or false if this LoginModule should be ignored.
 */
public boolean login() throws LoginException {
  try {
    Iterator<Principal> iterator=_subject.getPrincipals().iterator();
    String username=iterator.next().getName();
    if (StringUtils.isBlank(username)) {
      throw new FailedLoginException("Username is requried.");
    }
    Iterator<char[]> iterator2=_subject.getPrivateCredentials(char[].class).iterator();
    char[] passwordChars=iterator2.next();
    String password=new String(passwordChars);
    if (StringUtils.isBlank(password)) {
      throw new FailedLoginException("Password is requried.");
    }
    if (username.equals(_systemUsername) && password.equals(_systemPassword)) {
      Group roles=new SimpleGroup("Roles");
      roles.addMember(new SimplePrincipal(UserBO.SYSTEM_ADMINISTRATOR_ROLE_NAME));
      _subject.getPrincipals().add(roles);
      return true;
    }
    DB db=MongoConnection.getInstance().getConnection();
    UserBO user=UserController.getInstance().tryGetByUsername(db,username);
    if (user == null) {
      throw new FailedLoginException("Invalid username or password.");
    }
    if (StringUtils.isBlank(password) || !user.validatePassword(password)) {
      throw new FailedLoginException("Invalid username or password.");
    }
    Group roles=new SimpleGroup("Roles");
    for (    String role : user.getRoles()) {
      roles.addMember(new SimplePrincipal(role));
    }
    _subject.getPrincipals().add(roles);
    return true;
  }
 catch (  Exception ex) {
    throw new LoginException(ex.getMessage());
  }
}
 

Example 47

From project doorkeeper, under directory /core/src/main/java/net/dataforte/doorkeeper/filter/.

Source file: AuthenticatorRequestWrapper.java

  29 
vote

public Principal getUserPrincipal(){
  if (user != null) {
    return user;
  }
 else {
    return prePrincipal;
  }
}
 

Example 48

From project echo3, under directory /src/server-java/webcontainer/nextapp/echo/webcontainer/.

Source file: ContainerContextImpl.java

  29 
vote

/** 
 * @see nextapp.echo.webcontainer.ContainerContext#getUserPrincipal()
 */
public Principal getUserPrincipal(){
  Connection conn=WebContainerServlet.getActiveConnection();
  if (conn == null) {
    return null;
  }
 else {
    return conn.getRequest().getUserPrincipal();
  }
}
 

Example 49

From project Fotolia-API, under directory /java/libs/httpcomponents-client-4.1.2/examples/org/apache/http/examples/client/.

Source file: ClientKerberosAuthentication.java

  29 
vote

public static void main(String[] args) throws Exception {
  System.setProperty("java.security.auth.login.config","login.conf");
  System.setProperty("java.security.krb5.conf","krb5.conf");
  System.setProperty("sun.security.krb5.debug","true");
  System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    NegotiateSchemeFactory nsf=new NegotiateSchemeFactory();
    httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO,nsf);
    Credentials use_jaas_creds=new Credentials(){
      public String getPassword(){
        return null;
      }
      public Principal getUserPrincipal(){
        return null;
      }
    }
;
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null,-1,null),use_jaas_creds);
    HttpUriRequest request=new HttpGet("http://kerberoshost/");
    HttpResponse response=httpclient.execute(request);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    System.out.println("----------------------------------------");
    if (entity != null) {
      System.out.println(EntityUtils.toString(entity));
    }
    System.out.println("----------------------------------------");
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 50

From project fuzzydb-samples, under directory /sample-webapp/src/main/java/org/fuzzydb/samples/mvc/.

Source file: HomeController.java

  29 
vote

/** 
 * Simple scenario for updating one composite object
 */
@Transactional @RequestMapping(value=HOME_PAGE,method=RequestMethod.GET) public String home(Principal currentUser,Model model){
  model.addAttribute("connectionsToProviders",getConnectionRepository().findAllConnections());
  if (currentUser != null) {
    model.addAttribute("account",accountRepository.findOne(currentUser.getName()));
  }
  logger.info("Welcome home!");
  MyCounter counter=counterRepo.findOne(HOME_PAGE);
  if (counter == null) {
    counter=new MyCounter(HOME_PAGE);
  }
  counter.count++;
  counterRepo.save(counter);
  model.addAttribute("count",counter.count);
  return "home";
}
 

Example 51

From project ihatovgram, under directory /src/client/android/ihatovgram/lib/httpcomponents-client-4.1.3/examples/org/apache/http/examples/client/.

Source file: ClientKerberosAuthentication.java

  29 
vote

public static void main(String[] args) throws Exception {
  System.setProperty("java.security.auth.login.config","login.conf");
  System.setProperty("java.security.krb5.conf","krb5.conf");
  System.setProperty("sun.security.krb5.debug","true");
  System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    NegotiateSchemeFactory nsf=new NegotiateSchemeFactory();
    httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO,nsf);
    Credentials use_jaas_creds=new Credentials(){
      public String getPassword(){
        return null;
      }
      public Principal getUserPrincipal(){
        return null;
      }
    }
;
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null,-1,null),use_jaas_creds);
    HttpUriRequest request=new HttpGet("http://kerberoshost/");
    HttpResponse response=httpclient.execute(request);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    System.out.println("----------------------------------------");
    if (entity != null) {
      System.out.println(EntityUtils.toString(entity));
    }
    System.out.println("----------------------------------------");
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 52

From project jboss-remote-naming, under directory /src/test/java/org/jboss/naming/remote/.

Source file: TestUtils.java

  29 
vote

@Override public AuthorizingCallbackHandler getCallbackHandler(String mechanismName){
  if (mechanismName.equals(ANONYMOUS)) {
    return new AuthorizingCallbackHandler(){
      public void handle(      Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        for (        Callback current : callbacks) {
          throw new UnsupportedCallbackException(current,"ANONYMOUS mechanism so not expecting a callback");
        }
      }
      @Override public UserInfo createUserInfo(      Collection<Principal> remotingPrincipals) throws IOException {
        if (remotingPrincipals == null) {
          return null;
        }
        return new SimpleUserInfo(remotingPrincipals);
      }
    }
;
  }
  return null;
}
 

Example 53

From project JGlobus, under directory /ssl-proxies/src/main/java/org/globus/gsi/gssapi/jaas/.

Source file: SimplePrincipal.java

  29 
vote

public boolean equals(Object another){
  if (!(another instanceof Principal)) {
    return false;
  }
  String anotherName=((Principal)another).getName();
  if (this.name == null) {
    return (this.name == anotherName);
  }
 else {
    return this.name.equals(anotherName);
  }
}