當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。