java类org.springframework.security.Authentication的实例源码

AuthenticationExtensionFilter.java 文件源码 项目:pentaho-transparent-authentication 阅读 22 收藏 0 点赞 0 评论 0
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;
}
AuthenticationExtensionFilter.java 文件源码 项目:pentaho-authentication-ext 阅读 26 收藏 0 点赞 0 评论 0
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;
}
ExtensionAuthenticationProvider.java 文件源码 项目:pentaho-authentication-ext 阅读 23 收藏 0 点赞 0 评论 0
@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;
}
AuthenticationExtensionFilterTest.java 文件源码 项目:pentaho-authentication-ext 阅读 20 收藏 0 点赞 0 评论 0
@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);
}
ExtensionAuthenticationProvider.java 文件源码 项目:pentaho-transparent-authentication 阅读 25 收藏 0 点赞 0 评论 0
@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;
}
AuthenticationExtensionFilterTest.java 文件源码 项目:pentaho-transparent-authentication 阅读 22 收藏 0 点赞 0 评论 0
@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);
}
AbstractSecurityController.java 文件源码 项目:spring-rich-client 阅读 20 收藏 0 点赞 0 评论 0
/**
 * 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;
}
DefaultApplicationSecurityManager.java 文件源码 项目:spring-rich-client 阅读 28 收藏 0 点赞 0 评论 0
/**
 * 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;
}
ApplicationSession.java 文件源码 项目:spring-rich-client 阅读 19 收藏 0 点赞 0 评论 0
/**
 * 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);
}
EgovUserDetailsHelper.java 文件源码 项目:egovframework.rte.root 阅读 22 收藏 0 点赞 0 评论 0
/**
 * 인증된 사용자 여부를 체크한다.
 * @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)));
}
DefaultApplicationSecurityManager.java 文件源码 项目:spring-richclient 阅读 24 收藏 0 点赞 0 评论 0
/**
 * 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;
}
EgovUserDetailsHelper.java 文件源码 项目:egovframework.rte.root 阅读 21 收藏 0 点赞 0 评论 0
/**
 * 인증된 사용자객체를 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();
}
BasicAuthenticationFilterTest.java 文件源码 项目:gocd 阅读 23 收藏 0 点赞 0 评论 0
@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));
}
DefaultSurveillanceServiceTest.java 文件源码 项目:OpenNMS 阅读 22 收藏 0 点赞 0 评论 0
@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();
}
PreAuthenticatedRequestsProcessingFilterTest.java 文件源码 项目:gocd 阅读 25 收藏 0 点赞 0 评论 0
@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));
}
ReAuthenticationFilter.java 文件源码 项目:gocd 阅读 22 收藏 0 点赞 0 评论 0
@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);
}
RemoveAdminPermissionFilter.java 文件源码 项目:gocd 阅读 20 收藏 0 点赞 0 评论 0
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);
}
OauthAuthenticationFilter.java 文件源码 项目:gocd 阅读 24 收藏 0 点赞 0 评论 0
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);
}
EgovUserDetailsHelper.java 文件源码 项目:egovframework.rte.root 阅读 23 收藏 0 点赞 0 评论 0
/**
 * 인증된 사용자의 권한 정보를 가져온다. 예) [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;
}
RemoveAdminPermissionFilterIntegrationTest.java 文件源码 项目:gocd 阅读 23 收藏 0 点赞 0 评论 0
@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));
}
DefaultApplicationSecurityManagerTests.java 文件源码 项目:spring-richclient 阅读 28 收藏 0 点赞 0 评论 0
/**
 * 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 );
    }
}
ReAuthenticationFilterTest.java 文件源码 项目:gocd 阅读 21 收藏 0 点赞 0 评论 0
@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());
}
SessionDetails.java 文件源码 项目:spring-richclient 阅读 24 收藏 0 点赞 0 评论 0
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;
}
AuthenticationExtensionFilter.java 文件源码 项目:pentaho-authentication-ext 阅读 25 收藏 0 点赞 0 评论 0
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);
}
AuthenticationExtensionFilter.java 文件源码 项目:pentaho-transparent-authentication 阅读 24 收藏 0 点赞 0 评论 0
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);
}
AdminServiceImpl.java 文件源码 项目:SelfSoftShop 阅读 29 收藏 0 点赞 0 评论 0
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;
    }
}
SessionDetails.java 文件源码 项目:spring-rich-client 阅读 24 收藏 0 点赞 0 评论 0
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));
}
LoginDetails.java 文件源码 项目:spring-rich-client 阅读 28 收藏 0 点赞 0 评论 0
/**
 * 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();
}
BasicAuthHttpInvokerProxyFactoryBean.java 文件源码 项目:spring-rich-client 阅读 18 收藏 0 点赞 0 评论 0
/**
 * 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 );
    }
}
SecurityAwareConfigurer.java 文件源码 项目:spring-richclient 阅读 18 收藏 0 点赞 0 评论 0
/**
 * 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 );
    }
}


问题


面经


文章

微信
公众号

扫码关注公众号