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

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

Introduction

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

Prototype

public String getName();

Source Link

Document

Returns the name of this principal.

Usage

From source file:com.traffitruck.web.JsonController.java

@RequestMapping(value = "/deleteAlert", method = RequestMethod.POST)
String deleteAlert(@RequestParam("alertId") String alertId) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    dao.deleteAlert(alertId, username);/*from  w w  w  .ja v a 2 s  . c o  m*/
    return "Success!";
}

From source file:mvc.CheckUserController.java

private String getUserName() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken) && authentication != null) {
        String currentUserName = authentication.getName();
        return currentUserName;
    }//from www  .ja va  2 s  . c o m
    return "";
}

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

/**
 * Simple controller for "/" that returns a Thymeleaf view.
 *///  w w w .j  a v  a 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:oauth2.services.ChangePasswordService.java

@PreAuthorize("hasAnyRole('ROLE_AUTHENTICATED', 'ROLE_MUST_CHANGE_PASSWORD')")
public void changePassword(String userId, String oldPassword, String newPassword) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    // Step 1: Check user id against authenticated user
    if (!Objects.equal(userId, authentication.getName())) {
        throw new ChangePasswordException("Invalid user id");
    }/* w w w.jav  a  2 s  . c  o m*/

    // Step 2: Search user in repository
    User user = userRepository.findByUserId(userId);
    if (user == null) {
        throw new ChangePasswordException("User not found");
    }

    // Step 3: Validate if old password is correct.
    authenticationStrategy.authenticate(user, oldPassword);

    // Step 4: Validate new password.
    changePassword(user, newPassword);

    SecurityContextHolder.getContext().setAuthentication(null);
}

From source file:ru.codemine.ccms.service.ShopService.java

/**
 *  ?? ,    ???? ?/*from   w  w w.j av  a2 s.  co  m*/
 * @return
 */
public List<Shop> getCurrentUserShops() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        Employee currentUser = employeeDAO.getByUsername(auth.getName());
        if (currentUser != null && currentUser.getRoles().contains("ROLE_SHOP")) {
            List<Shop> result = shopDAO.getByAdmin(currentUser);
            return result;
        }
    }
    return null;
}

From source file:com.realdolmen.rdfleet.webmvc.controllers.rd.OrderCarController.java

private boolean canOrderNewCar() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    return employeeService.employeeCanOrderNewCar(auth.getName());
}

From source file:com.traffitruck.web.JsonController.java

@RequestMapping(value = "/load_user_details/{licensePlateNumber}/{loadId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public LoadAndUser getLoadAndUser(@PathVariable String licensePlateNumber, @PathVariable String loadId) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    // verify the truck belongs to the logged-in user
    Truck truck = dao.getTruckByUserAndLicensePlate(username, licensePlateNumber);
    if (truck == null) { // the logged in user does not have a truck with this license plate number
        return null;
    }/*  w  ww .j  a v  a  2s. c  o  m*/
    Load load = dao.getLoad(loadId);
    LoadsUser user = dao.getUser(username);
    return new LoadAndUser(load, user);
}

From source file:es.us.isa.ideas.app.social.CustomUserIdSource.java

public String getUserId() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
    }//from  w w  w. ja va  2  s.  c  o  m
    return authentication.getName();
}

From source file:com.coinblesk.server.controller.UserControllerAuthenticated.java

@RequestMapping(value = "/transfer-p2sh", method = POST, produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody/* w  w w  .ja v a2s .  co  m*/
public UserAccountTO transferToP2SH(@RequestBody BaseTO request) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    LOG.debug("Get account for {}", auth.getName());
    try {
        final ECKey clientKey = ECKey.fromPublicOnly(request.publicKey());
        UserAccountTO status = userAccountService.transferP2SH(clientKey, auth.getName());
        if (status != null) {
            LOG.debug("Transfer P2SH success for {}, tx:{}", auth.getName(), status.message());
            return status;
        } else {
            return new UserAccountTO().type(Type.ACCOUNT_ERROR);
        }
    } catch (Exception e) {
        LOG.error("User create error", e);
        return new UserAccountTO().type(Type.SERVER_ERROR).message(e.getMessage());
    }
}

From source file:org.georchestra.security.ImpersonateUserRequestHeaderProvider.java

@Override
protected Collection<Header> getCustomRequestHeaders(HttpSession session, HttpServletRequest originalRequest) {
    if (originalRequest.getHeader(HeaderNames.IMP_USERNAME) != null) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && trustedUsers != null && trustedUsers.contains(authentication.getName())) {
            List<Header> headers = new ArrayList<Header>(2);

            headers.add(new BasicHeader(HeaderNames.SEC_USERNAME,
                    originalRequest.getHeader(HeaderNames.IMP_USERNAME)));
            headers.add(/* ww  w . j a v  a 2  s .c  om*/
                    new BasicHeader(HeaderNames.SEC_ROLES, originalRequest.getHeader(HeaderNames.IMP_ROLES)));

            return headers;
        }
    }
    return Collections.emptyList();

}