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:fi.vm.sade.organisaatio.resource.OrganisaatioDevResource.java

/**
 * Hakee autentikoituneen kyttjn roolit/*from w  ww  .j  a  v a 2 s.  c om*/
 * @return Operaatio palauttaa samat kuin /cas/myroles. HUOM! Testikyttn tarkoitettu.
 */
@GET
@Path("/myroles")
@Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
@PreAuthorize("hasRole('ROLE_APP_ORGANISAATIOHALLINTA')")
public String getRoles() {
    StringBuilder ret = new StringBuilder("[");

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ret.append("\"");
    ret.append(auth.getName());
    ret.append("\",");

    for (GrantedAuthority ga : auth.getAuthorities()) {
        ret.append("\"");
        ret.append(ga.getAuthority().replace("ROLE_", ""));
        ret.append("\",");
    }
    ret.setCharAt(ret.length() - 1, ']');
    return ret.toString();
}

From source file:configuration.AuthSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException {
    request.getSession().setAttribute("name", authentication.getName());
    handle(request, response, authentication);
    clearAuthenticationAttributes(request);
}

From source file:de.itsvs.cwtrpc.sample1.server.service.LoginServiceImpl.java

@RolesAllowed("ROLE_SAMPLE")
public void logout() {
    final Authentication auth;

    auth = SecurityContextHolder.getContext().getAuthentication();
    log.info("Logout of user '" + auth.getName() + "'");
}

From source file:cn.org.once.cstack.utils.AuthentificationUtils.java

public User getAuthentificatedUser() throws ServiceException {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    return userService.findByLogin(auth.getName());
}

From source file:com.himanshu.poc.springbootsec.security.AuthenticationProviderImpl.java

@Override
public Authentication authenticate(Authentication arg0) throws AuthenticationException {
    logger.info(" User name is : " + arg0.getName());
    if (arg0.getName() == null || arg0.getName().isEmpty()) {
        //Token Based Authentication required
        logger.info("Since username is null or empty, hence token based authentication will be required");
        String tokenStr = (String) arg0.getCredentials();
        String userName = tokenKeeperService.queryUserByToken(tokenStr);

        UserDO user = userDao.getUserByUserName(userName);
        logger.info("Auth success");
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getPrincipal(),
                user.getCredentials(), user.getAuthorities());
        return token;

    } else {/*from  ww  w. j a  v  a 2s .  co m*/
        //Normal Authentication
        logger.info(
                "Since username is NOT null, hence username/password based authentication will be required");
        UserDO user = userDao.getUserByUserName(arg0.getName());

        if (user != null && user.getCredentials().equals(arg0.getCredentials())) {
            logger.info("Auth success");
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                    user.getPrincipal(), user.getCredentials(), user.getAuthorities());
            return token;
        }
    }

    logger.error("Auth failed");
    return null;
}

From source file:fm.lastify.web.LastifyFmMeController.java

private String getAuthenticatedUserName() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authentication == null ? null : authentication.getName();
}

From source file:hu.unideb.studentSupportInterface.backing.UserInfo.java

@PostConstruct
public void initBean() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    user = (User) userDao.loadUserByUsername(auth.getName());

    roleMap = new HashMap<Role, String>();

    roleMap.put(Role.TUTOR, "Oktat");
    roleMap.put(Role.ADMIN, "Admin");
    roleMap.put(Role.ASSESSOR, "rtkel");
    roleMap.put(Role.UPLOADER, "Feltlt");

}

From source file:org.web4thejob.security.ADAuthenticationProvider.java

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

    if (authentication.getName() == null || (String) authentication.getCredentials() == null) {
        throw new BadCredentialsException("");
    }// w  w w.  j a va  2 s  . c  o m

    String principal = getPrincipal(authentication.getName());
    String passwd = (String) authentication.getCredentials();

    LdapContext ctx = null;
    try {
        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, LdapCtxFactory.class.getCanonicalName());
        env.put(Context.SECURITY_AUTHENTICATION, "Simple");
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, passwd);
        env.put(Context.PROVIDER_URL, url);
        ctx = new InitialLdapContext(env, null);
        //LDAP Connection Successful

        UserDetails userDetails = userDetailsService.loadUserByUsername(principal);
        return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
    } catch (NamingException nex) {
        throw new BadCredentialsException("LDAP authentication failed.", nex);
    } catch (UsernameNotFoundException e) {
        throw new BadCredentialsException("UserDetails did not find a valid user for name: " + principal, e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:com.sasav.blackjack.controller.GameController.java

@RequestMapping(value = { "/game", "/" }, method = RequestMethod.GET)
public ModelAndView gamePage() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String login = auth.getName();
    ModelAndView mv = new ModelAndView("game");
    Game userGame = gameCore.getUserGame(login);
    if (userGame == null) {
        return new ModelAndView("error");
    }/*  ww w  . ja v  a2 s . c o  m*/
    Account account = accountMaster.getAccountByUsername(login);
    if (account != null) {
        mv.addObject("accountAmount", account.getAmount());
    }
    mv.addObject("userGame", userGame);

    return mv;
}

From source file:com.sasav.blackjack.controller.GameController.java

@RequestMapping(value = "/start_game", method = RequestMethod.GET)
public ModelAndView startGameRequest(@RequestParam(value = "bet", required = true) BigDecimal bet) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String login = auth.getName();

    Account account = accountMaster.getAccountByUsername(login);
    if (account != null) {
        if (account.getAmount().compareTo(bet) == -1) {
            return new ModelAndView("error", "message", "Not enough money");
        }/*from   w ww  . j av  a 2 s.c  o  m*/
    }
    Game userGame = gameCore.startNewGame(login, bet);
    if (userGame == null) {
        return new ModelAndView("error", "message", "Game is not created");
    }
    return new ModelAndView("redirect:game");
}