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:com.gst.infrastructure.security.filter.TenantAwareBasicAuthenticationFilter.java

@Override
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws IOException {
    super.onSuccessfulAuthentication(request, response, authResult);
    AppUser user = (AppUser) authResult.getPrincipal();

    String pathURL = request.getRequestURI();
    boolean isSelfServiceRequest = (pathURL != null && pathURL.contains("/self/"));

    boolean notAllowed = ((isSelfServiceRequest && !user.isSelfServiceUser())
            || (!isSelfServiceRequest && user.isSelfServiceUser()));

    if (notAllowed) {
        throw new BadCredentialsException("User not authorised to use the requested resource.");
    }//from   w  w  w .  j a  va  2 s. c o  m
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateUserAuthenticationConverterUnitTests.java

/**
 * Make sure that with all the require elements we can authenticate.
 *///from  w  w w. j a v a2s.  c om
@Test
public void canAuthenticateUser() {
    final String clientId = UUID.randomUUID().toString();
    final Set<String> scopes = Sets.newHashSet(PingFederateUserAuthenticationConverter.GENIE_PREFIX + "user");
    this.map.put(PingFederateUserAuthenticationConverter.CLIENT_ID_KEY, clientId);
    this.map.put(PingFederateUserAuthenticationConverter.SCOPE_KEY, scopes);
    final Authentication authentication = this.converter.extractAuthentication(this.map);

    Assert.assertTrue(authentication instanceof UsernamePasswordAuthenticationToken);
    Assert.assertThat(authentication.getPrincipal(), Matchers.is(clientId));
    Assert.assertThat(authentication.getAuthorities().size(), Matchers.is(1));
    Assert.assertThat(authentication.getAuthorities(),
            Matchers.contains(new SimpleGrantedAuthority("ROLE_USER")));
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateUserAuthenticationConverterUnitTests.java

/**
 * Make sure that with all the require elements we can authenticate an admin.
 *///w  ww .  j  a  va  2 s .c  o m
@Test
public void canAuthenticateAdmin() {
    final String clientId = UUID.randomUUID().toString();
    final Set<String> scopes = Sets.newHashSet(PingFederateUserAuthenticationConverter.GENIE_PREFIX + "admin");
    this.map.put(PingFederateUserAuthenticationConverter.CLIENT_ID_KEY, clientId);
    this.map.put(PingFederateUserAuthenticationConverter.SCOPE_KEY, scopes);
    final Authentication authentication = this.converter.extractAuthentication(this.map);

    Assert.assertTrue(authentication instanceof UsernamePasswordAuthenticationToken);
    Assert.assertThat(authentication.getPrincipal(), Matchers.is(clientId));
    Assert.assertThat(authentication.getAuthorities().size(), Matchers.is(2));
    Assert.assertThat(authentication.getAuthorities(), Matchers.containsInAnyOrder(
            new SimpleGrantedAuthority("ROLE_ADMIN"), new SimpleGrantedAuthority("ROLE_USER")));
}

From source file:org.jtalks.common.service.nontransactional.SecurityServiceImpl.java

/**
 * {@inheritDoc}/*from w w w  .j  a  v  a  2s .c o m*/
 */
@Override
public String getCurrentUserUsername() {
    Authentication auth = securityContextFacade.getContext().getAuthentication();
    if (auth == null) {
        return null;
    }
    Object principal = auth.getPrincipal();
    String username = extractUsername(principal);

    if (isAnonymous(username)) {
        return null;
    }
    return username;
}

From source file:com.largecode.interview.rustem.controller.UsersController.java

@PreAuthorize("@userRightResolverServiceImpl.canAccessToUser(principal, #id)")
@ApiOperation(value = "Update User.", notes = "Returns NO_CONTENT if update was successful. Regular user can not change his Role.")
@ApiResponses(value = { @ApiResponse(code = 401, message = "Only authenticated access allowed."),
        @ApiResponse(code = 403, message = "Only user of ADMIN role or User has authenticated with this Id can have access."),
        @ApiResponse(code = 404, message = "User with such Id not found."),
        @ApiResponse(code = 400, message = "Reasons:\n" + "1:Passwords not same or too short.\n"
                + "2:Other userDto.email already exists.\n" + "3:Bad role name.\n"
                + "3:value of ID different between Id in URL and userDto \n") })
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT)//from ww w .ja v  a 2  s.  com
public void updateUser(@ApiParam(value = "ID of User from DB", required = true) @PathVariable Long id,
        @ApiParam(value = "new properties for User by userDto", required = true) @Valid @RequestBody UserDto userDto,
        @ApiParam(value = "Authentication", hidden = true) Authentication authentication) {
    SpringUser springUser = (SpringUser) authentication.getPrincipal();
    LOGGER.debug("Update user {} by user '{}'", userDto, springUser.getUsername());
    checkUrlAndBodyForId(id, userDto);
    checkEmailNotExists(userDto, "update user");
    try {
        usersService.updateUser(id, userDto, springUser.getRole());
    } catch (NoSuchElementException exception) {
        throw new ExceptionUserNotFound(exception.getMessage());
    }
}

From source file:domain.user.social.SocialConfig.java

@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        throw new AccessDeniedException("No user signed in");
    }/* w  ww  .j a  va  2 s.  c o m*/
    User user = ((SecureUser) authentication.getPrincipal()).getUser();
    return usersConnectionRepository().createConnectionRepository(String.valueOf(user.getUid()));
}

From source file:com.rcn.controller.ResourceController.java

@RequestMapping(value = "/pkcs12/{file_name}", method = RequestMethod.POST)
public void pkcs12Post(@PathVariable("file_name") String fileName, @RequestParam("rid") Long rid,
        @RequestParam("password") String password, Authentication principal, Model model,
        HttpServletResponse response) throws IOException {
    RcnUserDetail user = (RcnUserDetail) principal.getPrincipal();
    Long targetUserId = user.getTargetUser().getId();

    String cert = resourceRepository.certById(targetUserId, targetUserId, rid);
    try {/*  ww  w .j a  va2 s  . c  o  m*/
        byte[] content = certificateService.toPkcs12(cert, password);
        response.setContentType("application/octet-stream");
        response.getOutputStream().write(content);
        response.flushBuffer();
    } catch (Exception e) {
        model.addAttribute("error", e.getMessage());
    }
}

From source file:org.saiku.web.service.SessionService.java

public void authenticate(HttpServletRequest req, String username, String password) {
    try {/*w w  w .  j  a  v a 2 s  . c  o m*/
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        token.setDetails(new WebAuthenticationDetails(req));
        Authentication authentication = this.authenticationManager.authenticate(token);
        log.debug("Logging in with [{}]", authentication.getPrincipal());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (BadCredentialsException bd) {
        throw new RuntimeException("Authentication failed for: " + username, bd);
    }

}

From source file:org.openengsb.opencit.ui.web.LoginPageTest.java

private void mockAuthentication() {
    AuthenticationManager authManager = mock(AuthenticationManager.class);
    final Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
    when(authManager.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {
        @Override//from  w w  w  .  ja  v  a 2s  .  c om
        public Authentication answer(InvocationOnMock invocation) {
            Authentication auth = (Authentication) invocation.getArguments()[0];
            if (auth.getCredentials().equals("password")) {
                return new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(),
                        authorities);
            }
            throw new BadCredentialsException("wrong password");
        }
    });
    contextMock.putBean("authenticationManager", authManager);
}

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

@RequestMapping(method = RequestMethod.POST, name = "saveApplication")
public ModelAndView save(@Valid SwotApplicationForm swotApplicationForm, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Authentication authentication) {

    if (bindingResult.hasErrors()) {
        return form(swotApplicationForm, authentication);
    }/*from w w w  . j av  a 2 s. c o m*/

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

    SwotApplication swotApplication = null;

    try {
        swotApplication = swotApplicationDAO.findOne(systemUser);
    } catch (EmptyResultDataAccessException ex) {
    }

    if (swotApplication == null) {
        swotApplication = new SwotApplication();
    }

    swotApplication.setName(swotApplicationForm.getName());
    swotApplication.setDescription(swotApplicationForm.getDescription());

    Calendar calendar = new GregorianCalendar();
    swotApplication.setReleaseDate(calendar);
    swotApplication.setSystemUser(systemUser);

    swotApplicationDAO.update(swotApplication);

    return new ModelAndView("redirect:/#three");
}