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:org.georchestra.security.SecurityRequestHeaderProvider.java

@Override
protected Collection<Header> getCustomRequestHeaders(HttpSession session, HttpServletRequest originalRequest) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    List<Header> headers = new ArrayList<Header>();
    if (authentication.getName().equals("anonymousUser"))
        return headers;
    headers.add(new BasicHeader(HeaderNames.SEC_USERNAME, authentication.getName()));
    StringBuilder roles = new StringBuilder();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (roles.length() != 0)
            roles.append(";");

        roles.append(grantedAuthority.getAuthority());
    }/*from   w  ww  . j  a va2s. co m*/
    headers.add(new BasicHeader(HeaderNames.SEC_ROLES, roles.toString()));

    return headers;
}

From source file:de.blizzy.documentr.web.attachment.AttachmentController.java

@RequestMapping(value = "/delete/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/"
        + "{branchName:" + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{pagePath:"
        + DocumentrConstants.PAGE_PATH_URL_PATTERN + "}/" + "{name:.*}", method = RequestMethod.GET)
@PreAuthorize("hasPagePermission(#projectName, #branchName, #pagePath, EDIT_PAGE)")
public String deleteAttachment(@PathVariable String projectName, @PathVariable String branchName,
        @PathVariable String pagePath, @PathVariable String name, Authentication authentication)
        throws IOException {

    User user = userStore.getUser(authentication.getName());
    pageStore.deleteAttachment(projectName, branchName, Util.toRealPagePath(pagePath), name, user);
    return "redirect:/attachment/list/" + projectName + "/" + branchName + "/" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            Util.toUrlPagePath(pagePath);
}

From source file:fr.keemto.web.config.ConnectionRepositoryConfig.java

@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
    }//from  ww w . j  a  v  a  2  s  .com
    String username = authentication.getName();
    ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(username);
    return new ObservableConnectionRepository(username, connectionRepository, accountInterceptor);
}

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

@SuppressWarnings({ "unchecked", "serial" })
@Test/*from   w w w  .j  a v  a2  s.co m*/
public void testSecondAuth() {
    // Given that there exists two plugins.
    Authentication auth = mock(UsernamePasswordAuthenticationToken.class);
    authProvider = spy(authProvider);

    when(auth.getPrincipal()).thenReturn("hello1");
    when(auth.getName()).thenReturn("hello1");
    when(auth.getCredentials()).thenReturn("world");

    when(manager.getEnabledModulesByClass(any(OnLoginRunnable.class.getClass()), any(OnLoginRunnable.class)))
            .thenReturn(new ArrayList<OnLoginRunnable>() {
                {
                    add(defaultLoginPlugin);
                    add(mockLoginPlugin);
                }
            });

    // When user is return by plugin module.
    User user = new User();
    user.setUserName("hello1");
    user.setUserId("hello1");
    user.setEmail("helloworld@gmail.com");
    user.setRole(Role.SUPER_USER);
    user.setAuthProviderClass(mockLoginPlugin.getClass().getName());
    when(mockLoginPlugin.loadUser("hello1")).thenReturn(user);
    when(mockLoginPlugin.validateUser(anyString(), anyString(), anyString(), any(), any())).thenReturn(true);

    // Then, Auth should be succeeded.
    assertThat(authProvider.authenticate(auth), notNullValue());

    // And should be inserted into DB
    // verify(authProvider, times(1)).addNewUserIntoLocal(any(SecuredUser.class));

    reset(authProvider);
    when(mockLoginPlugin.loadUser("hello1")).thenReturn(user);
    // Then, Auth should be succeeded.
    assertThat(authProvider.authenticate(auth), notNullValue());

    // And should not be inserted into DB
    // verify(authProvider, times(0)).addNewUserIntoLocal(any(SecuredUser.class));

}

From source file:co.com.carpco.altablero.spring.web.controller.TeacherController.java

@RequestMapping(value = "/admin/profesor/save", method = RequestMethod.POST)
public ModelAndView saveInformation(@RequestParam(value = "selDocType", required = true) String docType,
        @RequestParam(value = "txtDocNumber", required = true) String docNumber,
        @RequestParam(value = "txtName", required = true) String name,
        @RequestParam(value = "txtLastName", required = true) String lastName,
        @RequestParam(value = "txtBornDate", required = true) String bornDate,
        @RequestParam(value = "txtAddress", required = true) String address,
        @RequestParam(value = "txtPhone1", required = true) Long phone1,
        @RequestParam(value = "txtPhone2", required = true) Long phone2,
        @RequestParam(value = "selGender", required = true) String gender) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (!(auth instanceof AnonymousAuthenticationToken)) {

        ModelAndView model = roleUtils.createModelWithUserDetails(auth.getName());
        model.setViewName("admin/teacher/edit");
        UserBO userBo = new UserBO();
        userBo.setDocumentType(docType);
        userBo.setDocumentNumber(docNumber);
        userBo.setName(name);//from ww w  . j a v a2 s .c  o m
        userBo.setLastName(lastName);
        userBo.setBorn(new Date());
        userBo.setAddress(address);
        userBo.setPhone1(phone1);
        userBo.setPhone2(phone2);
        userBo.setGender(gender);

        userBll.saveUser(userBo);

        return model;
    } else {
        return new ModelAndView("redirect:/login");
    }

}

From source file:de.uni_koeln.spinfo.maalr.login.LoginManager.java

public boolean loggedIn(Authentication user) {
    if (user == null)
        return false;
    // TODO: Find better way to identify anonymous user...
    return user.isAuthenticated() && !anonymous.equals(user.getName());

}

From source file:com.companyname.providers.DAOAuthenticationProvider.java

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

    // Determine username and password
    String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

    String credentials = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : (String) authentication.getCredentials();

    logger.info("platform: Start authenticating user [" + username + "]");

    try {/*from w ww . ja va  2s.  c  o m*/
        Authentication auth = null;

        // authenticate from cache first to enhance performance
        auth = cache.authenticateFromCache(authentication);

        // perform authentication against our user's database store
        if (auth != null && auth.isAuthenticated()) {
            logger.info("User [" + username + "] is successfully authenticated against the cache");
        } else {
            auth = super.authenticate(authentication);
            cache.add(auth);
            logger.info("User [" + username + "] is successfully authenticated against DB store");
        }

        // build platform authentication object
        Authentication platformAuthentication = PlatAuthentication.getPlatAuthentication(auth);
        ((PlatAuthentication) platformAuthentication).setUserCredentials(credentials);
        return platformAuthentication;

    } catch (AuthenticationException ex1) {
        logger.log(Level.SEVERE, "Unsuccessfully authenticating user [" + username + "] ", ex1);
    }

    return null;
}

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

@RequestMapping(value = "/summary", method = RequestMethod.GET)
public String getSummaryCar(@ModelAttribute("employeeCar") EmployeeCar employeeCar,
        @ModelAttribute("order") Order order, Model model) {
    if (!canOrderNewCar() || employeeCar == null)
        return "redirect:/index";
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    try {/*from   w  ww .  j a v a2  s  .c  o m*/
        Order orderForEmployee = employeeService.createOrderForEmployee(auth.getName(), employeeCar);
        order.setAmountPaidByCompany(orderForEmployee.getAmountPaidByCompany());
        order.setAmountPaidByEmployee(orderForEmployee.getAmountPaidByEmployee());
        order.setOrderedCar(orderForEmployee.getOrderedCar());
        model.addAttribute("functionalLevel", employeeService.getFunctionalLevelByEmail(auth.getName()));
        model.addAttribute("car", carService.findById(employeeCar.getSelectedCar().getId()));
    } catch (IllegalArgumentException e) {
        model.addAttribute("error", e.getMessage());
    }
    return "rd/car.summary";
}

From source file:com.epam.trade.storefront.security.AcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();

    if (getBruteForceAttackCounter().isAttack(username)) {
        try {// w w w  .ja v a2  s  .  c o m
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));
            userModel.setLoginDisabled(true);
            getModelService().save(userModel);
            bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        } catch (final UnknownIdentifierException e) {
            LOG.warn("Brute force attack attempt for non existing user name " + username);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    return super.authenticate(authentication);

}

From source file:gmc.gestaxi.controller.UserServiceImpl.java

@Override
public String getLoggedInUsername() {
    Authentication userAuth = SecurityContextHolder.getContext().getAuthentication();
    if (userAuth != null) {
        return userAuth.getName();
    } else {/*from ww w.  j av a2 s.c o m*/
        return "anonymous";
    }
}