Java 类org.springframework.security.Authentication 实例源码

项目:pentaho-transparent-authentication    文件:AuthenticationExtensionFilter.java   
private boolean mustIgnore(HttpServletRequest request)
{
    Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
    if (currentAuthentication != null && currentAuthentication.isAuthenticated())
    {
        return true;
    }

    String autologinParam = request.getParameter(AUTOLOGIN_PARAM_NAME);
    if (!"true".equals(autologinParam))
    {
        return true;
    }

    // TODO: implement other conditions if appropriate.
    return false;
}
项目:pentaho-authentication-ext    文件:AuthenticationExtensionFilter.java   
private boolean mustIgnore(HttpServletRequest request)
{
    Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
    if (currentAuthentication != null && currentAuthentication.isAuthenticated())
    {
        return true;
    }

    String autologinParam = request.getParameter(AUTOLOGIN_PARAM_NAME);
    if (!"true".equals(autologinParam))
    {
        return true;
    }

    // TODO: implement other conditions if appropriate.
    return false;
}
项目:pentaho-authentication-ext    文件:ExtensionAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authenticationRequest)
        throws AuthenticationException {
    GrantedAuthority[] authorities = new GrantedAuthorityImpl[authenticationRequest.getAuthorities().length + 1];
    authorities[0] = new GrantedAuthorityImpl(AUTHENTICATED_AUTHORITY_NAME);
    int i = 1;
    for(GrantedAuthority originalAuth : authenticationRequest.getAuthorities()){
        authorities[i] = new GrantedAuthorityImpl(originalAuth.getAuthority());
        i += 1;
    }

    UsernamePasswordAuthenticationToken authenticationOutcome = new UsernamePasswordAuthenticationToken(authenticationRequest.getPrincipal(), 
            authenticationRequest.getCredentials(), authorities);
    authenticationOutcome.setDetails(authenticationRequest.getDetails());
    return authenticationOutcome;
}
项目:pentaho-authentication-ext    文件:AuthenticationExtensionFilterTest.java   
@Test
public void testDoFilter() throws IOException, ServletException, ExternalAppNotMappedException
{
    assertNotNull(loginTicketManager);

    //makes the ticket manager issue a ticket
    LoginTicket ticket = loginTicketManager.generateNewTicket("test", "externalTestUser");
    String ticketId = ticket.getIdAsString();

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain chain = new MockFilterChain();

    request.addParameter(AuthenticationExtensionFilter.AUTOLOGIN_PARAM_NAME, "true");
    request.addParameter(AuthenticationExtensionFilter.TICKET_PARAM_NAME, ticketId);

    authFilter.doFilter(request, response, chain);
    String content = response.getContentAsString();
    assertNotNull(content);

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    assertNotNull(auth);
}
项目:pentaho-transparent-authentication    文件:ExtensionAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authenticationRequest)
        throws AuthenticationException {
    GrantedAuthority[] authorities = new GrantedAuthorityImpl[authenticationRequest.getAuthorities().length + 1];
    authorities[0] = new GrantedAuthorityImpl(AUTHENTICATED_AUTHORITY_NAME);
    int i = 1;
    for(GrantedAuthority originalAuth : authenticationRequest.getAuthorities()){
        authorities[i] = new GrantedAuthorityImpl(originalAuth.getAuthority());
        i += 1;
    }

    UsernamePasswordAuthenticationToken authenticationOutcome = new UsernamePasswordAuthenticationToken(authenticationRequest.getPrincipal(), 
            authenticationRequest.getCredentials(), authorities);
    authenticationOutcome.setDetails(authenticationRequest.getDetails());
    return authenticationOutcome;
}
项目:pentaho-transparent-authentication    文件:AuthenticationExtensionFilterTest.java   
@Test
public void testDoFilter() throws IOException, ServletException, ExternalAppNotMappedException
{
    assertNotNull(loginTicketManager);

    //makes the ticket manager issue a ticket
    LoginTicket ticket = loginTicketManager.generateNewTicket("test", "externalTestUser");
    String ticketId = ticket.getIdAsString();

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain chain = new MockFilterChain();

    request.addParameter(AuthenticationExtensionFilter.AUTOLOGIN_PARAM_NAME, "true");
    request.addParameter(AuthenticationExtensionFilter.TICKET_PARAM_NAME, ticketId);

    authFilter.doFilter(request, response, chain);
    String content = response.getContentAsString();
    assertNotNull(content);

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    assertNotNull(auth);
}
项目:spring-rich-client    文件:AbstractSecurityController.java   
/**
 * Determine if our controlled objects should be authorized based on the provided
 * authentication token.
 * @param authentication token
 * @return true if should authorize
 */
protected boolean shouldAuthorize(Authentication authentication) {
    Assert.state( getAccessDecisionManager() != null, "The AccessDecisionManager can not be null!" );
    boolean authorize = false;
    try {
        if( authentication != null ) {
            Object securedObject = getSecuredObject();
            ConfigAttributeDefinition cad = getConfigAttributeDefinition( securedObject );
            getAccessDecisionManager().decide( authentication, getSecuredObject(), cad );
            authorize = true;
        }
    } catch( AccessDeniedException e ) {
        // This means the secured objects should not be authorized
    }
    return authorize;
}
项目:spring-rich-client    文件:DefaultApplicationSecurityManager.java   
/**
 * Determine if the currently authenticated user has the role provided. Note that role
 * comparisons are case sensitive.
 * 
 * @param role to check
 * @return true if the user has the role requested
 */
public boolean isUserInRole(String role) {
    boolean inRole = false;

    Authentication authentication = getAuthentication();
    if( authentication != null ) {
        GrantedAuthority[] authorities = authentication.getAuthorities();
        for( int i = 0; i < authorities.length; i++ ) {
            if( role.equals( authorities[i].getAuthority() ) ) {
                inRole = true;
                break;
            }
        }
    }
    return inRole;
}
项目:spring-rich-client    文件:ApplicationSession.java   
/**
 * When a correct login occurs, read all relevant userinformation into
 * session.
 *
 * @param event
 *            the loginEvent that triggered this handler.
 */
protected void handleLoginEvent(LoginEvent event)
{
    ApplicationSessionInitializer asi = getApplicationSessionInitializer();
    if (asi != null)
    {
        asi.initializeUser();
        Map<String, Object> userAttributes = asi.getUserAttributes();
        if (userAttributes != null)
        {
            setUserAttributes(userAttributes);
        }
    }
    Authentication auth = (Authentication) event.getSource();
    propertyChangeSupport.firePropertyChange(USER, null, auth);
}
项目:egovframework.rte.root    文件:EgovUserDetailsHelper.java   
/**
 * 인증된 사용자 여부를 체크한다.
 * @return 인증된 사용자 여부(TRUE / FALSE)
 */
public static Boolean isAuthenticated() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();

    if (EgovObjectUtil.isNull(authentication)) {
        log.debug("## authentication object is null!!");
        return Boolean.FALSE;
    }

    String username = authentication.getName();
    if (username.equals("roleAnonymous")) {
        log.debug("## username is " + username);
        return Boolean.FALSE;
    }

    Object principal = authentication.getPrincipal();

    return (Boolean.valueOf(!EgovObjectUtil.isNull(principal)));
}
项目:spring-richclient    文件:DefaultApplicationSecurityManager.java   
/**
 * Determine if the currently authenticated user has the role provided. Note that role
 * comparisons are case sensitive.
 * 
 * @param role to check
 * @return true if the user has the role requested
 */
public boolean isUserInRole(String role) {
    boolean inRole = false;

    Authentication authentication = getAuthentication();
    if( authentication != null ) {
        GrantedAuthority[] authorities = authentication.getAuthorities();
        for( int i = 0; i < authorities.length; i++ ) {
            if( role.equals( authorities[i].getAuthority() ) ) {
                inRole = true;
                break;
            }
        }
    }
    return inRole;
}
项目:egovframework.rte.root    文件:EgovUserDetailsHelper.java   
/**
 * 인증된 사용자객체를 VO형식으로 가져온다.
 * @return 사용자 ValueObject
 */
public static Object getAuthenticatedUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();

    if (EgovObjectUtil.isNull(authentication)) {
        log.debug("## authentication object is null!!");
        return null;
    }

    EgovUserDetails details =
        (EgovUserDetails) authentication.getPrincipal();

    log
        .debug("## EgovUserDetailsHelper.getAuthenticatedUser : AuthenticatedUser is "
            + details.getUsername());
    return details.getEgovUserVO();
}
项目:gocd    文件:BasicAuthenticationFilterTest.java   
@Test
public void shouldConvey_itsBasicProcessingFilter() throws IOException, ServletException {
    BasicAuthenticationFilter filter = new BasicAuthenticationFilter(localizer);
    final Boolean[] hadBasicMarkOnInsideAuthenticationManager = new Boolean[]{false};

    filter.setAuthenticationManager(new AuthenticationManager() {
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            hadBasicMarkOnInsideAuthenticationManager[0] = BasicAuthenticationFilter.isProcessingBasicAuth();
            return new UsernamePasswordAuthenticationToken("school-principal", "u can be principal if you know this!");
        }
    });
    assertThat(BasicAuthenticationFilter.isProcessingBasicAuth(), is(false));
    MockHttpServletRequest httpRequest = new MockHttpServletRequest();
    httpRequest.addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("loser:boozer".getBytes()));
    filter.doFilterHttp(httpRequest, new MockHttpServletResponse(), new FilterChain() {
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {

        }
    });
    assertThat(BasicAuthenticationFilter.isProcessingBasicAuth(), is(false));

    assertThat(hadBasicMarkOnInsideAuthenticationManager[0], is(true));
}
项目:OpenNMS    文件:DefaultSurveillanceServiceTest.java   
@Test
public void testGetUsernameNoPrincipalObject() {
    Authentication auth = new UsernamePasswordAuthenticationToken(null, null, new GrantedAuthority[0]);
    SecurityContextHolder.getContext().setAuthentication(auth);

    ThrowableAnticipator ta = new ThrowableAnticipator();
    ta.anticipate(new IllegalStateException("No principal object found when calling getPrinticpal on our Authentication object"));

    try {
        m_service.getUsername();
    } catch (Throwable t) {
        ta.throwableReceived(t);
    }

    ta.verifyAnticipated();
}
项目:gocd    文件:PreAuthenticatedRequestsProcessingFilterTest.java   
@Test
public void shouldAuthenticateUsersWithCredentials() throws IOException, ServletException {
    PreAuthenticatedAuthenticationToken token = mock(PreAuthenticatedAuthenticationToken.class);
    HashMap<String, String[]> params = new HashMap<>();
    params.put("code", new String[]{"some_auth_code"});
    SecurityAuthConfig githubAuthConfig = new SecurityAuthConfig("github", "github.oauth");
    securityConfig.securityAuthConfigs().add(githubAuthConfig);

    when(request.getRequestURI()).thenReturn("/go/plugin/github.oauth/authenticate");
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(Arrays.asList("Authorization")));
    when(request.getHeader("Authorization")).thenReturn("qwe123");
    when(request.getParameterMap()).thenReturn(params);
    when(authorizationExtension.fetchAccessToken("github.oauth", Collections.singletonMap("Authorization", "qwe123"),
            Collections.singletonMap("code", "some_auth_code"), Collections.singletonList(githubAuthConfig))).
            thenReturn(Collections.singletonMap("access_token", "token"));
    when(authenticationManager.authenticate(any(PreAuthenticatedAuthenticationToken.class))).thenReturn(token);
    filter.setDefaultTargetUrl("/");

    filter.doFilter(request, response, filterChain);

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    assertThat(authentication, is(token));
}
项目:gocd    文件:ReAuthenticationFilter.java   
@Override
protected void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (!systemEnvironment.isReAuthenticationEnabled() || authentication == null) {
        chain.doFilter(request, response);
        return;
    }

    synchronized (request.getSession().getId().intern()) {
        Long lastAuthenticationTime = (Long) request.getSession().getAttribute(LAST_REAUTHENICATION_CHECK_TIME);
        if (lastAuthenticationTime == null) {
            request.getSession().setAttribute(LAST_REAUTHENICATION_CHECK_TIME, timeProvider.currentTimeMillis());
        } else if (forceReAuthentication(lastAuthenticationTime)) {
            request.getSession().setAttribute(LAST_REAUTHENICATION_CHECK_TIME, timeProvider.currentTimeMillis());
            authentication.setAuthenticated(false);
        }
    }

    chain.doFilter(request, response);
}
项目:gocd    文件:RemoveAdminPermissionFilter.java   
public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        chain.doFilter(request, response);
        return;
    }
    synchronized (request.getRequestedSessionId().intern()) {
        long localCopyOfLastChangedTime = lastChangedTime;//This is so that the volatile variable is accessed only once.
        Long previousLastChangedTime = (Long) request.getSession().getAttribute(SECURITY_CONFIG_LAST_CHANGE);
        if (previousLastChangedTime == null) {
            request.getSession().setAttribute(SECURITY_CONFIG_LAST_CHANGE, localCopyOfLastChangedTime);
        } else if (previousLastChangedTime < localCopyOfLastChangedTime) {
            request.getSession().setAttribute(SECURITY_CONFIG_LAST_CHANGE, localCopyOfLastChangedTime);
            authentication.setAuthenticated(false);
        }
    }
    chain.doFilter(request, response);
}
项目:gocd    文件:OauthAuthenticationFilter.java   
protected void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    String header = request.getHeader(AUTHORIZATION);//Token token="ACCESS_TOKEN"

    if (header != null) {
        logger.debug("Oauth authorization header: " + header);
        Matcher matcher = OAUTH_TOKEN_PATTERN.matcher(header);
        if (matcher.matches()) {
            String token = matcher.group(1);
            OauthAuthenticationToken authenticationToken = new OauthAuthenticationToken(token);
            try {
                Authentication authResult = authenticationManager.authenticate(authenticationToken);
                SecurityContextHolder.getContext().setAuthentication(authResult);
            } catch (AuthenticationException e) {
                logger.debug("Oauth authentication request for token: " + token, e);
                SecurityContextHolder.getContext().setAuthentication(null);
            }
        }
    }
    chain.doFilter(request, response);
}
项目:egovframework.rte.root    文件:EgovUserDetailsHelper.java   
/**
 * 인증된 사용자의 권한 정보를 가져온다. 예) [ROLE_ADMIN, ROLE_USER,
 * ROLE_A, ROLE_B, ROLE_RESTRICTED,
 * IS_AUTHENTICATED_FULLY,
 * IS_AUTHENTICATED_REMEMBERED,
 * IS_AUTHENTICATED_ANONYMOUSLY]
 * @return 사용자 권한정보 목록
 */
public static List<String> getAuthorities() {
    List<String> listAuth = new ArrayList<String>();

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

    if (EgovObjectUtil.isNull(authentication)) {
        log.debug("## authentication object is null!!");
        return null;
    }

    GrantedAuthority[] authorities = authentication.getAuthorities();

    for (int i = 0; i < authorities.length; i++) {
        listAuth.add(authorities[i].getAuthority());

        log.debug("## EgovUserDetailsHelper.getAuthorities : Authority is "
            + authorities[i].getAuthority());
    }

    return listAuth;
}
项目:gocd    文件:RemoveAdminPermissionFilterIntegrationTest.java   
@Test
public void testShouldForceReAuthenticationOnRoleConfigChange() throws Exception {
    final ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
    final Username username = new Username("bob");
    final RoleConfig admin = new RoleConfig(new CaseInsensitiveString("admin"));
    final Authentication authentication = setupAuthentication();
    final RemoveAdminPermissionFilter filter = new RemoveAdminPermissionFilter(goConfigService, timeProvider, pluginRoleService);
    filter.initialize();

    filter.doFilterHttp(request, response, chain);
    assertThat(authentication.isAuthenticated(), is(true));

    roleService.create(username, admin, new HttpLocalizedOperationResult());

    verify(session).setAttribute(eq(SECURITY_CONFIG_LAST_CHANGE), argumentCaptor.capture());
    when(session.getAttribute(SECURITY_CONFIG_LAST_CHANGE)).thenReturn(argumentCaptor.getValue());

    filter.doFilterHttp(request, response, chain);

    assertThat(authentication.isAuthenticated(), is(false));
}
项目:spring-richclient    文件:DefaultApplicationSecurityManagerTests.java   
/**
 * Do one failed authentication invocation and test results.
 * @param authentication token to use
 * @param exceptionType Type of exception that should be thrown
 */
private void doOneFailed(Authentication authentication, Class exceptionType) {
    ApplicationSecurityManager asm = (ApplicationSecurityManager)ApplicationServicesLocator.services().getService(ApplicationSecurityManager.class);
    Authentication current = asm.getAuthentication();

    eventCounter.resetCounters();
    try {
        asm.doLogin( authentication );
        fail( exceptionType.getName() + " should have been thrown" );
    } catch( SpringSecurityException e ) {
        // We expect an exception
        assertTrue( "Wrong exception thrown; expecting: " + exceptionType.getName(), exceptionType
            .isAssignableFrom( e.getClass() ) );
        testCounters( 0, 1, 0, 0 );
        assertTrue( "User should still be logged in now", asm.isUserLoggedIn() );
        // Shouldn't have changed
        assertEquals( "Authentiation token should not have changed", asm.getAuthentication(), current );
    }
}
项目:gocd    文件:ReAuthenticationFilterTest.java   
@Test
public void shouldReAuthenticateIfReAuthTimeIntervalHasElapsed() throws IOException, ServletException {
    long currentTimeMillis = DateTimeUtils.currentTimeMillis();
    long minuteBack = DateTimeUtils.currentTimeMillis() - 60000;
    Authentication authentication = setupAuthentication(true);

    when(timeProvider.currentTimeMillis()).thenReturn(currentTimeMillis);
    when(systemEnvironment.isReAuthenticationEnabled()).thenReturn(true);
    when(systemEnvironment.getReAuthenticationTimeInterval()).thenReturn(55000L);
    when(session.getAttribute(LAST_REAUTHENICATION_CHECK_TIME)).thenReturn(minuteBack);

    filter.doFilterHttp(request, response, filterChain);

    verify(session).setAttribute(LAST_REAUTHENICATION_CHECK_TIME, currentTimeMillis);
    verify(filterChain).doFilter(request, response);
    verifyNoMoreInteractions(filterChain);
    assertFalse(authentication.isAuthenticated());
}
项目:spring-richclient    文件:SessionDetails.java   
public static Authentication logout() {
    Authentication existing = SecurityContextHolder.getContext().getAuthentication();

    // Make the Authentication object null if a SecureContext exists
    SecurityContextHolder.getContext().setAuthentication(null);

    // Create a non-null Authentication object if required (to meet
    // ApplicationEvent contract)
    if (existing == null) {
        existing = ClientSecurityEvent.NO_AUTHENTICATION;
    }

    // Fire application event to advise of logout
    ApplicationContext appCtx = Application.instance().getApplicationContext();
    appCtx.publishEvent(new LogoutEvent(existing));

    return existing;
}
项目:pentaho-authentication-ext    文件:AuthenticationExtensionFilter.java   
private void authenticateUser(String requestingUserName, HttpServletRequest request) throws UserNotFoundException
{
    IPentahoUser user = getUserRoleDao().getUser(null, requestingUserName);
    if (user == null)
    {
        // TODO: implement alternative behavior if needed, e.g. create the
        // user if it does not exist
        throw new UserNotFoundException("User '" + requestingUserName
                + "' not found in the current system using the default UserRoleDao bean");
    }

    List<IPentahoRole> roles = getUserRoleDao().getUserRoles(null, requestingUserName);
    GrantedAuthority[] authorities = new GrantedAuthority[roles.size()];
    int index = 0;
    for (IPentahoRole role : roles)
    {
        authorities[index] = new GrantedAuthorityImpl(role.getName());
    }
    ExtensionAuthenticationToken authRequestToken = new ExtensionAuthenticationToken(requestingUserName, null,
            authorities);
    authRequestToken.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticationOutcome = getAuthenticationManager().authenticate(authRequestToken);

    // TODO: manage possible errors (authenticationOutcome == null,
    // Exception, etc...)
    SecurityContextHolder.getContext().setAuthentication(authenticationOutcome);
}
项目:pentaho-transparent-authentication    文件:AuthenticationExtensionFilter.java   
private void authenticateUser(String requestingUserName, HttpServletRequest request) throws UserNotFoundException
{
    IPentahoUser user = getUserRoleDao().getUser(null, requestingUserName);
    if (user == null)
    {
        // TODO: implement alternative behavior if needed, e.g. create the
        // user if it does not exist
        throw new UserNotFoundException("User '" + requestingUserName
                + "' not found in the current system using the default UserRoleDao bean");
    }

    List<IPentahoRole> roles = getUserRoleDao().getUserRoles(null, requestingUserName);
    GrantedAuthority[] authorities = new GrantedAuthority[roles.size()];
    int index = 0;
    for (IPentahoRole role : roles)
    {
        authorities[index] = new GrantedAuthorityImpl(role.getName());
    }
    ExtensionAuthenticationToken authRequestToken = new ExtensionAuthenticationToken(requestingUserName, null,
            authorities);
    authRequestToken.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticationOutcome = getAuthenticationManager().authenticate(authRequestToken);

    // TODO: manage possible errors (authenticationOutcome == null,
    // Exception, etc...)
    SecurityContextHolder.getContext().setAuthentication(authenticationOutcome);
}
项目:SelfSoftShop    文件:AdminServiceImpl.java   
public Admin getLoginAdmin() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return null;
    }
    Object principal = authentication.getPrincipal();
    if (principal == null || !(principal instanceof Admin)) {
        return null;
    } else {
        return (Admin) principal;
    }
}
项目:spring-rich-client    文件:SessionDetails.java   
public void login() throws SpringSecurityException {
    final ApplicationContext appCtx = Application.instance().getApplicationContext();

    // Attempt login
    UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken(getUsername(),
            getPassword());

    Authentication result = null;

    try {
        result = authenticationManager.authenticate(request);
    } catch( SpringSecurityException e ) {
        logger.warn( "authentication failed", e);

        // Fire application event to advise of failed login
        appCtx.publishEvent( new AuthenticationFailedEvent(request, e));

        // And rethrow the exception to prevent the dialog from closing
        throw e;
    }

    // Handle success or failure of the authentication attempt
    if( logger.isDebugEnabled()) {
        logger.debug("successful login - update context holder and fire event");
    }

    // Commit the successful Authentication object to the secure
    // ContextHolder
    SecurityContextHolder.getContext().setAuthentication(result);

    // Fire application event to advise of new login
    appCtx.publishEvent(new LoginEvent(result));
}
项目:spring-rich-client    文件:LoginDetails.java   
/**
 * Constructor. Pre-load our username field with the data currently stored in the
 * security context, if any.
 */
public LoginDetails() {
    // Retrieve any existing login information and install it
    ApplicationSecurityManager sm = (ApplicationSecurityManager)ApplicationServicesLocator.services().getService(ApplicationSecurityManager.class);
    Authentication authentication = sm.getAuthentication();
    if( authentication != null ) {
        setUsername( authentication.getName() );
    }
    initRules();
}
项目:spring-rich-client    文件:BasicAuthHttpInvokerProxyFactoryBean.java   
/**
 * Handle a change in the current authentication token. Pass it along to the executor
 * if it's of the proper type.
 * @see BasicAuthHttpInvokerRequestExecutor
 * @see AuthenticationAware#setAuthenticationToken(org.springframework.security.Authentication)
 */
public void setAuthenticationToken(Authentication authentication) {
    if( logger.isDebugEnabled() ) {
        logger.debug( "New authentication token: " + authentication );
    }

    final HttpInvokerRequestExecutor hire = getHttpInvokerRequestExecutor();
    if( hire instanceof BasicAuthHttpInvokerRequestExecutor ) {
        if( logger.isDebugEnabled() ) {
            logger.debug( "Pass it along to executor" );
        }
        ((BasicAuthHttpInvokerRequestExecutor) hire).setAuthenticationToken( authentication );
    }
}
项目:spring-richclient    文件:SecurityAwareConfigurer.java   
/**
 * Broadcast an authentication event to all the AuthenticationAware beans.
 * @param authentication token
 */
protected void broadcastAuthentication(Authentication authentication) {
    if( logger.isDebugEnabled() )
        logger.debug( "BROADCAST authentication: token=" + authentication );

    // Save this for any new beans that we post-process
    currentAuthentication = authentication;

    final Iterator iter = getBeansToUpdate( AuthenticationAware.class ).iterator();
    while( iter.hasNext() ) {
        ((AuthenticationAware) iter.next()).setAuthenticationToken( authentication );
    }
}
项目:OpenNMS    文件:AuthenticationIntegrationTest.java   
@Test
public void testAuthenticateBadPassword() {
    Authentication authentication = new UsernamePasswordAuthenticationToken("admin", "badPassword");

    ThrowableAnticipator ta = new ThrowableAnticipator();
    ta.anticipate(new BadCredentialsException("Bad credentials"));
    try {
        m_provider.authenticate(authentication);
    } catch (Throwable t) {
        ta.throwableReceived(t);
    }
    ta.verifyAnticipated();
}
项目:OpenNMS    文件:SecurityAuthenticationEventOnmsEventBuilder.java   
private EventBuilder createEvent(String uei, AbstractAuthenticationEvent authEvent) {
    EventBuilder builder = new EventBuilder(uei, "OpenNMS.WebUI");
    builder.setTime(new Date(authEvent.getTimestamp()));
    Authentication auth = authEvent.getAuthentication();
    if (auth != null && auth.getName() != null) {
        builder.addParam("user", WebSecurityUtils.sanitizeString(auth.getName()));
    }
    if (auth != null && auth.getDetails() != null && auth.getDetails() instanceof WebAuthenticationDetails) {
        WebAuthenticationDetails webDetails = (WebAuthenticationDetails) auth.getDetails();
        if (webDetails.getRemoteAddress() != null) {
            builder.addParam("ip", webDetails.getRemoteAddress());
        }
    }
    return builder;
}
项目:OpenNMS    文件:SpringSecurityContextServiceTest.java   
@Before
public void setUp() throws Exception {
    SecurityContext context = new SecurityContextImpl();
    User principal = new User(USERNAME, PASS, true, true, true, true,
            new GrantedAuthority[] { ROLE_ADMIN, ROLE_PROVISION });
    Authentication auth = new PreAuthenticatedAuthenticationToken(
            principal, new Object());
    context.setAuthentication(auth);
    SecurityContextHolder.setContext(context);
    this.m_securityContextService = new SpringSecurityContextService();
}
项目:spring-rich-client    文件:SecurityAwareConfigurer.java   
/**
 * Broadcast a Login event to all the LoginAware beans.
 * @param authentication token
 */
protected void broadcastLogin(Authentication authentication) {
    if( logger.isDebugEnabled() )
        logger.debug( "BROADCAST login: token=" + authentication );

    final Iterator iter = getBeansToUpdate( LoginAware.class ).iterator();
    while( iter.hasNext() ) {
        ((LoginAware) iter.next()).userLogin( authentication );
    }
}
项目:spring-rich-client    文件:SecurityAwareConfigurer.java   
/**
 * Broadcast a Logout event to all the LoginAware beans.
 * @param authentication token
 */
protected void broadcastLogout(Authentication authentication) {
    if( logger.isDebugEnabled() )
        logger.debug( "BROADCAST logout: token=" + authentication );

    final Iterator iter = getBeansToUpdate( LoginAware.class ).iterator();
    while( iter.hasNext() ) {
        ((LoginAware) iter.next()).userLogout( authentication );
    }
}
项目:spring-rich-client    文件:SecurityAwareConfigurer.java   
public void onApplicationEvent(ApplicationEvent event) {

        // All events we care about are subtypes of ClientSecurityEvent
        if( event instanceof ClientSecurityEvent ) {
            Authentication authentication = (Authentication) event.getSource();

            if( logger.isDebugEnabled() ) {
                logger.debug( "RECEIVED ClientSecurityEvent: " + event );
                logger.debug( "Authentication token: " + authentication );
            }

            // Note that we need to inspect the new authentication token and see if it is
            // NO_AUTHENTICATION. If so, then we need to use null instead. This little
            // dance is required because the source of an event can't actually be null.

            if( authentication == ClientSecurityEvent.NO_AUTHENTICATION ) {
                if( logger.isDebugEnabled() ) {
                    logger.debug( "Converted NO_AUTHENTICATION to null" );
                }
                authentication = null;
            }

            // And dispatch according to the event type.

            if( event instanceof AuthenticationEvent ) {
                broadcastAuthentication( authentication );
            } else if( event instanceof LoginEvent ) {
                broadcastLogin( authentication );
            } else if( event instanceof LogoutEvent ) {
                broadcastLogout( authentication );
            } else {
                if( logger.isDebugEnabled() ) {
                    logger.debug( "Unsupported event not processed" );
                }
            }
        }
    }
项目:OpenNMS    文件:DefaultSurveillanceServiceTest.java   
@Test
public void testGetUsernameWithStringPrincipal() {
    Authentication auth = new UsernamePasswordAuthenticationToken("user", null, new GrantedAuthority[0]);
    SecurityContextHolder.getContext().setAuthentication(auth);

    String user = m_service.getUsername();
    assertNotNull("user should not be null", user);
    assertEquals("user name", "user", user);
}
项目:spring-rich-client    文件:RemotingSecurityConfigurer.java   
public void onApplicationEvent(ApplicationEvent event) {
    if (logger.isDebugEnabled() && event instanceof ClientSecurityEvent) {
        logger.debug("Processing event: " + event.toString());
    }

    if (event instanceof LoginEvent) {
        Authentication authentication = (Authentication)event.getSource();
        updateExporters(authentication.getPrincipal().toString(), authentication.getCredentials().toString());
    }
    else if (event instanceof LogoutEvent) {
        updateExporters(null, null);
    }
}
项目:spring-rich-client    文件:LogoutCommand.java   
protected void doExecuteCommand() {
    ApplicationSecurityManager sm = (ApplicationSecurityManager)ApplicationServicesLocator.services().getService(ApplicationSecurityManager.class);
    Authentication loggedOutAuth = sm.doLogout();
    onLogout(loggedOutAuth);

    if (displaySuccess) {
        JOptionPane.showMessageDialog(getParentWindowControl(), "You have been logged out.", "Logout Successful",
                JOptionPane.INFORMATION_MESSAGE);
    }
}
项目:spring-richclient    文件:DefaultApplicationSecurityManager.java   
/**
 * Process a login attempt and fire all related events. If the authentication fails,
 * then a {@link AuthenticationFailedEvent} is published and the exception is
 * rethrown. If the authentication succeeds, then an {@link AuthenticationEvent} is
 * published, followed by a {@link LoginEvent}.
 * 
 * @param authentication token to use for the login attempt
 * @return Authentication token resulting from a successful call to
 *         {@link AuthenticationManager#authenticate(org.springframework.security.Authentication)}.
 * @see org.springframework.richclient.security.ApplicationSecurityManager#doLogin(org.springframework.security.Authentication)
 * @throws SpringSecurityException If the authentication attempt fails
 */
public Authentication doLogin(Authentication authentication) {
    final ApplicationContext appCtx = Application.instance().getApplicationContext();

    Authentication result = null;

    try {
        result = getAuthenticationManager().authenticate( authentication );
    } catch( SpringSecurityException e ) {
        logger.info( "authentication failed: " + e.getMessage() );

        // Fire application event to advise of failed login
        appCtx.publishEvent( new AuthenticationFailedEvent( authentication, e ) );

        // rethrow the exception
        throw e;
    }

    // Handle success or failure of the authentication attempt
    if( logger.isDebugEnabled() ) {
        logger.debug( "successful login - update context holder and fire event" );
    }

    // Commit the successful Authentication object to the secure ContextHolder
    SecurityContextHolder.getContext().setAuthentication( result );
    setAuthentication( result );

    // Fire application events to advise of new login
    appCtx.publishEvent( new AuthenticationEvent( result ) );
    appCtx.publishEvent( new LoginEvent( result ) );

    return result;
}