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.epam.reportportal.auth.SsoEndpoint.java

@RequestMapping({ "/sso/me", "/sso/user" })
public Map<String, Object> user(Authentication user) {
    return ImmutableMap.<String, Object>builder().put("user", user.getName()).put("authorities",
            user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
            .build();// ww  w  .  j av  a 2 s . c  o m

}

From source file:au.edu.anu.orcid.security.OrcidAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    LOGGER.debug("User {} has authenticated", authentication.getName());

    if (authentication.getName().startsWith("u")) {
        String newPath = request.getContextPath() + "/rest/uid/" + authentication.getName() + "/import";
        LOGGER.debug("User {} logged in, redirecting the user to: {}", authentication.getName(), newPath);
        response.sendRedirect(newPath);//  w  ww.  j  a v a 2s. c  o m
    } else {
        response.sendRedirect(request.getContextPath() + "/");
    }
}

From source file:org.exoplatform.acceptance.security.CrowdAuthenticationProviderMock.java

/**
 * {@inheritDoc}//from www .j  a  va2s. c om
 * Performs authentication with the same contract as {@link
 * org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    try {
        UserDetails user = crowdUserDetailsServiceMock.loadUserByUsername(name);
        if (user.getPassword().equals(password)) {
            return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),
                    user.getAuthorities());
        } else {
            throw new BadCredentialsException("Invalid username or password");
        }
    } catch (UsernameNotFoundException unnfe) {
        throw new BadCredentialsException("Invalid username or password", unnfe);
    }
}

From source file:com.company.project.web.controller.service.CustomAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    // CustomUserDetailsService will take care of password comparison
    // return null if username is not existing or password comparison fails
    UserDetails userDetails = customUserDetailsService.loadUserByUsername(name);

    if (userDetails == null) {
        throw new BadCredentialsException("Username not found or password incorrect.");
    }//from   w  w w .  j a  va  2  s.  co m

    if (userDetails != null) {

        // 3. Preferably clear the password in the user object before storing in authentication object           
        //return new UsernamePasswordAuthenticationToken(name, null, userDetails.getAuthorities());
        // OR
        return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        // use authentication.getPrincipal() to get the "userDetails" object
    }
    return null;
}

From source file:com.sshdemo.common.security.web.authentication.rememberme.JPATokenBasedRememberMeService.java

@Override
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication successfulAuthentication) {
    String username = successfulAuthentication.getName();

    logger.debug("Creating new persistent login for user {}", username);

    String ip = getUserIPAddress(request);
    IPPersistentRememberMeToken persistentToken = new IPPersistentRememberMeToken(username,
            generateSeriesData(), generateTokenData(), new Date(), ip);
    try {/* w  w w  .ja  va 2 s.  c o m*/
        tokenRepository.createNewToken(persistentToken);
        addCookie(persistentToken, request, response);
    } catch (DataAccessException e) {
        logger.error("Failed to save persistent token ", e);
    }
}

From source file:org.statefulj.demo.ddd.customer.domain.impl.CustomerSessionServiceImpl.java

@Override
public Customer findLoggedInCustomer() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName(); //get logged in customername
    return customerRepo.findByContactInfoEmailEmail(name);
}

From source file:edu.uiowa.icts.bluebutton.controller.AbstractBluebuttonController.java

@ModelAttribute("username")
public String getUsername() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        return auth.getName();
    }/*from  ww  w .  j a va2  s  . com*/
    return "anonymousUser";
}

From source file:psiprobe.controllers.apps.AjaxToggleContextController.java

@Override
protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (!request.getContextPath().equals(contextName) && context != null) {
        try {// w ww. j ava 2s  .co  m
            // Logging action
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String name = auth.getName(); // get username logger
            if (context.getState().isAvailable()) {
                logger.info("{} requested STOP of {}", request.getRemoteAddr(), contextName);
                getContainerWrapper().getTomcatContainer().stop(contextName);
                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.stop"), name, contextName);
            } else {
                logger.info("{} requested START of {}", request.getRemoteAddr(), contextName);
                getContainerWrapper().getTomcatContainer().start(contextName);
                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.start"), name, contextName);
            }
        } catch (Exception e) {
            logger.error("Error during ajax request to START/STOP of '{}'", contextName, e);
        }
    }
    return new ModelAndView(getViewName(), "available",
            context != null && getContainerWrapper().getTomcatContainer().getAvailable(context));
}

From source file:com.ushahidi.swiftriver.core.api.auth.crowdmapid.CrowdmapIDAuthenticationProvider.java

@Transactional(readOnly = true)
@Override/*from www.  ja  va 2s .  c om*/
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String username = authentication.getName();
    String password = authentication.getCredentials().toString();

    User user = userDao.findByUsernameOrEmail(username);

    if (user == null || !crowdmapIDClient.signIn(username, password)) {
        throw new BadCredentialsException(String.format("Invalid username/password pair for %s", username));
    }
    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    for (Role role : user.getRoles()) {
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName().toUpperCase()));
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(username,
            authentication.getCredentials(), authorities);
    result.setDetails(authentication.getDetails());
    return result;
}

From source file:com.utils.SecurityContextReader.java

public String getUsername() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        return authentication.getName();
    } else {/*from w  w  w  . j av  a 2 s. c  o  m*/
        return "";
    }
}