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:cherry.sqlapp.controller.sqltool.clause.SqltoolClauseIdControllerImpl.java

@Override
public ModelAndView update(int id, SqltoolClauseForm form, BindingResult binding, Authentication auth,
        Locale locale, SitePreference sitePref, HttpServletRequest request) {

    SqltoolMetadata md = metadataService.findById(id, auth.getName());
    SqltoolMetadataForm mdForm = mdFormUtil.getMdForm(md);

    if (binding.hasErrors()) {
        ModelAndView mav = new ModelAndView(PathDef.VIEW_SQLTOOL_CLAUSE_ID_INIT);
        mav.addObject(PathDef.PATH_VAR_ID, id);
        mav.addObject(mdForm);/*from w  ww . j  a  v  a 2s .  c  o  m*/
        return mav;
    }

    SqltoolClause record = new SqltoolClause();
    record.setId(id);
    record.setDatabaseName(form.getDatabaseName());
    record.setSelectClause(form.getSelect());
    record.setFromClause(form.getFrom());
    record.setWhereClause(form.getWhere());
    record.setGroupByClause(form.getGroupBy());
    record.setHavingClause(form.getHaving());
    record.setOrderByClause(form.getOrderBy());
    record.setParamMap(form.getParamMap());
    record.setLockVersion(form.getLockVersion());

    if (clauseService.update(record)) {
        UriComponents uc = fromMethodCall(
                on(SqltoolClauseIdController.class).init(id, auth, locale, sitePref, request)).build();
        ModelAndView mav = new ModelAndView();
        mav.setView(new RedirectView(uc.toUriString(), true));
        return mav;
    } else {
        logicErrorUtil.rejectOnOptimisticLockingFailure(binding);
        ModelAndView mav = new ModelAndView(PathDef.VIEW_SQLTOOL_CLAUSE_ID_INIT);
        mav.addObject(PathDef.PATH_VAR_ID, id);
        mav.addObject(mdForm);
        return mav;

    }
}

From source file:org.dspace.EDMExport.service.EDMExportAuthenticationManager.java

/**
 * Redefinimos el mtodo para autenticarse
 * //from   w  ww.  j av a 2s. c  o  m
 * @param auth objeto de Spring de Authentication {@link Authentication}
 * @return UsernamePasswordAuthenticationToken {@link Authentication}
 * @throws AuthenticationException
 */
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    logger.debug("Performing EDMExport authentication");

    try {
        // Buscar usuario con login y grupo o slo con login
        if (groupIDStr != null && !groupIDStr.isEmpty()) {
            eperson = daoEperson.getEperson(auth.getName(), Integer.parseInt(groupIDStr));
        } else
            eperson = daoEperson.getEperson(auth.getName());
    } catch (Exception e) {
        logger.error("User " + auth.getName() + " does not exists! " + e.getMessage() + "," + e.toString(), e);
        //SecurityContextHolder.getContext().setAuthentication(null);
        throw new BadCredentialsException("User does not exists!");
    }

    // Validamos el password
    if (!passwordEncoder.isPasswordValid(eperson.getPassword(), (String) auth.getCredentials(), null)) {
        logger.error("Wrong password!" + eperson.getPassword() + " " + (String) auth.getCredentials());
        throw new BadCredentialsException("Wrong password!");
    }

    // Comprobamos que el login no se igual que el password, poco seguridad
    if (auth.getName().equals(auth.getCredentials())) {
        logger.debug("Entered username and password are the same!");
        throw new BadCredentialsException("Entered username and password are the same!");
    } else {
        logger.debug("User details are good and ready to go");
        return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),
                getAuthorities(eperson.getAccess()));
    }
}

From source file:com.alliander.osgp.shared.security.CustomAuthenticationManager.java

/**
 * The login function. Use an Authentication instance with the principal set
 * to the user name and the credentials set to the password. Authentication
 * will be granted if the user is permitted for an/this application, the
 * user name is registered and the password matches.
 *
 * @param authentication//from  w  ww  . j  av a2 s . c o  m
 *            An Authentication instance containing user name and password.
 *
 * @return An CustomAuthentication instance containing user name, users
 *         organisation identification, platform domains, user role, user
 *         applications and an authentication token.
 */
@Override
public Authentication authenticate(final Authentication authentication) {

    // Check if user has authentication instance.
    this.checkAuthenticationInstance(authentication);

    // Get user name and password.
    final String username = authentication.getName();
    final String password = (String) authentication.getCredentials();

    // Check user name and password.
    this.checkUsernameAndPasswordForEmptiness(username, password);

    // Prepare LoginRequest and LoginResponse.
    final LoginRequest loginRequest = new LoginRequest(username, password, this.application);
    LoginResponse loginResponse = null;

    // Try to login.
    try {

        loginResponse = this.authenticationClient.login(loginRequest);
    } catch (final Exception e) {
        LOGGER.debug(LOGIN_ATTEMPT_FAILED, e);
        throw new BadCredentialsException(LOGIN_ATTEMPT_FAILED, e);
    }

    // Check the response.
    this.checkLoginResponse(loginResponse);

    // Create the CustomAuthentication instance.
    return this.createCustomAuthenticationInstance(username, password, loginResponse);
}

From source file:de.iew.spring.integration.SpringIntegrationJmxTest.java

@Test
public void testJmxSpringIntegrationWithAuditEventMessage() throws Exception {
    // Testfix erstellen
    long timestamp = System.currentTimeMillis();

    Authentication authentication = newAnonymousAuthentication();

    AuditEventMessage auditEventMessage = new AuditEventMessage();
    auditEventMessage.setTimestamp(new Date(timestamp));
    auditEventMessage.setPrincipal(authentication.getName());
    auditEventMessage.setSeverity(Severity.INFO);
    auditEventMessage.setMessage("Foo Bar");

    // Test durchfhren
    Map<String, Object> headers = new Hashtable<String, Object>();
    GenericMessage<AuditEventMessage> message = new GenericMessage<AuditEventMessage>(auditEventMessage,
            headers);/*  ww  w. j  a  v a  2 s .com*/
    this.messageChannel.send(message);

    // Test auswerten
    /// Etwas warten, bis die Notifications verschickt wurden
    Thread.sleep(3000);

    Assert.assertEquals(1, this.springIntegrationTestNotificationListener.getNotifications().size());

    Notification notification = this.springIntegrationTestNotificationListener.getNotifications().get(0);

    Assert.assertEquals(AuditEventMessage.class.getName(), notification.getType());
    Assert.assertNull(notification.getMessage());

    AuditEventMessage userData = (AuditEventMessage) notification.getUserData();
    Assert.assertEquals("Foo Bar", userData.getMessage());
    Assert.assertEquals(Severity.INFO, userData.getSeverity());
    Assert.assertEquals(new Date(timestamp), userData.getTimestamp());
}

From source file:org.mdissjava.mdisscore.view.upload.UploadDetailsBean.java

private void retrieveSessionUserNick() {
    //Get the current logged user's username
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    this.userNick = auth.getName();

}

From source file:com.realdolmen.rdfleet.webmvc.controllers.rd.OrderCarController.java

@RequestMapping(value = "/{id}/order", method = RequestMethod.GET)
public String getOrderNewCar(@PathVariable("id") Long id, Model model,
        @ModelAttribute("employeeCar") EmployeeCar employeeCar) {
    if (!canOrderNewCar())
        return "redirect:/index";
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    try {//from   w w  w .j  av a 2s.  c om
        employeeCar.setSelectedCar(carService.findByIdAndIsOrderable(id));
        employeeCar.setCarOptions(new ArrayList<>());
        model.addAttribute("functionalLevel", employeeService.getFunctionalLevelByEmail(auth.getName()));
        model.addAttribute("carOptions", carOptionService.findAllCarOptionsByTowingBracketPossibility(
                employeeCar.getSelectedCar().isTowingBracketPossibility()));
    } catch (IllegalArgumentException e) {
        model.addAttribute("error", e.getMessage());
    }
    return "rd/car.order";
}

From source file:sk.lazyman.gizmo.security.SimpleBindAunthenticator.java

@Override
public DirContextOperations authenticate(Authentication authentication) {
    DirContextOperations user = null;/* w w  w.j  av a2 s. co  m*/
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

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

    if (StringUtils.isEmpty(password)) {
        LOG.debug("Rejecting empty password for user " + username);
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
    }

    // If DN patterns are configured, try authenticating with them directly
    for (String dn : getUserDns(username)) {
        user = bindWithDn(dn, username, password);

        if (user != null) {
            break;
        }
    }

    // Otherwise use the configured search object to find the user and authenticate with the returned DN.
    if (user == null && getUserSearch() != null) {
        DirContextOperations userFromSearch = getUserSearch().searchForUser(username);
        user = bindWithDn(userFromSearch.getDn().toString(), username, password);
    }

    try {
        if (user != null && StringUtils.isNotEmpty(gizmoGroup)) {
            BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource();
            DirContext ctx = ctxSource.getReadOnlyContext();

            DistinguishedName userDn = new DistinguishedName(user.getDn());
            userDn.prepend(ctxSource.getBaseLdapPath());

            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String filter = String.format(GROUP_SEARCH_QUERY, gizmoGroup, userDn.toCompactString());
            NamingEnumeration en = ctx.search("", filter, controls);
            if (!en.hasMore()) {
                throw new BadCredentialsException(
                        messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
            }
        }
    } catch (javax.naming.NamingException ex) {
        throw new BadCredentialsException("Couldn't check group membership");
    }

    if (user == null) {
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:com.sonymobile.backlogtool.HomeController.java

@RequestMapping(value = "/{lastArea}", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model, @PathVariable String lastArea,
        HttpServletResponse response) {//from  www . ja v  a 2  s .  c  o m
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String username = auth.getName();

    List<String> adminAreas = null;
    List<String> nonAdminAreas = null;

    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();

        User currentUser = (User) session.get(User.class, username);

        Query allAreasQuery = session.createQuery("from Area order by name");
        List<Area> allAreas = allAreasQuery.list();

        adminAreas = new ArrayList<String>();
        nonAdminAreas = new ArrayList<String>();
        for (Area area : allAreas) {
            if ((currentUser != null && currentUser.isMasterAdmin()) || area.isAdmin(username)) {
                adminAreas.add(area.getName());
            } else {
                nonAdminAreas.add(area.getName());
            }
        }

        tx.commit();

    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        session.close();
    }

    //Disables cache on this page so that the area list is refreshed every time.
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");

    ModelAndView view = new ModelAndView("home");
    view.addObject("nonAdminAreas", nonAdminAreas);
    view.addObject("adminAreas", adminAreas);
    view.addObject("isLoggedIn", isLoggedIn());
    view.addObject("lastArea", lastArea);
    view.addObject("view", "home");
    return view;
}

From source file:org.socialhistoryservices.pid.controllers.KeysController.java

@RequestMapping("/admin/keys")
public ModelAndView list(@RequestParam(value = "token", required = false) String refresh_token) {

    ModelAndView mav = new ModelAndView("keys");
    final SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    List<String> nas = NamingAuthority.getNaRole(authentication);
    if (refresh_token != null) {
        mongoTokenStore.removeAccessTokenUsingRefreshToken(refresh_token);
        mongoTokenStore.removeRefreshToken(refresh_token);
    }//from  ww  w .ja v a  2  s.  c  o m
    OAuth2AccessToken token = mongoTokenStore.selectKeys(authentication.getName());
    if (token == null) {
        final ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        final ClientToken clientToken = new ClientToken(clientId,
                new HashSet<String>(clientDetails.getResourceIds()), clientDetails.getClientSecret(),
                new HashSet<String>(clientDetails.getScope()), clientDetails.getAuthorities());
        final OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(clientToken, authentication);
        token = tokenServices.createAccessToken(oAuth2Authentication);
    }
    mav.addObject("token", token);
    mav.addObject("nas", nas);
    return mav;
}

From source file:com.inkubator.sms.gateway.util.CustomAuthenticationLogoutSuccessHandler.java

@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    try {//w  w  w. ja  v  a 2  s . c o m
        if (request.getSession().getAttribute(SMSGATEWAY.USER_LOGIN_ID) != null) {
            Long id = (Long) request.getSession().getAttribute(SMSGATEWAY.USER_LOGIN_ID);
            LoginHistory loginHistory = new LoginHistory();
            loginHistory.setId(id);
            this.loginHistoryService.updateAndPushMessage(loginHistory);
            LOGGER.info(authentication.getName() + " Success Logout");
        }
    } catch (Exception ex) {
        LOGGER.error("Error", ex);
    }
}