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


Java SecurityContextHolder.getContext方法代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: 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

示例5: testShouldRender500WithHTMLTextBodyWithApiAcceptHeaderWithHTML

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
@Test
public void testShouldRender500WithHTMLTextBodyWithApiAcceptHeaderWithHTML() throws IOException {

    httpRequest.addHeader("Accept", "text/html");

    SecurityContext context = SecurityContextHolder.getContext();

    filter.handleException(httpRequest, httpResponse, new Exception("some error"));
    verify(localizer).localize("AUTHENTICATION_ERROR");

    assertThat(((Exception) (httpRequest.getSession().getAttribute(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY))).getMessage(), is(errorMessage));
    assertThat(httpRequest.getAttribute(SessionDenialAwareAuthenticationProcessingFilterEntryPoint.SESSION_DENIED).toString(), is("true"));
    assertThat(context.getAuthentication(), is(nullValue()));
    assertThat(httpResponse.getRedirectedUrl(), is("/go/auth/login?login_error=1"));
}
 
开发者ID:gocd,项目名称:gocd,代码行数:16,代码来源:BasicAuthenticationFilterTest.java

示例6: setUp

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
@Before
public void setUp() throws Exception {
    originalContext = SecurityContextHolder.getContext();
    userService = mock(UserService.class);
    filter = new UserEnabledCheckFilter(userService);
    req = mock(HttpServletRequest.class);
    res = mock(HttpServletResponse.class);
    chain = mock(FilterChain.class);
    session = mock(HttpSession.class);
    when(req.getSession()).thenReturn(session);
}
 
开发者ID:gocd,项目名称:gocd,代码行数:12,代码来源:UserEnabledCheckFilterTest.java

示例7: setup

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
@Before
public void setup() throws Exception {
    systemEnvironment = new SystemEnvironment();
    systemEnvironment.setProperty(SystemEnvironment.OPTIMIZE_FULL_CONFIG_SAVE.propertyName(), "false");
    configHelper = new GoConfigFileHelper();
    configHelper.onSetUp();
    configRepository = new ConfigRepository(systemEnvironment);
    configRepository.initialize();
    timeProvider = mock(TimeProvider.class);
    fullConfigSaveMergeFlow = mock(FullConfigSaveMergeFlow.class);
    fullConfigSaveNormalFlow = mock(FullConfigSaveNormalFlow.class);
    when(timeProvider.currentTime()).thenReturn(new Date());
    ServerVersion serverVersion = new ServerVersion();
    ConfigElementImplementationRegistry registry = ConfigElementImplementationRegistryMother.withNoPlugins();
    ServerHealthService serverHealthService = new ServerHealthService();
    cachedGoPartials = new CachedGoPartials(serverHealthService);
    dataSource = new GoFileConfigDataSource(new GoConfigMigration(new GoConfigMigration.UpgradeFailedHandler() {
        public void handle(Exception e) {
            throw new RuntimeException(e);
        }
    }, configRepository, new TimeProvider(), configCache, registry),
            configRepository, systemEnvironment, timeProvider, configCache, serverVersion, registry, mock(ServerHealthService.class),
            cachedGoPartials, fullConfigSaveMergeFlow, fullConfigSaveNormalFlow);

    dataSource.upgradeIfNecessary();
    CachedGoConfig cachedGoConfig = new CachedGoConfig(serverHealthService, dataSource, mock(CachedGoPartials.class), null, null);
    cachedGoConfig.loadConfigIfNull();
    goConfigDao = new GoConfigDao(cachedGoConfig);
    configHelper.load();
    configHelper.usingCruiseConfigDao(goConfigDao);
    GoConfigWatchList configWatchList = new GoConfigWatchList(cachedGoConfig, mock(GoConfigService.class));
    ConfigElementImplementationRegistry configElementImplementationRegistry = new ConfigElementImplementationRegistry(new NoPluginsInstalled());
    GoConfigPluginService configPluginService = new GoConfigPluginService(mock(ConfigRepoExtension.class), new ConfigCache(), configElementImplementationRegistry, cachedGoConfig);
    repoConfig = new ConfigRepoConfig(new GitMaterialConfig("url"), "plugin");
    configHelper.addConfigRepo(repoConfig);
    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(new UsernamePasswordAuthenticationToken(new User("loser_boozer", "pass", true, true, true, true, new GrantedAuthority[]{}), null));
}
 
开发者ID:gocd,项目名称:gocd,代码行数:39,代码来源:GoFileConfigDataSourceTest.java

示例8: shouldUse_UserFromSession_asConfigModifyingUserWhenNoneGiven

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
@Test
public void shouldUse_UserFromSession_asConfigModifyingUserWhenNoneGiven() throws GitAPIException, IOException {
    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(new UsernamePasswordAuthenticationToken(new User("loser_boozer", "pass", true, true, true, true, new GrantedAuthority[]{}), null));
    goConfigDao.updateMailHost(getMailHost("mailhost.local"));

    CruiseConfig cruiseConfig = goConfigDao.load();
    GoConfigRevision revision = configRepository.getRevision(cruiseConfig.getMd5());
    assertThat(revision.getUsername(), is("loser_boozer"));
}
 
开发者ID:gocd,项目名称:gocd,代码行数:11,代码来源:GoFileConfigDataSourceTest.java

示例9: shouldIdentifyLoggedInUserAsModifyingUser_WhenNoModifyingUserIsGiven

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
@Test
public void shouldIdentifyLoggedInUserAsModifyingUser_WhenNoModifyingUserIsGiven() {
    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(new UsernamePasswordAuthenticationToken(new User("loser_boozer", "pass", true, true, true, true, new GrantedAuthority[]{}), null));
    ConfigModifyingUser user = new ConfigModifyingUser();
    assertThat(user.getUserName(), is("loser_boozer"));
}
 
开发者ID:gocd,项目名称:gocd,代码行数:8,代码来源:ConfigModifyingUserTest.java

示例10: doFilterHttp

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
protected void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    User user = getUser(request);
    if(user.getId() != NOT_PERSISTED && UserHelper.getUserId(request) == null){
        UserHelper.setUserId(request, user.getId());
    }
    
    if (!user.isEnabled()) {
        SecurityContext context = SecurityContextHolder.getContext();
        request.getSession().setAttribute(SPRING_SECURITY_LAST_EXCEPTION_KEY, new DisabledException("Your account has been disabled by the administrator"));
        request.setAttribute(SESSION_DENIED, true);
        context.setAuthentication(null);
        UserHelper.setUserId(request, null);
    }
    chain.doFilter(request, response);
}
 
开发者ID:gocd,项目名称:gocd,代码行数:16,代码来源:UserEnabledCheckFilter.java

示例11: getUserName

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
public static Username getUserName() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    if (securityContext != null && securityContext.getAuthentication() != null) {
        return getUserName(securityContext.getAuthentication());
    }
    return ANONYMOUS;
}
 
开发者ID:gocd,项目名称:gocd,代码行数:8,代码来源:UserHelper.java

示例12: matchesRole

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
private static boolean matchesRole(String role) {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    if (securityContext != null && securityContext.getAuthentication() != null) {
        return matchesRole(securityContext.getAuthentication(), role);
    }
    return false;
}
 
开发者ID:gocd,项目名称:gocd,代码行数:8,代码来源:UserHelper.java

示例13: setup

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
@Before public void setup() throws Exception {
    dataSource.reloadEveryTime();
    configHelper.usingCruiseConfigDao(goConfigDao);
    configHelper.onSetUp();
    response = new MockHttpServletResponse();
    configHelper.enableSecurity();
    configHelper.addAdmins("admin");
    originalSecurityContext = SecurityContextHolder.getContext();
    setCurrentUser("admin");
}
 
开发者ID:gocd,项目名称:gocd,代码行数:11,代码来源:GoConfigAdministrationControllerIntegrationTest.java

示例14: shouldRerunJobsWithUserAsApprover

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
@Test
public void shouldRerunJobsWithUserAsApprover() throws Exception {
    Pipeline pipeline = fixture.createdPipelineWithAllStagesPassed();
    Stage oldStage = pipeline.getStages().byName(fixture.devStage);

    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(new UsernamePasswordAuthenticationToken(new User("loser", "pass", true, true, true, true, new GrantedAuthority[]{}), null));
    HttpOperationResult result = new HttpOperationResult();
    Stage newStage = scheduleService.rerunJobs(oldStage, a("foo", "foo3"), result);
    Stage loadedLatestStage = dbHelper.getStageDao().findStageWithIdentifier(newStage.getIdentifier());
    assertThat(loadedLatestStage.getApprovedBy(), is("loser"));
    assertThat(oldStage.getApprovedBy(), is(not("loser")));
    assertThat(result.canContinue(), is(true));
}
 
开发者ID:gocd,项目名称:gocd,代码行数:15,代码来源:ScheduleStageTest.java

示例15: beforeAll

import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
@BeforeClass
public static void beforeAll() throws Exception {
    originalContext = SecurityContextHolder.getContext();
}
 
开发者ID:gocd,项目名称:gocd,代码行数:5,代码来源:OauthAuthenticationFilterTest.java


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