Java 类org.springframework.security.core.context.SecurityContext 实例源码

项目:mzzb-server    文件:SessionController.java   
@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);
    }
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
     * 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;
    }
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
     * 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;
    }
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:qpp-conversion-tool    文件:JwtAuthorizationFilterTest.java   
@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));
}
项目:springboot-shiro-cas-mybatis    文件:TicketOrCredentialPrincipalResolverTests.java   
@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());
}
项目:lemon    文件:InternalUserAuthConnectorImpl.java   
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);
}
项目:esup-ecandidat    文件:UserController.java   
/**
 * 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);
    }
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
     * 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;
    }
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:tdd-pingpong    文件:WithMockCustomUserSecurityContextFactory.java   
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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
 * 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;
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
     * 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;
    }
项目:esup-ecandidat    文件:RecoverSecurityContextAtmosphereInterceptor.java   
/**
 * @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;
}
项目:devoxxus-jhipster-microservices-demo    文件:SecurityUtils.java   
/**
 * 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;
}
项目:xm-ms-config    文件:SecurityUtils.java   
/**
 * 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;
}
项目:xm-uaa    文件:SecurityUtilsUnitTest.java   
@Test
public void testIsAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isTrue();
}
项目:xm-uaa    文件:SecurityUtilsUnitTest.java   
@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();
}
项目:spring-io    文件:SecurityUtils.java   
/**
 * 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;
}
项目:Microservices-with-JHipster-and-Spring-Boot    文件:SecurityUtilsUnitTest.java   
@Test
public void testAnonymousIsNotAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isFalse();
}
项目:Spring-Security-Third-Edition    文件:SpringSecurityUserContext.java   
/**
     * 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();

//        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;
    }
项目:jhipster-microservices-example    文件:SecurityUtilsUnitTest.java   
@Test
public void testIsAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isTrue();
}
项目:klask-io    文件:SecurityUtilsUnitTest.java   
@Test
public void testAnonymousIsNotAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isFalse();
}
项目:jhipster-microservices-example    文件:SecurityUtilsUnitTest.java   
@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();
}
项目:jhipster-microservices-example    文件:ExceptionTranslatorTest.java   
@Test
public void processParameterizedValidationErrorTest() throws Exception {
    // These lines will throw the wanted exception
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenThrow(new CustomParameterizedException(null));
    SecurityContextHolder.setContext(securityContext);

    MvcResult res = mock.perform(get("/api/account"))
        .andExpect(status().isBadRequest())
        .andReturn();

    assertThat(res.getResolvedException(), instanceOf(CustomParameterizedException.class));
}
项目:jhipster-microservices-example    文件:ExceptionTranslatorTest.java   
@Test
public void processAccessDeniedExceptionTest() throws Exception {
    // These lines will throw the wanted exception
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenThrow(new AccessDeniedException(null));
    SecurityContextHolder.setContext(securityContext);

    MvcResult res = mock.perform(get("/api/account"))
        .andExpect(status().isForbidden())
        .andReturn();

    assertThat(res.getResolvedException(), instanceOf(AccessDeniedException.class));
}
项目:spring-io    文件:SecurityUtils.java   
/**
 * Check if a user is authenticated.
 *
 * @return true if the user is authenticated, false otherwise
 */
public static boolean isAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null) {
        return authentication.getAuthorities().stream()
            .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS));
    }
    return false;
}
项目:jhipster-microservices-example    文件:SecurityUtils.java   
/**
 * 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;
}