public void setUp() throws Exception {
   IUnifiedRepository repository =
       new MockUnifiedRepository(new MockUnifiedRepository.SpringSecurityCurrentUserProvider());
   datasourceMgmtService =
       new JcrBackedDatasourceMgmtService(repository, new DatabaseDialectService());
   datasourceMgmtWebService = new DefaultDatasourceMgmtWebService(datasourceMgmtService);
   dbConnectionAdapter = new DatabaseConnectionAdapter();
   SecurityContextHolder.getContext()
       .setAuthentication(
           new UsernamePasswordAuthenticationToken(
               MockUnifiedRepository.root().getName(), null, new GrantedAuthority[0]));
   repository.createFolder(
       repository.getFile("/etc").getId(),
       new RepositoryFile.Builder(FOLDER_PDI).folder(true).build(),
       new RepositoryFileAcl.Builder(MockUnifiedRepository.root())
           .ace(MockUnifiedRepository.everyone(), READ, READ_ACL, WRITE, WRITE_ACL)
           .build(),
       null);
   repository.createFolder(
       repository.getFile("/etc/pdi").getId(),
       new RepositoryFile.Builder(FOLDER_DATABASES).folder(true).build(),
       null);
   SecurityContextHolder.getContext()
       .setAuthentication(
           new UsernamePasswordAuthenticationToken(EXP_LOGIN, null, new GrantedAuthority[0]));
 }
コード例 #2
0
  public Principal login(Object credentials, String charset) {
    List<String> decodedCredentials = Arrays.asList(decodeBase64Credentials(credentials, charset));

    HttpGraniteContext context = (HttpGraniteContext) GraniteContext.getCurrentInstance();
    HttpServletRequest httpRequest = context.getRequest();

    String user = decodedCredentials.get(0);
    String password = decodedCredentials.get(1);
    Authentication auth = new UsernamePasswordAuthenticationToken(user, password);
    Principal principal = null;

    ApplicationContext ctx =
        WebApplicationContextUtils.getWebApplicationContext(
            httpRequest.getSession().getServletContext());
    if (ctx != null) {
      AbstractAuthenticationManager authenticationManager =
          BeanFactoryUtils.beanOfTypeIncludingAncestors(ctx, AbstractAuthenticationManager.class);
      try {
        Authentication authentication = authenticationManager.authenticate(auth);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
        principal = authentication;
        SecurityContextHolder.setContext(securityContext);
        saveSecurityContextInSession(securityContext, 0);

        endLogin(credentials, charset);
      } catch (AuthenticationException e) {
        handleAuthenticationExceptions(e);
      }
    }

    log.debug("User %s logged in", user);

    return principal;
  }
コード例 #3
0
  /**
   * Logs in with given username.
   *
   * @param username username of user
   * @param tenantId tenant to which this user belongs
   * @tenantAdmin true to add the tenant admin authority to the user's roles
   */
  protected void login(final String username, final ITenant tenant, String[] roles) {
    StandaloneSession pentahoSession =
        new StandaloneSession(tenantedUserNameUtils.getPrincipleId(tenant, username));
    pentahoSession.setAuthenticated(
        tenant.getId(), tenantedUserNameUtils.getPrincipleId(tenant, username));
    PentahoSessionHolder.setSession(pentahoSession);
    pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, tenant.getId());
    final String password = "******";

    List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();

    for (String roleName : roles) {
      authList.add(
          new GrantedAuthorityImpl(tenantedRoleNameUtils.getPrincipleId(tenant, roleName)));
    }
    GrantedAuthority[] authorities = authList.toArray(new GrantedAuthority[0]);
    UserDetails userDetails = new User(username, password, true, true, true, true, authorities);
    Authentication auth =
        new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
    PentahoSessionHolder.setSession(pentahoSession);
    // this line necessary for Spring Security's MethodSecurityInterceptor
    SecurityContextHolder.getContext().setAuthentication(auth);
    SecurityHelper.getInstance().becomeUser(tenantedUserNameUtils.getPrincipleId(tenant, username));
    SecurityContextHolder.getContext().setAuthentication(auth);
  }
 private void setCurrentUser(String username) {
   originalSecurityContext = SecurityContextHolder.getContext();
   SecurityContextImpl context = new SecurityContextImpl();
   context.setAuthentication(
       new UsernamePasswordAuthenticationToken(
           new User(username, "", true, new GrantedAuthority[] {}), null));
   SecurityContextHolder.setContext(context);
 }
コード例 #5
0
  public Object authorize(AbstractSecurityContext context) throws Exception {
    log.debug("Authorize: %s", context);
    log.debug(
        "Is %s secured? %b",
        context.getDestination().getId(), context.getDestination().isSecured());

    startAuthorization(context);

    HttpGraniteContext graniteContext = (HttpGraniteContext) GraniteContext.getCurrentInstance();

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    SecurityContext securityContextBefore = null;
    int securityContextHashBefore = 0;
    if (graniteContext.getRequest().getAttribute(FILTER_APPLIED) == null) {
      securityContextBefore = loadSecurityContextFromSession();
      if (securityContextBefore == null) securityContextBefore = SecurityContextHolder.getContext();
      else securityContextHashBefore = securityContextBefore.hashCode();
      SecurityContextHolder.setContext(securityContextBefore);
      authentication = securityContextBefore.getAuthentication();
    }

    if (context.getDestination().isSecured()) {
      if (!isAuthenticated(authentication)
          || authentication instanceof AnonymousAuthenticationToken) {
        log.debug("Is not authenticated!");
        throw SecurityServiceException.newNotLoggedInException("User not logged in");
      }
      if (!userCanAccessService(context, authentication)) {
        log.debug("Access denied for: %s", authentication.getName());
        throw SecurityServiceException.newAccessDeniedException("User not in required role");
      }
    }

    try {
      Object returnedObject =
          securityInterceptor != null
              ? securityInterceptor.invoke(context)
              : endAuthorization(context);

      return returnedObject;
    } catch (AccessDeniedException e) {
      throw SecurityServiceException.newAccessDeniedException(e.getMessage());
    } catch (InvocationTargetException e) {
      handleAuthorizationExceptions(e);
      throw e;
    } finally {
      if (graniteContext.getRequest().getAttribute(FILTER_APPLIED) == null) {
        // Do this only when not already filtered by Spring Security
        SecurityContext securityContextAfter = SecurityContextHolder.getContext();
        SecurityContextHolder.clearContext();
        saveSecurityContextInSession(securityContextAfter, securityContextHashBefore);
      }
    }
  }
 @BeforeClass
 public static void beforeClass() throws Exception {
   System.setProperty(SYSTEM_PROPERTY, "MODE_GLOBAL");
   PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL);
   FileUtils.deleteDirectory(new File("/tmp/jackrabbit-test-TRUNK"));
   SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
 }
コード例 #7
0
  @Before
  public void setUp() throws Exception {

    manager = new MockBackingRepositoryLifecycleManager(new MockSecurityHelper());
    repo = context.mock(IUnifiedRepository.class);

    booter = new MicroPlatform("test-res/solution1");
    booter.define(IPasswordService.class, Base64PasswordService.class, Scope.GLOBAL);
    booter.define(IDatabaseConnection.class, DatabaseConnection.class, Scope.GLOBAL);
    booter.define(IDatabaseDialectService.class, DatabaseDialectService.class, Scope.GLOBAL);
    booter.define(IMondrianCatalogService.class, MondrianCatalogHelper.class, Scope.GLOBAL);
    booter.define(ICacheManager.class, CacheManager.class, Scope.GLOBAL);
    booter.defineInstance(IUserRoleListService.class, context.mock(IUserRoleListService.class));
    final IAuthorizationPolicy policy = context.mock(IAuthorizationPolicy.class);
    booter.defineInstance(IAuthorizationPolicy.class, policy);
    booter.defineInstance(IUnifiedRepository.class, repo);
    booter.setSettingsProvider(new SystemSettings());
    booter.start();

    context.checking(
        new Expectations() {
          {
            oneOf(policy);
            will(returnValue(false));
            oneOf(policy);
            will(returnValue(false));
            oneOf(policy);
            will(returnValue(false));
          }
        });

    PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL);
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
  }
コード例 #8
0
  protected void login(final String username, final String tenantId, final boolean tenantAdmin) {
    StandaloneSession pentahoSession = new StandaloneSession(username);
    pentahoSession.setAuthenticated(username);
    pentahoSession.setAttribute(IPentahoSession.TENANT_ID_KEY, tenantId);
    final String password = "******";

    List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
    authList.add(
        new GrantedAuthorityImpl(
            MessageFormat.format(tenantAuthenticatedAuthorityNamePattern, tenantId)));
    if (tenantAdmin) {
      authList.add(
          new GrantedAuthorityImpl(
              MessageFormat.format(tenantAdminAuthorityNamePattern, tenantId)));
    }
    GrantedAuthority[] authorities = authList.toArray(new GrantedAuthority[0]);
    UserDetails userDetails = new User(username, password, true, true, true, true, authorities);
    Authentication auth =
        new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
    PentahoSessionHolder.setSession(pentahoSession);
    // this line necessary for Spring Security's MethodSecurityInterceptor
    SecurityContextHolder.getContext().setAuthentication(auth);

    manager.newTenant();
    manager.newUser();
  }
コード例 #9
0
  protected void onSetUpInTransaction() throws Exception {
    super.onSetUpInTransaction();

    servletConfig = new MockServletConfig(new MockServletContext(), "simple");
    MockServletConfig complexConfig =
        new MockServletConfig(servletConfig.getServletContext(), "complex");
    complexConfig.addInitParameter("publishContext", "false");
    complexConfig.addInitParameter("class", "notWritable");
    complexConfig.addInitParameter("unknownParam", "someValue");

    simpleDispatcherServlet = new DispatcherServlet();
    simpleDispatcherServlet.setContextClass(SimpleWebApplicationContext.class);
    simpleDispatcherServlet.init(servletConfig);

    complexDispatcherServlet = new DispatcherServlet();
    complexDispatcherServlet.setContextClass(WebApplicationContext.class);
    complexDispatcherServlet.setNamespace("test");

    Constants constants = (Constants) applicationContext.getBean("constants");
    Authentication auth = constants.getAuthentication(applicationContext);
    SecurityContextHolder.getContext().setAuthentication(auth);

    parent = (Controller) applicationContext.getBean("workCodeController");
    child = (Controller) applicationContext.getBean("workCodeFormController");
    sf = (SessionFactory) applicationContext.getBean("sessionFactory");
  }
コード例 #10
0
 protected boolean isLoggedIn() {
   final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
   if (authentication == null || authentication.getPrincipal() == null) {
     return false;
   }
   return true;
 }
コード例 #11
0
  /** {@inheritDoc} */
  @Override
  protected void doFilterHttp(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    boolean shouldFilter = AclUtils.shouldFilter();

    try {
      if (shouldFilter) {
        String user = SecurityContextHolder.getContext().getAuthentication().getName();

        List<Group> groups = m_groupDao.findGroupsForUser(user);

        String[] groupNames = new String[groups.size()];
        for (int i = 0; i < groups.size(); i++) {
          groupNames[i] = groups.get(i).getName();
        }

        m_filterManager.enableAuthorizationFilter(groupNames);
      }

      chain.doFilter(request, response);

    } finally {
      if (shouldFilter) {
        m_filterManager.disableAuthorizationFilter();
      }
    }
  }
コード例 #12
0
  public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException {
    // TODO Auto-generated method stub
    FilterInvocation filterInvocation = (FilterInvocation) filter;
    String requestURI = filterInvocation.getRequestUrl();
    Map<String, Set<String>> urlAuthorities = this.getUrlAuthorities(filterInvocation);

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    boolean isSuperUser = false;
    if (auth != null) {
      for (int i = 0; i < auth.getAuthorities().length; i++) {
        if ("超级管理员".equals(auth.getAuthorities()[i].getAuthority())) {
          isSuperUser = true;
          break;
        }
      }
      if ((!isSuperUser) && (!isUrlGrantedRight(requestURI, auth))) {
        return null;
      } else {
        String grantedAuthorities = null;
        grantedAuthorities = getAuth(requestURI, auth);

        if (grantedAuthorities != null) {
          ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor();
          configAttrEditor.setAsText(grantedAuthorities);
          return (ConfigAttributeDefinition) configAttrEditor.getValue();
        }
      }
    }

    return null;
  }
 @After
 public void teardown() throws Exception {
   if (originalSecurityContext != null) {
     SecurityContextHolder.setContext(originalSecurityContext);
   }
   configHelper.onTearDown();
 }
コード例 #14
0
 @Before
 public void setUp() {
   String[] configFiles = new String[] {"springTestFilterBeans.xml"};
   this.ctx = new ClassPathXmlApplicationContext(configFiles);
   SecurityContextHolder.getContext().setAuthentication(null);
   this.filter = (NegotiateSecurityFilter) this.ctx.getBean("waffleNegotiateSecurityFilter");
 }
コード例 #15
0
  public void logout() {
    HttpGraniteContext context = (HttpGraniteContext) GraniteContext.getCurrentInstance();
    HttpSession session = context.getSession(false);
    if (session != null
        && session.getAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY)
            != null) session.invalidate();

    SecurityContextHolder.clearContext();
  }
コード例 #16
0
ファイル: MachineServiceTest.java プロジェクト: grkvlt/abiquo
  @BeforeMethod
  public void setupSysadmin() {
    Enterprise e = enterpriseGenerator.createUniqueInstance();
    Role r = roleGenerator.createInstance();
    User u = userGenerator.createInstance(e, r, "sysadmin", "sysadmin");
    setup(e, r, u);

    SecurityContextHolder.getContext().setAuthentication(new SysadminAuthentication());
  }
コード例 #17
0
 protected boolean isAdmin() {
   final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
   if (authentication == null || authentication.getPrincipal() == null) {
     return false;
   }
   if (hasAdminRole(authentication.getAuthorities())) {
     return true;
   }
   return false;
 }
コード例 #18
0
 protected User getLoggedInUser() {
   Authentication auth = SecurityContextHolder.getContext().getAuthentication();
   if (auth == null) {
     return null;
   }
   Object obj = auth.getPrincipal();
   if (obj instanceof UserDetails) {
     return (User) obj;
   }
   return null;
 }
コード例 #19
0
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    // store initial security context for later restoration
    initialSecurityContext = SecurityContextHolder.getContext();

    SecurityContext context = new SecurityContextImpl();
    User user = new User("user");
    user.setId(1L);
    user.setPassword("password");
    user.addRole(new Role(Constants.USER_ROLE));

    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getPassword(), user.getAuthorities());
    token.setDetails(user);
    context.setAuthentication(token);
    SecurityContextHolder.setContext(context);
  }
コード例 #20
0
  public User getUser() {
    // 取得登录用户
    SecurityContext ctx = SecurityContextHolder.getContext();
    Authentication auth = ctx.getAuthentication();
    User user = null;
    if (auth.getPrincipal() instanceof UserDetails) {
      user = (User) auth.getPrincipal();
    }

    return user;
  }
コード例 #21
0
  /**
   * After returning, grab the user, check if they've been modified and reset the SecurityContext if
   * they have.
   *
   * @param returnValue the user object
   * @param method the name of the method executed
   * @param args the arguments to the method
   * @param target the target class
   * @throws Throwable thrown when args[0] is null or not a User object
   */
  public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
      throws Throwable {
    User user = (User) args[0];

    if (user.getVersion() != null) {
      // reset the authentication object if current user
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
      // allow new users to signup - this is OK b/c Signup doesn't allow setting of roles
      boolean signupUser = resolver.isAnonymous(auth);
      if (auth != null && !signupUser) {
        User currentUser = getCurrentUser(auth);
        if (currentUser.getId().equals(user.getId())) {
          auth =
              new UsernamePasswordAuthenticationToken(
                  user, user.getPassword(), user.getAuthorities());
          SecurityContextHolder.getContext().setAuthentication(auth);
        }
      }
    }
  }
コード例 #22
0
 /**
  * Returns the connected user details.
  *
  * @return
  */
 public static Account getLoginAccount() {
   SecurityContext context = SecurityContextHolder.getContext();
   Authentication authen = context.getAuthentication();
   Object principal = null;
   if (authen != null) {
     principal = authen.getPrincipal();
   }
   if (principal != null && principal instanceof Account) {
     return (Account) principal;
   } else {
     return null;
   }
 } // - getLoginAccount
 protected void loginAsRepositoryAdmin() {
   StandaloneSession pentahoSession = new StandaloneSession(repositoryAdminUsername);
   pentahoSession.setAuthenticated(repositoryAdminUsername);
   final GrantedAuthority[] repositoryAdminAuthorities = new GrantedAuthority[] {};
   final String password = "******";
   UserDetails repositoryAdminUserDetails =
       new User(
           repositoryAdminUsername, password, true, true, true, true, repositoryAdminAuthorities);
   Authentication repositoryAdminAuthentication =
       new UsernamePasswordAuthenticationToken(
           repositoryAdminUserDetails, password, repositoryAdminAuthorities);
   PentahoSessionHolder.setSession(pentahoSession);
   // this line necessary for Spring Security's MethodSecurityInterceptor
   SecurityContextHolder.getContext().setAuthentication(repositoryAdminAuthentication);
 }
コード例 #24
0
  @BeforeClass
  public static void beforeClass() throws Exception {
    //    BasicConfigurator.configure();
    System.setProperty(SYSTEM_PROPERTY, "MODE_GLOBAL");
    Logger.getLogger("org").setLevel(Level.WARN);
    Logger.getLogger("org.pentaho").setLevel(Level.WARN);
    Logger.getLogger(RepositoryResource.class).setLevel(Level.DEBUG);
    //    Logger.getLogger(RequestProxy.class).setLevel(Level.DEBUG);
    Logger.getLogger("MIME_TYPE").setLevel(Level.TRACE);

    PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL);

    FileUtils.deleteDirectory(new File("/tmp/jackrabbit-test-TRUNK"));
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
  }
コード例 #25
0
  @Test
  public void testGuestIsDisabled() throws IOException, ServletException {
    String securityPackage = "Negotiate";
    SimpleFilterChain filterChain = new SimpleFilterChain();
    SimpleHttpRequest request = new SimpleHttpRequest();

    String clientToken = BaseEncoding.base64().encode("Guest".getBytes());
    request.addHeader("Authorization", securityPackage + " " + clientToken);

    SimpleHttpResponse response = new SimpleHttpResponse();
    this.filter.doFilter(request, response, filterChain);

    assertEquals(401, response.getStatus());
    assertNull(SecurityContextHolder.getContext().getAuthentication());
  }
コード例 #26
0
  public void testAddUserWithoutAdminRole() throws Exception {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    assertTrue(auth.isAuthenticated());
    UserManager userManager = makeInterceptedTarget();
    User user = new User("admin");
    user.setId(2L);

    try {
      userManager.saveUser(user);
      fail("AccessDeniedException not thrown");
    } catch (AccessDeniedException expected) {
      assertNotNull(expected);
      assertEquals(expected.getMessage(), UserSecurityAdvice.ACCESS_DENIED);
    }
  }
コード例 #27
0
  /**
   * {@inheritDoc}
   *
   * <p>Creates a {@code UsernamePasswordAuthenticationToken} from the given {@code principal} and
   * {@code credentials} and passes to Spring Security {@code AuthenticationManager}.
   */
  @Override
  protected Authentication getAuthentication(
      final Principal principal, final Credentials credentials) throws RepositoryException {

    // only handles SimpleCredential instances; DefaultLoginModule behaves the same way (albeit
    // indirectly)
    if (!(credentials instanceof SimpleCredentials)) {
      logger.debug("credentials not instance of SimpleCredentials; returning null"); // $NON-NLS-1$
      return null;
    }

    SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;

    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            simpleCredentials.getUserID(), String.valueOf(simpleCredentials.getPassword()));

    boolean authenticated = false;

    try {
      org.springframework.security.Authentication authentication =
          SecurityContextHolder.getContext().getAuthentication();
      if (authentication != null
          && authentication.getName().equals(simpleCredentials.getUserID())) {
        // see if there's already an active Authentication for this user.
        authenticated = true;
      } else {
        // delegate to Spring Security
        getAuthenticationManager().authenticate(token);
        authenticated = true;
      }
    } catch (AuthenticationException e) {
      logger.debug("authentication exception", e); // $NON-NLS-1$
    }

    final boolean authenticateResult = authenticated;

    return new Authentication() {
      public boolean canHandle(Credentials credentials) {
        // this is decided earlier in getAuthentication
        return true;
      }

      public boolean authenticate(Credentials credentials) throws RepositoryException {
        return authenticateResult;
      }
    };
  }
コード例 #28
0
  /**
   * Save the user, encrypting their passwords if necessary
   *
   * @return success when good things happen
   * @throws Exception when bad things happen
   */
  public String save() throws Exception {
    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    try {
      userManager.saveUser(user);
    } catch (AccessDeniedException ade) {
      // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
      log.warn(ade.getMessage());
      getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
      return null;
    } catch (UserExistsException e) {
      log.warn(e.getMessage());
      List<Object> args = new ArrayList<Object>();
      args.add(user.getUsername());
      args.add(user.getEmail());
      addActionError(getText("errors.existing.user", args));

      // redisplay the unencrypted passwords
      user.setPassword(user.getConfirmPassword());
      return INPUT;
    }

    saveMessage(getText("user.registered"));
    getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    UsernamePasswordAuthenticationToken auth =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send an account information e-mail
    mailMessage.setSubject(getText("signup.email.subject"));

    try {
      sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest()));
    } catch (MailException me) {
      addActionError(me.getMostSpecificCause().getMessage());
    }

    return SUCCESS;
  }
コード例 #29
0
ファイル: LoginPage.java プロジェクト: newtonik/preppa
  void onValidateForm() {

    provider.setUserDetailsService(userserve);

    provider.setPasswordEncoder(new ShaPasswordEncoder());
    authtoken = new UsernamePasswordAuthenticationToken(fLogin, fpass);
    provider.setSaltSource(salt);
    Authentication token = null;
    try {
      token = provider.authenticate(authtoken);
    } catch (org.springframework.security.BadCredentialsException e) {
      loginform.recordError("Either the Username or Password is incorrect, Please try again.");
      return;
    }
    if (token.isAuthenticated()) {
      System.out.println("user has been authenticated");
      this.user = userDAO.findByUsername(fLogin);
      SecurityContextHolder.getContext().setAuthentication(token);

      SavedRequest savedRequest =
          (SavedRequest)
              requestGlobals
                  .getHTTPServletRequest()
                  .getSession()
                  .getAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY);
      Session s = request.getSession(false);
      s.invalidate();
      s = request.getSession(true);
      if (savedRequest != null) {
        url = null;

        try {
          url = new URL(savedRequest.getRequestURL());
        } catch (MalformedURLException e) {
          System.out.println("malformed url:" + savedRequest.getRequestURI());
        }
      }

    } else {
      // fpass = null;
      // fLogin = null;

      loginform.recordError("Either the Username or Password is incorrect, Please try again.");
    }
  }
コード例 #30
0
  @Before
  public void beforeTest() throws PlatformInitializationException {
    mp = new MicroPlatform();
    // used by DefaultPentahoJackrabbitAccessControlHelper
    mp.defineInstance(IAuthorizationPolicy.class, authorizationPolicy);
    mp.defineInstance(ITenantManager.class, tenantManager);
    mp.define(ITenant.class, Tenant.class);
    mp.defineInstance("roleAuthorizationPolicyRoleBindingDaoTarget", roleBindingDaoTarget);
    mp.defineInstance(IRoleAuthorizationPolicyRoleBindingDao.class, roleBindingDaoTarget);
    mp.defineInstance("tenantedUserNameUtils", tenantedUserNameUtils);
    mp.defineInstance("tenantedRoleNameUtils", tenantedRoleNameUtils);
    mp.defineInstance("repositoryAdminUsername", repositoryAdminUsername);
    mp.define(
        IRoleAuthorizationPolicyRoleBindingDao.class, RoleAuthorizationPolicy.class, Scope.GLOBAL);
    mp.define(ITenantManager.class, RepositoryTenantManager.class, Scope.GLOBAL);
    mp.defineInstance("singleTenantAdminAuthorityName", new String("Administrator"));
    mp.defineInstance(
        "RepositoryFileProxyFactory",
        new RepositoryFileProxyFactory(this.testJcrTemplate, this.repositoryFileDao));

    UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
    userDetailsService.setUserRoleDao(userRoleDao);
    List<String> systemRoles = new ArrayList<String>();
    systemRoles.add("Admin");
    List<String> extraRoles = Arrays.asList(new String[] {"Authenticated", "Anonymous"});
    String adminRole = "Admin";

    userRoleListService =
        new UserRoleDaoUserRoleListService(
            userRoleDao,
            userDetailsService,
            tenantedUserNameUtils,
            systemRoles,
            extraRoles,
            adminRole);
    ((UserRoleDaoUserRoleListService) userRoleListService).setUserRoleDao(userRoleDao);
    ((UserRoleDaoUserRoleListService) userRoleListService)
        .setUserDetailsService(userDetailsService);

    mp.defineInstance(IUserRoleListService.class, userRoleListService);
    mp.start();
    logout();
    startupCalled = true;
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
  }