Example usage for org.springframework.security.core.userdetails User getUsername

List of usage examples for org.springframework.security.core.userdetails User getUsername

Introduction

In this page you can find the example usage for org.springframework.security.core.userdetails User getUsername.

Prototype

public String getUsername() 

Source Link

Usage

From source file:com.jayway.restassured.module.mockmvc.http.SecuredController.java

@RequestMapping(value = "/springSecurityGreeting", method = GET)
public @ResponseBody Greeting greeting(
        @RequestParam(value = "name", required = false, defaultValue = "World") String name) {
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (user == null || !user.getUsername().equals("authorized_user")) {
        throw new IllegalArgumentException("Not authorized");
    }/*from   w ww  .  j  ava2 s .c om*/

    return new Greeting(counter.incrementAndGet(), String.format(template, name));
}

From source file:co.edu.utb.softeng.springtodos.service.security.MyUserDetailsService.java

private User buildSpringUser(co.edu.utb.softeng.springtodos.entity.security.User user,
        List<GrantedAuthority> authorities) {
    return new User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
}

From source file:com.ar.dev.tierra.api.config.security.CustomLogoutSuccessHandler.java

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    String token = request.getHeader(HEADER_AUTHORIZATION);
    if (token != null && token.startsWith(BEARER_AUTHENTICATION)) {
        OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token.split(" ")[1]);
        if (oAuth2AccessToken != null) {
            Calendar cal = Calendar.getInstance();
            Date date = cal.getTime();
            Map<String, Object> map = oAuth2AccessToken.getAdditionalInformation();
            OAuth2Authentication auth = tokenStore.readAuthentication(oAuth2AccessToken);
            User user = (User) auth.getPrincipal();
            Usuarios u = usuariosDAO.findUsuarioByUsername(user.getUsername());
            u.setUltimaConexion(date);/*from www .j  av  a 2s  .co  m*/
            usuariosDAO.updateUsuario(u);
            tokenStore.removeAccessToken(oAuth2AccessToken);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:com.mysample.springbootsample.security.CustomUserDetailsService.java

private User buildUserForAuthentication(com.mysample.springbootsample.domain.User user,
        List<GrantedAuthority> authorities) {

    return new User(user.getUsername(), user.getPassword(), true, true, true, true, authorities);
}

From source file:cn.cuizuoli.gotour.service.CategoryService.java

/**
 * addCategory//w w  w . ja v a2 s  . com
 * @param info
 * @param user
 */
@Transactional
public void addCategory(Info info, User user) {
    info.setInfoType(InfoType.CATEGORY.getCode());
    info.setCreator(user.getUsername());
    info.setModifier(user.getUsername());
    infoRepository.insert(info);
}

From source file:sample.web.account.AccountController.java

@RequestMapping(value = "/edit", method = RequestMethod.GET)
public String edit(Model model, @AuthenticationPrincipal User user) {
    Account account = accountService.getAccount(user.getUsername());
    EditAccountForm accountForm = new EditAccountForm();
    BeanUtils.copyProperties(account, accountForm, "password");
    return modelAndViewForEdit(model, accountForm, user);
}

From source file:sample.web.account.AccountController.java

private String modelAndViewForEdit(Model model, EditAccountForm accountForm, User user) {
    model.addAttribute(accountForm);/*ww  w .j av a2s  .  c om*/
    model.addAttribute("username", user.getUsername());
    model.addAttribute("languageList", Constants.LANGUAGE_LIST);
    model.addAttribute("categoryList", Constants.CATEGORY_LIST);
    return "account/edit";
}

From source file:com.ar.dev.tierra.api.config.security.CustomTokenEnhancer.java

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    User user = (User) authentication.getPrincipal();
    final Map<String, Object> additionalInfo = new HashMap<>();
    String hashedUsername = passwordEncoder.encode(user.getUsername());
    additionalInfo.put("role", authentication.getAuthorities());
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}

From source file:com.artivisi.belajar.restful.ui.controller.HomepageController.java

@RequestMapping("/homepage/userinfo")
@ResponseBody/* w ww. j  a  va  2s. co m*/
public Map<String, String> userInfo() {
    Map<String, String> hasil = new HashMap<String, String>();

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        Object principal = auth.getPrincipal();
        if (principal != null && User.class.isAssignableFrom(principal.getClass())) {
            User u = (User) principal;
            hasil.put("user", u.getUsername());
            com.artivisi.belajar.restful.domain.User ux = belajarRestfulService
                    .findUserByUsername(u.getUsername());
            if (ux != null || ux.getRole() != null || ux.getRole().getName() != null) {
                hasil.put("group", ux.getRole().getName());
            } else {
                hasil.put("group", "undefined");
            }
        }
    }

    return hasil;
}

From source file:com.netflix.genie.web.security.x509.X509UserDetailsServiceUnitTests.java

/**
 * Make sure if everything is present and proper the service returns a valid user.
 *
 * @throws UsernameNotFoundException on any error
 *///  w w w  .  j  a  v a  2  s. c  om
@Test
public void canAuthenticate() throws UsernameNotFoundException {
    final String username = UUID.randomUUID().toString();
    final String role1 = UUID.randomUUID().toString();
    final String role2 = UUID.randomUUID().toString();
    Mockito.when(this.token.getPrincipal()).thenReturn(username + ":" + role1 + "," + role2);
    final UserDetails userDetails = this.service.loadUserDetails(this.token);

    if (!(userDetails instanceof User)) {
        throw new UsernameNotFoundException("Invalid return type");
    }

    final User user = (User) userDetails;
    Assert.assertThat(user.getUsername(), Matchers.is(username));
    Assert.assertThat(user.getPassword(), Matchers.is("NA"));
    Assert.assertThat(user.getAuthorities().size(), Matchers.is(3));
    Assert.assertThat(user.getAuthorities(),
            Matchers.hasItems(new SimpleGrantedAuthority("ROLE_USER"),
                    new SimpleGrantedAuthority("ROLE_" + role1.toUpperCase()),
                    new SimpleGrantedAuthority("ROLE_" + role2.toUpperCase())));
}