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:org.springframework.security.jackson2.UserDeserializerTests.java

@Test
public void deserializeUserWithClassIdInAuthoritiesTest() throws IOException {
    String userJson = "{\"@class\": \"org.springframework.security.core.userdetails.User\", "
            + "\"username\": \"user\", \"password\": \"pass\", \"accountNonExpired\": true, "
            + "\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"enabled\": true, "
            + "\"authorities\": [\"java.util.Collections$UnmodifiableSet\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
    User user = buildObjectMapper().readValue(userJson, User.class);
    assertThat(user).isNotNull();/*from  w w  w .  j  a  va2 s  . co  m*/
    assertThat(user.getUsername()).isEqualTo("user");
    assertThat(user.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}

From source file:it.smartcommunitylab.aac.controller.TokenIntrospectionController.java

@ApiOperation(value = "Get token metadata")
@RequestMapping(method = RequestMethod.POST, value = "/token_introspection")
public ResponseEntity<AACTokenIntrospection> getTokenInfo(@RequestParam String token) {
    AACTokenIntrospection result = new AACTokenIntrospection();

    try {// ww w .  j av a2 s .c o m
        OAuth2Authentication auth = resourceServerTokenServices.loadAuthentication(token);

        OAuth2AccessToken storedToken = tokenStore.getAccessToken(auth);

        String clientId = auth.getOAuth2Request().getClientId();

        String userName = null;
        String userId = null;
        boolean applicationToken = false;

        if (auth.getPrincipal() instanceof User) {
            User principal = (User) auth.getPrincipal();
            userId = principal.getUsername();
        } else {
            ClientDetailsEntity client = clientDetailsRepository.findByClientId(clientId);
            applicationToken = true;
            userId = "" + client.getDeveloperId();
        }
        userName = userManager.getUserInternalName(Long.parseLong(userId));
        String localName = userName.substring(0, userName.lastIndexOf('@'));
        String tenant = userName.substring(userName.lastIndexOf('@') + 1);

        result.setUsername(localName);
        result.setClient_id(clientId);
        result.setScope(StringUtils.collectionToDelimitedString(auth.getOAuth2Request().getScope(), " "));
        result.setExp((int) (storedToken.getExpiration().getTime() / 1000));
        result.setIat(result.getExp() - storedToken.getExpiresIn());
        result.setIss(issuer);
        result.setNbf(result.getIat());
        result.setSub(userId);
        result.setAud(clientId);
        // jti is not supported in this form

        // only bearer tokens supported
        result.setToken_type(OAuth2AccessToken.BEARER_TYPE);
        result.setActive(true);

        result.setAac_user_id(userId);
        result.setAac_grantType(auth.getOAuth2Request().getGrantType());
        result.setAac_applicationToken(applicationToken);
        result.setAac_am_tenant(tenant);
    } catch (Exception e) {
        logger.error("Error getting info for token: " + e.getMessage());
        result = new AACTokenIntrospection();
        result.setActive(false);
    }
    return ResponseEntity.ok(result);
}

From source file:org.springframework.security.jackson2.UserDeserializerTests.java

@Test
public void deserializeUserWithNullPasswordNoAuthorityTest() throws IOException {
    String userJsonWithoutPasswordString = "{\"@class\": \"org.springframework.security.core.userdetails.User\", "
            + "\"username\": \"user\", \"accountNonExpired\": true, "
            + "\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"enabled\": true, "
            + "\"authorities\": [\"java.util.HashSet\", []]}";
    ObjectMapper mapper = buildObjectMapper();
    User user = mapper.readValue(userJsonWithoutPasswordString, User.class);
    assertThat(user).isNotNull();/* www.  ja  v  a 2  s .com*/
    assertThat(user.getUsername()).isEqualTo("user");
    assertThat(user.getPassword()).isEqualTo("");
    assertThat(user.getAuthorities()).hasSize(0);
    assertThat(user.isEnabled()).isEqualTo(true);
}

From source file:hu.bme.iit.quiz.controller.QuizController.java

/**
 * *************************************************
 * URL: /quiz/start/{innerkey}/*from ww w . j  ava  2  s .  c  om*/
 * **************************************************
 */
@Secured(value = { "isAuthenticated()" })
@RequestMapping(value = "/quiz/stop/{innerkey}", method = RequestMethod.GET)
public String stopQuiz(@PathVariable String innerkey) {
    try {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        quizService.stopQuizByInnerKeyForUser(innerkey, user.getUsername());

        return "redirect:/my-quizzes";
    } catch (Exception e) {
        logger.error(e);
        e.printStackTrace();
        return "redirect:/my-quizzes?start-error";
    }
}

From source file:org.hspconsortium.platform.authorization.launchcontext.LaunchOrchestrationEndpoint.java

@RequestMapping(value = "/Launch", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void handleLaunchRequest(HttpServletRequest request, HttpServletResponse response,
        @RequestBody String jsonString) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {//w  ww. j  av  a2  s .  c o m

        HttpSession sessionObj = request.getSession();

        JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
        JsonObject jsonParams = json.get("parameters").getAsJsonObject();

        JsonElement jsonLaunchId = jsonParams.get("launch_id");
        String launchId = null;
        String patientId = null;
        if (jsonLaunchId != null) {
            launchId = jsonLaunchId.getAsString();
        }
        JsonElement jsonPatientId = jsonParams.get("patient");
        if (jsonPatientId != null) {
            patientId = jsonPatientId.getAsString();
        }

        LaunchContext launchContext = createLaunchContext(launchId, patientId);
        LaunchContextHolder.addLaunchContext(launchContext);

        SecurityContext securityContext = (SecurityContext) sessionObj.getAttribute("SPRING_SECURITY_CONTEXT");
        if (securityContext != null) {
            Authentication authentication = securityContext.getAuthentication();
            User user = (User) authentication.getPrincipal();
            jsonMap.put("username", user.getUsername());
        } else { //TODO this shouldn't happen when we turn authentication back on
            jsonMap.put("username", "none");
        }

        //TODO: get actual values
        jsonMap.put("created_by", "hspc_platform");
        jsonMap.put("launch_id", launchContext.getLaunchId());
        jsonMap.put("created_at", new Date().toString());
        Map<String, Object> retMap = new Gson().fromJson(json.get("parameters"),
                new TypeToken<HashMap<String, Object>>() {
                }.getType());
        jsonMap.put("parameters", retMap);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    response.setHeader("Content-Type", "application/json;charset=utf-8");
    try {
        response.getWriter().write(new Gson().toJson(jsonMap));
    } catch (IOException io_ex) {
        throw new RuntimeException(io_ex);
    }
}

From source file:ch.silviowangler.dox.security.DoxUserDetailService.java

@Override
@Transactional(readOnly = true)//from   w  w  w. ja va  2s  .com
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    logger.trace("Trying create user details for user '{}'", username);

    final DoxUser user = userRepository.findByUsername(username);

    if (user == null) {
        logger.info("No such user with name '{}'", username);
        throw new UsernameNotFoundException("No such user " + username);
    }
    Collection<SimpleGrantedAuthority> authorities = Sets.newHashSet();

    for (Role role : user.getRoles()) {
        final String roleName = "ROLE_" + role.getName();
        logger.debug("Adding role {}", roleName);
        authorities.add(new SimpleGrantedAuthority(roleName));
        for (ch.silviowangler.dox.domain.security.GrantedAuthority grantedAuthority : role
                .getGrantedAuthorities()) {
            authorities.add(new SimpleGrantedAuthority(grantedAuthority.getName()));
        }
    }
    User springSecurityUser = new User(user.getUsername(), user.getPassword(), authorities);

    logger.trace("User '{}' has these granted authorities '{}'", springSecurityUser.getUsername(),
            springSecurityUser.getAuthorities());
    return springSecurityUser;
}

From source file:org.smartplatforms.oauth2.LaunchOrchestrationEndpoint.java

@RequestMapping(value = "/Launch", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void handleLaunchRequest(HttpServletRequest request, HttpServletResponse response,
        @RequestBody String jsonString) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {/*  ww  w .  ja va 2 s. com*/

        HttpSession sessionObj = request.getSession();

        JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
        JsonObject jsonParams = json.get("parameters").getAsJsonObject();

        JsonElement jsonLaunchId = jsonParams.get("launch_id");
        String launchId = null;
        if (jsonLaunchId != null) {
            launchId = jsonLaunchId.getAsString();
        }

        Map<String, Object> launchContextParams = buildLaunchContextParamsMap(jsonParams);

        LaunchContext launchContext = createLaunchContext(launchId, launchContextParams);
        LaunchContextHolder.addLaunchContext(launchContext);

        SecurityContext securityContext = (SecurityContext) sessionObj.getAttribute("SPRING_SECURITY_CONTEXT");
        if (securityContext != null) {
            Authentication authentication = securityContext.getAuthentication();
            User user = (User) authentication.getPrincipal();
            jsonMap.put("username", user.getUsername());
        } else { //TODO this shouldn't happen when we turn authentication back on
            jsonMap.put("username", "none");
        }

        //TODO: get actual values
        jsonMap.put("created_by", "hspc_platform");
        jsonMap.put("launch_id", launchContext.getLaunchId());
        jsonMap.put("created_at", new Date().toString());
        Map<String, Object> retMap = new Gson().fromJson(json.get("parameters"),
                new TypeToken<HashMap<String, Object>>() {
                }.getType());
        jsonMap.put("parameters", retMap);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    response.setHeader("Content-Type", "application/json;charset=utf-8");
    try {
        response.getWriter().write(new Gson().toJson(jsonMap));
    } catch (IOException io_ex) {
        throw new RuntimeException(io_ex);
    }
}

From source file:io.dacopancm.jfee.managedController.EditarFuncionarioBean.java

@PostConstruct
public void postConstruct() {
    try {/*from w w  w .ja v  a 2 s.c  o m*/
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        selectedPersonal = personalService.getPersonalByCi(userDetails.getUsername());
    } catch (Exception ex) {

    }
}

From source file:org.ff4j.security.test.FlipSecurityTests.java

@Before
public void setUp() throws Exception {
    securityCtx = SecurityContextHolder.getContext();
    // Init SpringSecurity Context
    SecurityContext context = new SecurityContextImpl();
    List<GrantedAuthority> listOfRoles = new ArrayList<GrantedAuthority>();
    listOfRoles.add(new SimpleGrantedAuthority("ROLE_USER"));
    User u1 = new User("user1", "user1", true, true, true, true, listOfRoles);
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(u1.getUsername(),
            u1.getPassword(), u1.getAuthorities());
    token.setDetails(u1);/*  w  w  w .j  a va 2  s  .co m*/
    context.setAuthentication(token);
    SecurityContextHolder.setContext(context);
    // <--

    ff4j = new FF4j("test-ff4j-security-spring.xml");
    ff4j.setAuthorizationsManager(new SpringSecurityAuthorisationManager());
}

From source file:hu.bme.iit.quiz.controller.QuizController.java

/**
 * *************************************************
 * URL: /quiz/start/{innerkey}// ww  w.ja va  2s.c om
 * **************************************************
 */
@Secured(value = { "isAuthenticated()" })
@RequestMapping(value = "/quiz/start/{innerkey}", method = RequestMethod.GET)
public String startQuiz(@PathVariable String innerkey) {
    try {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int quizPresentationID = quizService.startQuizByInnerKeyForUser(innerkey, user.getUsername());

        return "redirect:/quiz/room/" + quizPresentationID;
    } catch (Exception e) {
        logger.error(e);
        e.printStackTrace();
        return "redirect:/my-quizzes?start-error";
    }
}