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.javaeeeee.components.JpaAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Optional<User> optional = usersRepository.findByUsernameAndPassword(authentication.getName(),
            authentication.getCredentials().toString());
    if (optional.isPresent()) {
        return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                authentication.getCredentials(), authentication.getAuthorities());

    } else {//w ww.j ava 2  s  . com
        throw new AuthenticationCredentialsNotFoundException("Wrong credentials.");
    }
}

From source file:org.geonode.security.GeoNodeAnonymousProcessingFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    final Authentication existingAuth = securityContext.getAuthentication();

    final boolean authenticationRequired = existingAuth == null || !existingAuth.isAuthenticated();

    if (authenticationRequired) {
        try {//www.  j a va2 s .c  om
            Object principal = existingAuth == null ? null : existingAuth.getPrincipal();
            Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null
                    : existingAuth.getAuthorities();
            Authentication authRequest = new AnonymousGeoNodeAuthenticationToken(principal, authorities);
            final Authentication authResult = getSecurityManager().authenticate(authRequest);
            securityContext.setAuthentication(authResult);
            LOGGER.finer("GeoNode Anonymous filter kicked in.");
        } catch (AuthenticationException e) {
            // we just go ahead and fall back on basic authentication
            LOGGER.log(Level.WARNING, "Error connecting to the GeoNode server for authentication purposes", e);
        }
    }

    // move forward along the chain
    chain.doFilter(request, response);
}

From source file:com.acc.oauth2.HybrisOauth2UserFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (containsRole(auth, ROLE_ANONYMOUS) || containsRole(auth, ROLE_CUSTOMERGROUP)
            || containsRole(auth, ROLE_CUSTOMERMANAGERGROUP)) {
        final UserModel userModel = userService.getUserForUID((String) auth.getPrincipal());
        userService.setCurrentUser(userModel);
    }//from   w  ww  .j a  v  a2 s  .  co  m
    chain.doFilter(request, response);
}

From source file:ch.wisv.areafiftylan.products.controller.OrderRestController.java

/**
 * When a User does a POST request to /orders, a new Order is created. The requestbody is a TicketDTO, so an order
 * always contains at least one ticket. Optional next tickets should be added to the order by POSTing to the
 * location provided.//from w  ww .  ja  v  a  2 s.  c o  m
 *
 * @param auth      The User that is currently logged in
 * @param ticketDTO Object containing information about the Ticket that is being ordered.
 *
 * @return A message informing about the result of the request
 */
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/orders", method = RequestMethod.POST)
@JsonView(View.OrderOverview.class)
public ResponseEntity<?> createOrder(Authentication auth, @RequestBody @Validated TicketDTO ticketDTO) {
    HttpHeaders headers = new HttpHeaders();
    User user = (User) auth.getPrincipal();

    // You can't buy non-buyable Tickts for yourself, this should be done via the createAdminOrder() method.
    if (!ticketDTO.getType().isBuyable()) {
        return createResponseEntity(HttpStatus.FORBIDDEN,
                "Can't order tickets with type " + ticketDTO.getType().getText());
    }

    Order order = orderService.create(user.getId(), ticketDTO);

    headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(order.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, headers,
            "Ticket available and order successfully created at " + headers.getLocation(), order);
}

From source file:com.abixen.platform.common.infrastructure.security.PlatformPermissionEvaluator.java

@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
        Object permission) {/*from   w w w.ja  v a  2 s. c  o m*/
    log.debug("hasPermission() - authentication: " + authentication + ", targetId: " + targetId
            + ", targetType: " + targetType + ", permission: " + permission);

    PlatformUser platformUser = (PlatformUser) authentication.getPrincipal();
    log.debug("platformWebUser" + platformUser.getId());

    return securityIntegrationClient.hasPermission(platformUser.getUsername(), (Long) targetId,
            AclClassName.getByName(targetType), (String) permission);
}

From source file:shiver.me.timbers.spring.security.jwt.JwtPrincipalAuthenticationConverterTest.java

@Test
@SuppressWarnings("unchecked")
public void Can_convert_an_authentication_with_a_username_to_a_jwt_principle() {

    final Authentication authentication = mock(Authentication.class);

    final String username = someString();
    final Collection<GrantedAuthority> authorities = mock(Collection.class);
    final List<String> roles = mock(List.class);

    // Given//w  w w.  ja v  a 2  s.com
    given(authentication.getPrincipal()).willReturn(username);
    given(authentication.getAuthorities()).willReturn((Collection) authorities);
    given(grantedAuthorityConverter.convert(authorities)).willReturn(roles);

    // When
    final JwtPrincipal actual = converter.convert(authentication);

    // Then
    assertThat(actual.getUsername(), is(username));
    assertThat(actual.getRoles(), is(roles));
}

From source file:eionet.transfer.dao.UploadsServiceDBFiles.java

/**
 * Helper method to get authenticated userid.
 *///w ww. j  a va 2 s .  c  o m
private String getUserName() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null) {
        return "UNAUTHENTICATED";
        //throw new IllegalArgumentException("Not authenticated");
    }
    Object principal = auth.getPrincipal();
    if (principal instanceof UserDetails) {
        return ((UserDetails) principal).getUsername();
    } else {
        return principal.toString();
    }
}

From source file:com.github.lynxdb.server.api.http.handlers.EpQuery.java

@RequestMapping(path = "", method = { RequestMethod.GET, RequestMethod.POST,
        RequestMethod.DELETE }, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity rootJson(@RequestBody @Valid QueryRequest _request, Authentication _authentication,
        HttpServletResponse _response) {

    User user = (User) _authentication.getPrincipal();

    List<Query> queries;

    try {//w w w  .  j a va 2s.  co  m
        queries = parseQuery(vhosts.byId(user.getVhost()), _request);
    } catch (ParsingQueryException ex) {
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, ex.getMessage(), ex).response();
    }

    File f;
    FileOutputStream fos;
    try {
        f = File.createTempFile("lynx.", ".tmp");
        fos = new FileOutputStream(f);
    } catch (IOException ex) {
        return new ErrorResponse(mapper, HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex).response();
    }

    try {
        saveResponse(fos, queries);
    } catch (IOException ex) {
        return new ErrorResponse(mapper, HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex).response();
    }

    try {
        return ResponseEntity.ok(new InputStreamResource(new FileInputStream(f)));
    } catch (FileNotFoundException ex) {
        return new ErrorResponse(mapper, HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex).response();
    } finally {
        f.delete();
    }
}

From source file:com.ram.topup.business.service.authentication.impl.AuthenticationServiceImpl.java

@Override
public UserProfile login(String username, String password) {
    try {/*from w  w w. j a  v a 2s.  c om*/
        Authentication authenticate = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        if (authenticate.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            return ((ExtendedUserDetailsImpl) authenticate.getPrincipal()).getUser().toUserProfile();
        } else {
            throw new TopupException("Authentication Failed with username=" + username);
        }
    } catch (AuthenticationException e) {
        throw new TopupException("Authentication Error Occured", e);
    }

}

From source file:io.github.azige.bbs.web.controller.AccountController.java

public ResponseEntity<?> loginAjax(@RequestBody Account account, Model model) throws IOException {
    try {//from ww  w  . ja va  2  s  .co m
        Authentication authentication = accountService.authenticate(
                new UsernamePasswordAuthenticationToken(account.getAccountName(), account.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        Profile loginProfile = (Profile) authentication.getPrincipal();
        return new ResponseEntity<>(loginProfile, HttpStatus.OK);
    } catch (AuthenticationException ex) {
        return new ResponseEntity<>(
                new ErrorResult(
                        messageSource.getMessage("account.login.fail", null, LocaleContextHolder.getLocale())),
                HttpStatus.UNAUTHORIZED);
    }
}