当前位置: 首页>>代码示例>>Java>>正文


Java SecurityContextHolder类代码示例

本文整理汇总了Java中org.springframework.security.context.SecurityContextHolder的典型用法代码示例。如果您正苦于以下问题:Java SecurityContextHolder类的具体用法?Java SecurityContextHolder怎么用?Java SecurityContextHolder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


SecurityContextHolder类属于org.springframework.security.context包,在下文中一共展示了SecurityContextHolder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: mustIgnore

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
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;
}
 
开发者ID:Rospaccio,项目名称:pentaho-transparent-authentication,代码行数:18,代码来源:AuthenticationExtensionFilter.java

示例2: testDoFilter

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
@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);
}
 
开发者ID:Rospaccio,项目名称:pentaho-authentication-ext,代码行数:24,代码来源:AuthenticationExtensionFilterTest.java

示例3: testDoFilterNoMapping

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
@Test
public void testDoFilterNoMapping() throws IOException, ServletException
{
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	MockFilterChain chain = new MockFilterChain();

	request.addParameter(LoginTicketGeneratorFilter.GENERATE_TICKET_PARAM_NAME, "1");
	request.addParameter(LoginTicketGeneratorFilter.REQUESTING_APP_PARAM_NAME, "IDoNotExist");
	request.addParameter(LoginTicketGeneratorFilter.REQUESTING_USERNAME_PARAM_NAME, "testUser");

	// Adds an authentication in the SecurityContext, in order to simulate
	// the
	// work of the requestParametersAuthenticationFilter
	SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("test", "test"));

	loginTicketGeneratorFilter.doFilter(request, response, chain);

	assertNotNull(response);
	assertEquals(500, response.getStatus());
}
 
开发者ID:Rospaccio,项目名称:pentaho-authentication-ext,代码行数:22,代码来源:LoginTicketGeneratorFilterTest.java

示例4: testDoFilterNoMapping

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
@Test
public void testDoFilterNoMapping() throws IOException, ServletException
{
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	MockFilterChain chain = new MockFilterChain();

	request.addParameter(LoginTicketGeneratorFilter.GENERATE_TICKET_PARAM_NAME, "1");
	request.addParameter(LoginTicketGeneratorFilter.REQUESTING_APP_PARAM_NAME, "IDoNotExist");
	request.addParameter(LoginTicketGeneratorFilter.REQUESTING_USERNAME_PARAM_NAME, "testUser");

	// Adds an authentication in the SecurityContext, in order to simulate
	// the
	// work of the requestParametersAuthenticationFilter
	SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("test", "test"));

	loginTicketGeneratorFilter.doFilter(request, response, chain);

	assertEquals(500, response.getStatus());
	assertNotNull(response.getErrorMessage());
}
 
开发者ID:Rospaccio,项目名称:pentaho-transparent-authentication,代码行数:22,代码来源:LoginTicketGeneratorFilterTest.java

示例5: testDoFilterNoAuthentication

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
@Test
public void testDoFilterNoAuthentication() throws IOException, ServletException
{
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	MockFilterChain chain = new MockFilterChain();
	
	SecurityContextHolder.getContext().setAuthentication(null);
	
	request.addParameter(LoginTicketGeneratorFilter.GENERATE_TICKET_PARAM_NAME, "1");
	request.addParameter(LoginTicketGeneratorFilter.REQUESTING_APP_PARAM_NAME, "test");
	request.addParameter(LoginTicketGeneratorFilter.REQUESTING_USERNAME_PARAM_NAME, "testUser");
	
	loginTicketGeneratorFilter.doFilter(request, response, chain);

	assertEquals(500, response.getStatus());
	assertNotNull(response.getErrorMessage());
	assertEquals(LoginTicketGeneratorFilter.MISSING_AUTH_ERROR_MESSAGE, response.getErrorMessage());
}
 
开发者ID:Rospaccio,项目名称:pentaho-transparent-authentication,代码行数:20,代码来源:LoginTicketGeneratorFilterTest.java

示例6: logout

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
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;
}
 
开发者ID:shevek,项目名称:spring-rich-client,代码行数:19,代码来源:SessionDetails.java

示例7: clearSingletons

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
public static void clearSingletons() {
    AnalyticsMetadataStore.instance().clear();
    ArtifactMetadataStore.instance().clear();
    AuthorizationMetadataStore.instance().clear();
    ConfigRepoMetadataStore.instance().clear();
    ElasticAgentMetadataStore.instance().clear();
    NewSCMMetadataStore.instance().clear();
    NotificationMetadataStore.instance().clear();
    PackageMaterialMetadataStore.instance().clear();
    PluggableTaskMetadataStore.instance().clear();

    //
    SecurityContextHolder.getContext().setAuthentication(null);

    //
    PackageMetadataStore.getInstance().clear();
    PluggableTaskConfigStore.store().clear();
    PluginSettingsMetadataStore.getInstance().clear();
    RepositoryMetadataStore.getInstance().clear();
    SCMMetadataStore.getInstance().clear();
}
 
开发者ID:gocd,项目名称:gocd,代码行数:22,代码来源:ClearSingleton.java

示例8: shouldClearUserIdFromSessionWhenLoggedInUserIsDisabled

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
@Test
public void shouldClearUserIdFromSessionWhenLoggedInUserIsDisabled() throws IOException, ServletException {
    String userName = "winner";
    SecurityContextHelper.setCurrentUser(userName);
    Long userId = 1L;
    User user = getUser(userName, userId);
    user.disable();
    when(session.getAttribute(USERID_ATTR)).thenReturn(null);
    when(userService.findUserByName(userName)).thenReturn(user);

    filter.doFilterHttp(req, res, chain);

    assertThat(SecurityContextHolder.getContext().getAuthentication(), is(nullValue()));
    verify(session).setAttribute(USERID_ATTR, null);
    verify(chain).doFilter(req, res);
}
 
开发者ID:gocd,项目名称:gocd,代码行数:17,代码来源:UserEnabledCheckFilterTest.java

示例9: shouldAuthenticateUsersWithCredentials

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
@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));
}
 
开发者ID:gocd,项目名称:gocd,代码行数:24,代码来源:PreAuthenticatedRequestsProcessingFilterTest.java

示例10: doFilterHttp

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
@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);
}
 
开发者ID:gocd,项目名称:gocd,代码行数:22,代码来源:ReAuthenticationFilter.java

示例11: doFilterHttp

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
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);
}
 
开发者ID:gocd,项目名称:gocd,代码行数:19,代码来源:RemoveAdminPermissionFilter.java

示例12: doFilterHttp

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
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);
}
 
开发者ID:gocd,项目名称:gocd,代码行数:21,代码来源:OauthAuthenticationFilter.java

示例13: getAuthenticatedUser

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
/**
 * 인증된 사용자객체를 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();
}
 
开发者ID:eGovFrame,项目名称:egovframework.rte.root,代码行数:22,代码来源:EgovUserDetailsHelper.java

示例14: getAuthorities

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
/**
 * 인증된 사용자의 권한 정보를 가져온다. 예) [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;
}
 
开发者ID:eGovFrame,项目名称:egovframework.rte.root,代码行数:31,代码来源:EgovUserDetailsHelper.java

示例15: isAuthenticated

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
/**
 * 인증된 사용자 여부를 체크한다.
 * @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)));
}
 
开发者ID:eGovFrame,项目名称:egovframework.rte.root,代码行数:24,代码来源:EgovUserDetailsHelper.java


注:本文中的org.springframework.security.context.SecurityContextHolder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。