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

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

Introduction

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

Prototype

Object getPrincipal();

Source Link

Document

The identity of the principal being authenticated.

Usage

From source file:org.ngrinder.security.NGrinderAuthenticationPreAuthProvider.java

/**
 * Authenticate the given PreAuthenticatedAuthenticationToken.
 * //www . j a v a 2  s.c  o  m
 * If the principal contained in the authentication object is null, the request will be ignored to allow other
 * providers to authenticate it.
 * 
 * @param authentication
 *            authentication
 * @return authorized {@link Authentication}
 */
@SuppressWarnings("unchecked")
@Override
public Authentication authenticate(Authentication authentication) {
    Object details = authentication.getDetails();
    Authentication authenticate = super.authenticate(authentication);
    SecuredUser securedUser = (SecuredUser) authenticate.getPrincipal();
    if (details instanceof HashMap) {
        securedUser.getUser().setTimeZone(((HashMap<String, String>) details).get("user_timezone"));
        securedUser.getUser().setUserLanguage(((HashMap<String, String>) details).get("user_language"));
    } else if (details instanceof LanguageAndTimezone) {
        LanguageAndTimezone languageAndTimeZone = ((LanguageAndTimezone) details);
        securedUser.getUser().setTimeZone(languageAndTimeZone.getTimezone());
        securedUser.getUser().setUserLanguage(languageAndTimeZone.getLanguage());
    }
    // If It's the first time to login
    // means.. If the user info provider is not defaultLoginPlugin..
    if (securedUser.getUser().getId() == null) {
        addNewUserIntoLocal(securedUser);
    }
    return authenticate;
}

From source file:br.com.joaops.smt.configuration.CurrentTenantIdentifierResolverImpl.java

@Override
public String resolveCurrentTenantIdentifier() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String database = "master"; //Nome do Banco de Dados Principal
    if (authentication != null && authentication.getPrincipal() instanceof SmtUserDetails) {
        SmtUserDetails user = (SmtUserDetails) authentication.getPrincipal();
        database = user.getDatabaseName();
    }//  www. j  ava2  s. c om
    return database;
}

From source file:mx.edu.um.mateo.general.utils.LoginHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException {
    super.onAuthenticationSuccess(request, response, authentication);
    String username = ((UserDetails) authentication.getPrincipal()).getUsername();
    log.debug("Se ha firmado a {}", username);
    Usuario usuario = (Usuario) authentication.getPrincipal();
    ambiente.actualizaSesion(request.getSession(), usuario);
}

From source file:pl.com.softproject.diabetyk.web.services.UserServiceImpl.java

@Override
public UserData loadCurrentUserData() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth != null) {
        Object principal = auth.getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            String userName = userDetails.getUsername();
            return userDataDAO.findOne(userName);
        }//from  w  w  w.j a v  a2s . com
    }

    return null;
}

From source file:uk.org.rbc1b.roms.db.AuditInterceptor.java

private Integer findUserId() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    ROMSUserDetails user = (ROMSUserDetails) authentication.getPrincipal();

    return user.getUserId();
}

From source file:org.zalando.stups.stupsback.admin.domain.ThumbsUpHandler.java

@HandleBeforeCreate
public void handleCreate(ThumbsUp likes) {

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

    if (authentication != null) {
        final Optional<Object> principal = Optional.ofNullable(authentication.getPrincipal());
        likes.setUsername(principal.orElse(new String("testuser")).toString());
    } else {/*from  ww w  . j av  a2s  . c  om*/
        likes.setUsername("anonymous");
    }
}

From source file:br.com.semanticwot.cd.controllers.SwotApplicationController.java

@RequestMapping("/form")
public ModelAndView form(SwotApplicationForm swotApplicationForm, Authentication authentication) {

    SystemUser systemUser = (SystemUser) authentication.getPrincipal();

    SwotApplication swotApplication = null;

    try {/* w w  w. jav  a2 s . c om*/
        swotApplication = swotApplicationDAO.findOne(systemUser);
    } catch (EmptyResultDataAccessException ex) {
    }

    // Carrega o formulario com os dados da aplicacao do usuario
    if (swotApplication != null) {
        swotApplicationForm.setDescription(swotApplication.getDescription());
        swotApplicationForm.setName(swotApplication.getName());
    }

    // Pegar essa porta do arquivo de configuracao
    int port = systemUser.getPort();

    ModelAndView modelAndView = new ModelAndView("application/form");
    modelAndView.addObject("noderedport", String.valueOf(port));
    modelAndView.addObject("infonode",
            "<a>http://localhost:" + port + "</a> is your node-RED instance. Use this URL "
                    + "for access HTTP nodes in node-RED. For example: http://localhost:" + port
                    + "/myservice");
    // Inicializar o node-red com um json e settings baseado no id do usuario
    // Enviar para a view o caminho para o iframe
    // Escrever os passos no lado direito
    // Tenho que finalizar o node? talvez s quando acabar a sesso do usurio
    startNodeRed(systemUser);

    return modelAndView;
}

From source file:org.devgateway.toolkit.persistence.dao.AuditorAwareImpl.java

@Override
public String getCurrentAuditor() {
    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        return null;
    }//from  www.  j  a v  a  2  s  .  c o m
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return null;
    }
    final Object principal = authentication.getPrincipal();
    if (principal instanceof Person) {
        return ((Person) principal).getUsername();
    }
    return null;

}

From source file:ar.com.zauber.commons.social.oauth.examples.web.controllers.WelcomeController.java

/**
 * Join!// ww w.jav  a  2s  .  c o m
 * 
 * @param username
 * @return
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public ModelAndView doPost(@RequestParam(value = "username", required = true) final String username)
        throws IOException {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ExampleUserDetails principal = (ExampleUserDetails) auth.getPrincipal();

    ExampleUser user = new ExampleUser();
    user.setUsername(username);
    user.setAccessToken(principal.getAccessToken());

    userDao.save(user);

    SecurityContextHolder.clearContext();

    return new ModelAndView("index");
}

From source file:eu.cloud4soa.frontend.commons.server.security.C4sAuthenticationProvider.java

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

    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();

    UserInstance userInstance;//from   w w w. j  av a2 s.c o  m

    try {
        userInstance = userService.authenticateUser(username, password);
    } catch (Throwable e) {
        if (e.getMessage().contains("wrong username") || e.getMessage().contains("No user instance"))
            throw new BadCredentialsException("Bad username or password.");

        String msg = "An error occurred while authenticating user '" + Strings.defaultString(username) + "': "
                + e.getMessage();
        logger.debug(msg, e);
        throw new BadCredentialsException(msg, e);
    }

    Authentication auth = new C4sUserAuthentication(loadUserByUsername(username).getAuthorities(),
            authentication, userInstance.getUriId());
    auth.setAuthenticated(true);

    return auth;
}