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


Java SecurityContext类代码示例

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


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

示例1: status

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
@GetMapping(value = "/api/session", produces = CONTENT_TYPE)
public String status() {
    logger.info("状态获取: 正在检测登入状态");

    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        String username = authentication.getName();
        if (!"anonymousUser".equals(username)) {
            logger.info("状态获取: 检测到已登入用户, username={}", username);
            JSONObject object = new JSONObject();
            object.put("success", true);
            object.put("username", username);
            putAuthority(object, authentication);
            return object.toString();
        } else {
            logger.info("状态获取: 检测到匿名用户");
            return booleanResult(false);
        }
    } else {
        logger.info("状态获取: 未检测到已登入状态");
        return booleanResult(false);
    }
}
 
开发者ID:mingzuozhibi,项目名称:mzzb-server,代码行数:25,代码来源:SessionController.java

示例2: getCurrentUser

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
/**
 * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
 * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
 * application Spring Security usernames are email addresses).
 */
@Override
public CalendarUser getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        return null;
    }

    CalendarUser user = (CalendarUser) authentication.getPrincipal();
    String email = user.getEmail();
    if (email == null) {
        return null;
    }
    CalendarUser result = calendarService.findUserByEmail(email);
    if (result == null) {
        throw new IllegalStateException(
                "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
    }

    logger.info("CalendarUser: {}", result);
    return result;
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:28,代码来源:SpringSecurityUserContext.java

示例3: getCurrentUser

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();

        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:28,代码来源:SpringSecurityUserContext.java

示例4: getCurrentUser

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:27,代码来源:SpringSecurityUserContext.java

示例5: getCurrentUser

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
/**
 * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
 * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
 * application Spring Security usernames are email addresses).
 */
@Override
public CalendarUser getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        return null;
    }
    CalendarUser user = (CalendarUser) authentication.getPrincipal();
    String email = user.getEmail();        if (email == null) {
        return null;
    }
    CalendarUser result = calendarService.findUserByEmail(email);
    if (result == null) {
        throw new IllegalStateException(
                "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
    }

    logger.info("CalendarUser: {}", result);
    return result;
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:26,代码来源:SpringSecurityUserContext.java

示例6: testDoFilterInternalWithNoOrgType

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
@Test
public void testDoFilterInternalWithNoOrgType() throws IOException, ServletException {
	JwtPayloadHelper payload = new JwtPayloadHelper()
			.withName(JwtAuthorizationFilter.ORG_NAME);

	request.addHeader("Authorization", JwtTestHelper.createJwt(payload));
	JwtAuthorizationFilter testJwtAuthFilter = new JwtAuthorizationFilter(authenticationManager);

	PowerMockito.mockStatic(SecurityContextHolder.class);
	SecurityContext mockSecurityContext = PowerMockito.mock(SecurityContext.class);

	PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(mockSecurityContext);

	testJwtAuthFilter.doFilterInternal(request, response, filterChain);

	verify(filterChain, times(1)).doFilter(any(MockHttpServletRequest.class), any(MockHttpServletResponse.class));
	verify(SecurityContextHolder.getContext(), times(0)).setAuthentication(any(UsernamePasswordAuthenticationToken.class));
}
 
开发者ID:CMSgov,项目名称:qpp-conversion-tool,代码行数:19,代码来源:JwtAuthorizationFilterTest.java

示例7: verifyResolverSecurityContext

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
@Test
public void verifyResolverSecurityContext() throws Exception {
    final UserDetails ud = mock(UserDetails.class);
    when(ud.getUsername()).thenReturn("pid");
    final Authentication authn = mock(Authentication.class);
    when(authn.getPrincipal()).thenReturn(ud);
    final SecurityContext securityContext = mock(SecurityContext.class);
    when(securityContext.getAuthentication()).thenReturn(authn);
    SecurityContextHolder.setContext(securityContext);

    final TicketOrCredentialPrincipalResolver res =
            new TicketOrCredentialPrincipalResolver(getCentralAuthenticationService());
    final JoinPoint jp = mock(JoinPoint.class);
    when(jp.getArgs()).thenReturn(new Object[]{ud});

    final String result = res.resolveFrom(jp, null);
    assertNotNull(result);
    assertEquals(result, ud.getUsername());
}
 
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:20,代码来源:TicketOrCredentialPrincipalResolverTests.java

示例8: findFromSession

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
public UserAuthDTO findFromSession(HttpSession session) {
    SecurityContext securityContext = (SecurityContext) session
            .getAttribute("SPRING_SECURITY_CONTEXT");

    if (securityContext == null) {
        return null;
    }

    Authentication authentication = securityContext.getAuthentication();

    if (authentication == null) {
        return null;
    }

    Object principal = authentication.getPrincipal();

    if (!(principal instanceof UserAuthDTO)) {
        return null;
    }

    return ((UserAuthDTO) principal);
}
 
开发者ID:zhaojunfei,项目名称:lemon,代码行数:23,代码来源:InternalUserAuthConnectorImpl.java

示例9: alimenteSecurityUserCptMin

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
/**
 * Alimente la session pour un compte local
 * 
 * @param cptMin
 *            le compte a minima a connecter
 */
public void alimenteSecurityUserCptMin(CompteMinima cptMin) {
	SecurityUser user = (SecurityUser) getCurrentUser();
	if (user != null) {
		List<GrantedAuthority> authoritiesListe = new ArrayList<GrantedAuthority>();
		SimpleGrantedAuthority sga = new SimpleGrantedAuthority(ConstanteUtils.ROLE_CANDIDAT);
		authoritiesListe.add(sga);

		SecurityUserCandidat securityUserCandidat = new SecurityUserCandidat(user.getUsername(),
				user.getDisplayName(), authoritiesListe, cptMin.getIdCptMin(), cptMin.getNumDossierOpiCptMin(),
				cptMin.getTemValidCptMin(), cptMin.getTemValidMailCptMin(), null);
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
				securityUserCandidat, securityUserCandidat.getUsername(), securityUserCandidat.getAuthorities());
		Authentication authentication = authenticationManagerCandidat.authenticate(authRequest);
		SecurityContext context = SecurityContextHolder.createEmptyContext();
		context.setAuthentication(authentication);
		SecurityContextHolder.setContext(context);
		UI.getCurrent().getSession().getSession()
				.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
	}
}
 
开发者ID:EsupPortail,项目名称:esup-ecandidat,代码行数:27,代码来源:UserController.java

示例10: createSecurityContext

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
public SecurityContext createSecurityContext(pingis.entities.User customUser) {
  SecurityContext context = SecurityContextHolder.createEmptyContext();

  TmcUserDto principal = new TmcUserDto(Long.toString(customUser.getId()),
          customUser.getName(),
          TEST_EMAIL,
          customUser.isAdministrator());

  Authentication authentication = new UsernamePasswordAuthenticationToken(principal,
          "password",
          principal.getAuthorities());

  context.setAuthentication(authentication);

  return context;
}
 
开发者ID:tdd-pingis,项目名称:tdd-pingpong,代码行数:17,代码来源:WithMockCustomUserSecurityContextFactory.java

示例11: inspect

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
/**
 * @see org.atmosphere.cpr.AtmosphereInterceptor#inspect(org.atmosphere.cpr.AtmosphereResource)
 */
@Override
public Action inspect(final AtmosphereResource atmosphereResource) {
	try {
		SecurityContext context = (SecurityContext) atmosphereResource.getRequest().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
		final Authentication auth = context.getAuthentication();
		if (auth instanceof Authentication) {
			MDC.put(UserMdcServletFilter.USER_KEY, auth.getName());
			logger.trace("Username set in MDC");
		}	
	} catch (final NullPointerException e) {}
	return Action.CONTINUE;
}
 
开发者ID:EsupPortail,项目名称:esup-ecandidat,代码行数:16,代码来源:RecoverSecurityContextAtmosphereInterceptor.java

示例12: getCurrentUserLogin

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
/**
 * Get the login of the current user.
 *
 * @return the login of the current user
 */
public static String getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}
 
开发者ID:mraible,项目名称:devoxxus-jhipster-microservices-demo,代码行数:20,代码来源:SecurityUtils.java

示例13: testIsAuthenticated

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
@Test
public void testIsAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isTrue();
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:9,代码来源:SecurityUtilsUnitTest.java

示例14: testIsCurrentUserInRole

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
@Test
public void testIsCurrentUserInRole() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities));
    SecurityContextHolder.setContext(securityContext);

    assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.USER)).isTrue();
    assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)).isFalse();
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:12,代码来源:SecurityUtilsUnitTest.java

示例15: getCurrentUserJWT

import org.springframework.security.core.context.SecurityContext; //导入依赖的package包/类
/**
 * Get the JWT of the current user.
 *
 * @return the JWT of the current user
 */
public static String getCurrentUserJWT() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null && authentication.getCredentials() instanceof String) {
        return (String) authentication.getCredentials();
    }
    return null;
}
 
开发者ID:deepu105,项目名称:spring-io,代码行数:14,代码来源:SecurityUtils.java


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