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:org.ligoj.app.http.security.RestAuthenticationProviderTest.java

@Test
public void authenticateOverrideDifferentUser() {
    httpServer.stubFor(post(urlPathEqualTo("/"))
            .willReturn(aResponse().withStatus(HttpStatus.SC_NO_CONTENT).withHeader("X-Real-User", "other")));
    httpServer.start();/*  w  w w  . j av  a 2  s.co  m*/
    final Authentication authentication = authenticate("http://localhost");
    Assertions.assertNotNull(authentication);
    Assertions.assertEquals("other", authentication.getName());
    Assertions.assertEquals("other", authentication.getPrincipal().toString());
}

From source file:cherry.sqlman.tool.clause.SqlClauseIdControllerImpl.java

@Override
public SqlMetadataForm getMetadata(int id, Authentication auth) {
    SqlMetadataForm mdForm = metadataService.findById(id, auth.getName());
    shouldExist(mdForm, SqlMetadataForm.class, id, auth.getName());
    return mdForm;
}

From source file:org.ligoj.app.http.security.RestAuthenticationProviderTest.java

@Test
public void authenticate() {
    httpServer.stubFor(post(urlPathEqualTo("/")).willReturn(aResponse().withStatus(HttpStatus.SC_NO_CONTENT)));
    httpServer.start();//ww  w.  j  a  va  2  s  .c  om
    final Authentication authentication = authenticate("http://localhost");
    Assertions.assertNotNull(authentication);
    Assertions.assertEquals("junit", authentication.getName());
    Assertions.assertEquals("junit", authentication.getPrincipal().toString());

    Assertions.assertTrue(authenticationProvider.supports(Object.class));
}

From source file:fr.hoteia.qalingo.web.handler.security.ExtSimpleUrlAuthenticationSuccessHandler.java

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

    // Find the current customer
    Customer customer = customerService.getCustomerByLoginOrEmail(authentication.getName());

    // Persit only the new CustomerConnectionLog
    CustomerConnectionLog customerConnectionLog = new CustomerConnectionLog();
    customerConnectionLog.setCustomerId(customer.getId());
    customerConnectionLog.setLoginDate(new Date());
    customerConnectionLog.setApp(Constants.APP_NAME_FO_MCOMMERCE_CODE);
    customerConnectionLog.setHost(request.getRemoteHost());
    customerConnectionLog.setAddress(request.getRemoteAddr());
    customerConnectionLogService.saveOrUpdateCustomerConnectionLog(customerConnectionLog);

    try {//w  w  w  .  ja  v a 2s .co  m
        // Update the Customer in Session
        customer.getConnectionLogs().add(customerConnectionLog);
        requestUtil.updateCurrentCustomer(request, customer);
        setUseReferer(false);
        String url = requestUtil.getCurrentRequestUrlNotSecurity(request);

        // SANITY CHECK
        if (StringUtils.isEmpty(url)) {
            url = urlService.generateUrl(FoUrls.HOME, requestUtil.getRequestData(request));
        } else {
            String cartDetails = "cart-details.html";
            if (url.contains(cartDetails)) {
                url = urlService.generateUrl(FoUrls.CART_DELIVERY, requestUtil.getRequestData(request));
            }
        }

        setDefaultTargetUrl(url);
        redirectStrategy.sendRedirect(request, response, url);

    } catch (Exception e) {
        LOG.error("", e);
    }

}

From source file:com.autoupdater.server.utils.authentication.BCryptAuthenticationManager.java

/**
 * Authenticate user.//  www.j a v a  2  s .c o m
 * 
 * @param auth
 *            authentication data passed by Spring Security
 * @return result of authentication
 */
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    logger.debug("Performing authentication");

    User user = null;

    logger.debug("Searching user [" + auth.getName() + "] in DB");
    try {
        user = userService.findByUsername(auth.getName());
    } catch (Exception e) {
        logger.error("User [" + auth.getName() + "] does not exists (exception)!");
        throw new AuthenticationServiceException("Error while obtaining User data!");
    }
    if (user == null) {
        logger.error("User [" + auth.getName() + "] does not exists (null)!");
        throw new BadCredentialsException("User does not exists!");
    }

    if (!BCrypt.checkpw(auth.getCredentials().toString(), user.getHashedPassword())) {
        logger.error("Password doesn't match!");
        throw new BadCredentialsException("Password doesn't match!");
    }

    logger.debug("User details are good and ready to go");
    return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),
            getAuthorities(user.isAdmin(), user.isPackageAdmin()));
}

From source file:org.parancoe.plugins.security.SecureInterceptor.java

/**
 * Put in the Mapped Diagnostic Context (MDC) the infos on the logged user.
 * So these infos can be showed in the log, using the %X{key} format sequence in the log layout.
 *//*w  ww .  j a  v a  2  s  . c om*/
private void populateMDC() {
    String username = "unknown";
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        username = authentication.getName();
    }
    MDC.put(USERNAME_MDC_KEY, username);
}

From source file:binky.reportrunner.ui.actions.base.StandardRunnerAction.java

public final String getSessionUserName() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        return auth.getName();
    } else {/*from   w ww.jav a2  s . co  m*/
        RunnerUser user = getSessionUser();
        if (user != null) {
            return user.getUsername();
        } else {
            return null;
        }
    }

}

From source file:com.alehuo.wepas2016projekti.controller.ProfileController.java

/**
 * Profiilin selaus/*from  ww w .  jav a2s  .c o m*/
 *
 * @param a Autentikoini
 * @param username Kyttjnimi
 * @param m Malli
 * @param l Lokalisaatio
 * @return
 * @throws UnsupportedEncodingException
 */
@RequestMapping("/profile/{username}")
public String viewProfile(Authentication a, @PathVariable String username, Model m, Locale l)
        throws UnsupportedEncodingException {

    UserAccount loggedInUser = userService.getUserByUsername(a.getName());
    m.addAttribute("user", loggedInUser);
    String profileUsername = URLDecoder.decode(username, "UTF-8");
    UserAccount u = userService.getUserByUsername(profileUsername);
    m.addAttribute("userProfile", u);

    //Jos kyttj ei ole tyhj, lis kyttjn lismt kuvat
    if (u != null) {
        List<Image> images = imageService.findAllByUserAccount(u);
        m.addAttribute("userImages", images);
    }

    LOG.log(Level.INFO, "Kayttaja ''{0}'' selasi kayttajan ''{1}'' profiilia.",
            new Object[] { a.getName(), username });
    return "profile";
}

From source file:com.rambird.miles.repository.jdbc.JdbcMileRepositoryImpl.java

/**
 * Loads {@link Owner Owners} from the data store by last name, returning all owners whose last name <i>starts</i> with
 * the given name; also loads the {@link Pet Pets} and {@link Visit Visits} for the corresponding owners, if not
 * already loaded.//  w w  w  .  j  av a2 s .c om
 */
@Override
public Collection<MyMile> findAll(SearchMiles searchMiles) throws DataAccessException {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("userName", auth.getName());
    String searchIndexFilter = StringUtils.isEmpty(searchMiles.getSearchText()) ? ""
            : " and search_index @@ to_tsquery('" + searchMiles.getSearchText() + "') ";

    List<MyMile> miles = this.namedParameterJdbcTemplate.query(
            SELECT_QUERY + " where user_name=:userName " + searchIndexFilter, params,
            ParameterizedBeanPropertyRowMapper.newInstance(MyMile.class));

    return miles;
}

From source file:controller.PaymentController.java

@RequestMapping(method = RequestMethod.GET)
public ModelAndView payment(Authentication authen) {
    ModelAndView model = new ModelAndView();
    try {//w w  w.ja  va 2  s  .  co  m
        model.setViewName("payment");
        double sum = 0;
        Customer cus = cusModel.find(authen.getName(), "username", false).get(0);
        int orderID = orderModel.getOrderIDByCustomer(cus.getCustomerId());
        Order od = orderModel.getByID(orderID);
        Set<OderDetail> listDetail = od.getOderDetails();
        for (OderDetail detail : listDetail) {
            sum += detail.getPrice() * detail.getQuantity();
        }
        model.addObject("listDetail", listDetail);
        model.addObject("sum", sum);
        model.addObject("title", "Payment");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return model;
}