Example usage for org.springframework.security.core Authentication getPrincipal

List of usage examples for org.springframework.security.core Authentication getPrincipal

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getPrincipal.

Prototype

Object getPrincipal();

Source Link

Document

The identity of the principal being authenticated.

Usage

From source file:eu.supersede.fe.rest.GadgetRest.java

@RequestMapping("")
public List<UserGadget> getUserAuthenticatedApplicationsGadgets(Authentication auth) {
    DatabaseUser user = (DatabaseUser) auth.getPrincipal();
    List<UserGadget> gadgets = userGadgets.findByUserIdOrderByGadgetIdAsc(user.getUserId());
    return gadgets;
}

From source file:at.ac.univie.isc.asio.security.HttpMethodRestrictionFilterTest.java

@Test
public void should_keep_other_token_properties() throws Exception {
    final TestingAuthenticationToken token = new TestingAuthenticationToken("user", "secret",
            Collections.<GrantedAuthority>singletonList(Permission.INVOKE_UPDATE));
    token.setDetails("details");
    setAuthentication(token);/*www .j  a  v  a  2  s .  co m*/
    request.setMethod(HttpMethod.GET.name());
    subject.doFilter(request, response, chain);
    final Authentication filtered = getAuthentication();
    assertThat(filtered.getPrincipal(), equalTo(token.getPrincipal()));
    assertThat(filtered.getCredentials(), equalTo(token.getCredentials()));
    assertThat(filtered.getDetails(), equalTo(token.getDetails()));
}

From source file:com.tcloud.bee.key.server.mvc.controller.HomeController.java

/**
 * Simple controller for "/" that returns a Thymeleaf view.
 *//*from ww  w.j  a va  2  s.  c o m*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    logger.info("Welcome home! the client locale is " + locale.toString());

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    logger.trace("Authentication principal: {}", auth.getPrincipal());
    logger.trace("Authentication name: {}", auth.getName());

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate);
    // model.addAttribute("echoService", echoService);
    model.addAttribute("someItems", new String[] { "one", "two", "three" });

    return "home";
}

From source file:org.cloudfoundry.identity.uaa.login.ResetPasswordControllerIntegrationTests.java

@Test
public void testResettingAPassword() throws Exception {
    mockUaaServer.expect(requestTo("http://localhost:8080/uaa/password_change")).andExpect(method(POST))
            .andExpect(jsonPath("$.code").value("the_secret_code"))
            .andExpect(jsonPath("$.new_password").value("secret"))
            .andRespond(withSuccess(/*  w  w w  . java  2s .  c o  m*/
                    "{" + "\"user_id\":\"newly-created-user-id\"," + "\"username\":\"user@example.com\"" + "}",
                    APPLICATION_JSON));

    MockHttpServletRequestBuilder post = post("/reset_password.do").param("code", "the_secret_code")
            .param("email", "user@example.com").param("password", "secret")
            .param("password_confirmation", "secret");

    MvcResult mvcResult = mockMvc.perform(post).andExpect(status().isFound()).andExpect(redirectedUrl("home"))
            .andReturn();

    SecurityContext securityContext = (SecurityContext) mvcResult.getRequest().getSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    Authentication authentication = securityContext.getAuthentication();
    Assert.assertThat(authentication.getPrincipal(), instanceOf(UaaPrincipal.class));
    UaaPrincipal principal = (UaaPrincipal) authentication.getPrincipal();
    Assert.assertThat(principal.getId(), equalTo("newly-created-user-id"));
    Assert.assertThat(principal.getName(), equalTo("user@example.com"));
    Assert.assertThat(principal.getEmail(), equalTo("user@example.com"));
    Assert.assertThat(principal.getOrigin(), equalTo(Origin.UAA));
}

From source file:architecture.user.security.authentication.impl.DefaultAuthenticationProvider.java

public User getUser() {
    try {// ww w  . j a  v  a  2 s . com
        Authentication authen = getAuthentication();
        Object obj = authen.getPrincipal();
        if (obj instanceof ExtendedUserDetails)
            return ((ExtendedUserDetails) obj).getUser();
    } catch (Exception ignore) {
    }
    return createAnonymousUser();
}

From source file:architecture.user.security.authentication.impl.DefaultAuthenticationProvider.java

public AuthToken getAuthToken() {
    try {//from   w  w w  .j  ava2  s  .  com
        Authentication authen = getAuthentication();
        Object obj = authen.getPrincipal();
        if (obj instanceof AuthToken)
            return (AuthToken) obj;
    } catch (Exception ignore) {
    }
    return createAnonymousUser();
}

From source file:cn.cuizuoli.gotour.resolver.UserInfoMethodArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    Class<?> paramType = parameter.getParameterType();
    if (User.class.isAssignableFrom(paramType)) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof User) {
                return (User) principal;
            }//from  w  w  w .  j av  a2s  .  co m
        }
    }
    return null;
}

From source file:org.wallride.service.AuthorizedUserDetailsService.java

@Transactional(readOnly = false)
@Override//from w ww.  j  a v a2  s . c  om
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    AuthorizedUser authorizedUser = (AuthorizedUser) authentication.getPrincipal();
    userRepository.updateLastLoginTime(authorizedUser.getId(), new Date());

    logger.info("\"{}\" logged in. IP: [{}]", authorizedUser.toString(), request.getRemoteAddr());

    super.onAuthenticationSuccess(request, response, authentication);
}

From source file:org.elasticstore.server.service.impl.ElasticSearchAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    final String username = authentication.getName();
    return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
            authentication.getCredentials());
}

From source file:org.jtalks.poulpe.security.AclAwareDecisionVoter.java

/**
 * Since SpringSecurity by default thinks of anonymous user as the one that is authenticated, we need to check a bit
 * more. First we check whether she's authenticated by SpringSecurity per se, and then we check whether {@link
 * UserDetails} is created which indicates that it's not an anonymous user.
 *
 * @param authentication to check whether it's an authenticated user and that it's not anonymous
 * @return true if the user is authenticated by SpringSecurity as an existing user, false if it's an anonymous or
 *         not authenticated user/*w  w  w  .  ja v a  2 s  .  c o m*/
 */
private boolean authenticatedAsUser(Authentication authentication) {
    return authentication.isAuthenticated() && authentication.getPrincipal() instanceof UserDetails;
}