• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java SecurityContextHolder类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: getAuthenticationInfo

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
private void getAuthenticationInfo() {
	if (m_uri == null || m_uri.getScheme() == null) {
		throw new RuntimeException("no URI specified!");
	}
	if (m_uri.getScheme().equals("rmi")) {
		// RMI doesn't have authentication
		return;
	}
	
	if (m_username == null) {
		GroovyGui gui = createGui();
        gui.createAndShowGui();
        AuthenticationBean auth = gui.getAuthenticationBean();
        m_username = auth.getUsername();
        m_password = auth.getPassword();
	}
	
	if (m_username != null) {
		SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
		SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(m_username, m_password));
	}
}
 
开发者ID:vishwaabhinav,项目名称:OpenNMS,代码行数:23,代码来源:Main.java


示例17: testBackendWithBasicAuthInDifferentThread

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
@Test
@JUnitHttpServer(port=9162, basicAuth=true, [email protected](context="/", path="src/test/resources/simple-test-webapp"))
public void testBackendWithBasicAuthInDifferentThread() throws Exception {
	SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("testuser", "testpassword"));
	assertNotNull(m_authBackEnd);
	
	final AtomicInteger first = new AtomicInteger(-1);
	final AtomicInteger second = new AtomicInteger(-1);
	
	Thread t = new Thread() {
		public void run() {
			first.set(m_authBackEnd.getCount());
			second.set(m_authBackEnd.getCount());
		}
	};
	t.start();
	t.join();
	assertEquals("first get should be 0", 0, first.get());
	assertEquals("second should be 1", 1, second.get());
}
 
开发者ID:vishwaabhinav,项目名称:OpenNMS,代码行数:21,代码来源:SimpleBackEndTest.java


示例18: getUsername

import org.springframework.security.context.SecurityContextHolder; //导入依赖的package包/类
/**
 * <p>getUsername</p>
 *
 * @return a {@link java.lang.String} object.
 */
protected String getUsername() {
    /*
     * This should never be null, as the strategy should create a
     * SecurityContext if one doesn't exist, but let's check anyway.
     */
    SecurityContext context = SecurityContextHolder.getContext();
    Assert.state(context != null, "No security context found when calling SecurityContextHolder.getContext()");
    
    Authentication auth = context.getAuthentication();
    Assert.state(auth != null, "No Authentication object found when calling getAuthentication on our SecurityContext object");
    
    Object obj = auth.getPrincipal();
    Assert.state(obj != null, "No principal object found when calling getPrinticpal on our Authentication object");
    
    
    if (obj instanceof UserDetails) { 
        return ((UserDetails)obj).getUsername(); 
    } else { 
        return obj.toString(); 
    }
}
 
开发者ID:vishwaabhinav,项目名称:OpenNMS,代码行数:27,代码来源:DefaultSurveillanceService.java


示例19: testGetUsernameNoPrincipalObject

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


示例20: authenticateUser

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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java PopulatorTree类代码示例发布时间:2022-05-22
下一篇:
Java ISaveablePart类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap