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.sf.springsecurityregistration1.web.controllers.AnnouncementSearchController.java

/**
 * This method searches our database for announcements based on the given
 * {@link AnnouncementSearchCriteria}. Only announcements matching the 
 * criteria are returned.//ww  w.j  a  va 2  s . co  m
 *
 * @param criteria the criteria used for searching
 * @return model of next view
 */
@RequestMapping(value = "/customer/announcement/search", method = { RequestMethod.GET })
public ModelAndView list(@ModelAttribute("announcementSearchCriteria") AnnouncementSearchCriteria criteria) {
    //        System.out.println("criteria " + criteria.getAuthor() + " " 
    //                + criteria.getCategory());

    //        if Enum.valueOf(criteria.getAuthor().equals(SELECTION_TYPES.my.)) {
    if ("my".equals(criteria.getAuthor())) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName(); //get logged in username
        //            System.out.println("logged " + name);
        //            System.out.println("my is selected ");
        criteria.setAuthor(name);
    }
    Collection<Announcements> announcementsList = this.announcementService.findAnnouncements(criteria);
    ModelAndView model = new ModelAndView("/customer/announcement/search");
    model.addObject("announcementsList", announcementsList);
    return model;
}

From source file:cs544.letmegiveexam.controller.LoginController.java

@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String welcome(Model model, HttpSession session) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName();

    if (session.getAttribute("user") == null) {
        User user = userServices.getUserByUsername(name);
        session.setAttribute("user", user);
    }//w ww .  jav a 2s  . c o  m
    //ModelAndView model = new ModelAndView();
    List<Subject> subjects = subjectService.getAllSubjects();

    //        for (Subject sub : subjects) {
    //            System.out.println("Subject:" + sub.getName() + "  Description:" + sub.getDescription());
    //
    //        }
    model.addAttribute("subjects", subjects);
    return "welcome";
}

From source file:psiprobe.controllers.deploy.UndeployContextController.java

@Override
protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    try {//from   w w  w.j av a 2 s. c o  m
        if (request.getContextPath().equals(contextName)) {
            throw new IllegalStateException(
                    getMessageSourceAccessor().getMessage("probe.src.contextAction.cannotActOnSelf"));
        }

        getContainerWrapper().getTomcatContainer().remove(contextName);
        // Logging action
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName(); // get username logger
        logger.info(getMessageSourceAccessor().getMessage("probe.src.log.undeploy"), name, contextName);

    } catch (Exception e) {
        request.setAttribute("errorMessage", e.getMessage());
        logger.error("Error during undeploy of '{}'", contextName, e);
        return new ModelAndView(
                new InternalResourceView(getFailureViewName() == null ? getViewName() : getFailureViewName()));
    }
    return new ModelAndView(new RedirectView(request.getContextPath() + getViewName()));
}

From source file:at.ac.univie.isc.asio.security.WhoamiResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from w w w.  j av a 2  s  .com*/
public AuthInfo getAuthInfo() {
    final Authentication authentication = security.getAuthentication();
    final Identity identity = AuthTools.findIdentity(security);
    return AuthInfo.from(authentication.getName(), identity, authentication.getAuthorities());
}

From source file:ch.astina.hesperid.web.services.users.impl.UserServiceImpl.java

public boolean isAuthenticated() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    return auth != null && auth.isAuthenticated() && auth.getName() != null && auth.getName().isEmpty() == false
            && auth.getName().equals(anonymousUsername) == false;
}

From source file:cherry.sqlman.tool.password.PasswordChangeControllerImpl.java

private void initializeForm(PasswordChangeForm form, Authentication auth) {
    form.setLockVersion(passwordChangeService.getLockVersion(auth.getName()));
}

From source file:cn.com.fubon.springboot.starter.jwt.auth.JwtTokenServiceImpl.java

@Override
public String createJwtToken(Authentication authentication, int minutes) {
    Claims claims = Jwts.claims().setId(UUID.randomUUID().toString()).setSubject(authentication.getName())
            .setExpiration(new Date(currentTimeMillis() + minutes * 60 * 1000)).setIssuedAt(new Date());

    String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority)
            .map(String::toUpperCase).collect(Collectors.joining(","));

    claims.put(AUTHORITIES, authorities);

    return Jwts.builder().setClaims(claims).signWith(HS512, secretkey).compact();
}

From source file:hr.foi.sis.conf.PBKDF2AuthProvider.java

@Override
public Authentication authenticate(Authentication a) throws AuthenticationException {

    String username = a.getName();

    Logger.getLogger("Auth").log(Level.INFO, "POST on login username -- " + username);

    if (username == null)
        throw new BadCredentialsException("Username not found.");

    String password = (String) a.getCredentials();

    Logger.getLogger("Auth").log(Level.INFO, "POST on password -- " + password);

    if (password == null)
        throw new BadCredentialsException("Password not found.");

    Logger.getLogger("Auth").log(Level.INFO, "Getting user from database");

    UserSaltDetails user = userService.loadUserByUsername(username);

    Logger.getLogger("Auth").log(Level.INFO, "User get with username: " + user.getUsername());

    Logger.getLogger("Auth").log(Level.INFO, "User get with password: " + user.getPassword());
    String pw = user.getPassword();

    Logger.getLogger("Auth").log(Level.INFO, "User get with salt : " + user.getUserSalt());

    Logger.getLogger("Auth").log(Level.INFO, "User get with authorities : " + user.getAuthorities().toString());

    boolean isAuthenticated = false;

    try {/*from   w  w w. j a v a  2  s .co  m*/

        isAuthenticated = PBKDF2.authenticate(password, user.getPassword(), user.getUserSalt());
        Logger.getLogger("Auth").log(Level.INFO, "Is true : " + isAuthenticated);

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(PBKDF2AuthProvider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(PBKDF2AuthProvider.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (!isAuthenticated)
        throw new BadCredentialsException("Wrong password.");
    else
        Logger.getLogger("Auth").log(Level.INFO, "Authenticated");

    return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());

}

From source file:com.amediamanager.controller.UserController.java

@RequestMapping(value = "/user", method = RequestMethod.POST)
public String userPost(@ModelAttribute User user, BindingResult result, RedirectAttributes attr,
        HttpSession session) {//  w  ww .ja v a 2s.  c  o  m
    // Don't allow user name changes
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    user.setId(auth.getName());
    user.setEmail(auth.getName());

    // Update user and re-set val in session
    userService.update(user);

    // Update user auth object in security context
    UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(auth.getName(), null,
            auth.getAuthorities());
    newAuth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(newAuth);

    return "redirect:/user";
}

From source file:com.javaeeeee.components.JpaAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Optional<User> optional = usersRepository.findByUsernameAndPassword(authentication.getName(),
            authentication.getCredentials().toString());
    if (optional.isPresent()) {
        return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), authentication.getAuthorities());

    } else {/*from w w w  .jav a 2  s .  co m*/
        throw new AuthenticationCredentialsNotFoundException("Wrong credentials.");
    }
}