本文整理汇总了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();
}
示例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;
}
示例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)));
}
示例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();
}
}
示例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"));
}
示例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);
}
示例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));
}
示例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"));
}
示例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"));
}
示例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);
}
示例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;
}
示例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;
}
示例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");
}
示例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));
}
示例15: beforeAll
import org.springframework.security.context.SecurityContextHolder; //导入方法依赖的package包/类
@BeforeClass
public static void beforeAll() throws Exception {
originalContext = SecurityContextHolder.getContext();
}