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:io.gravitee.management.security.config.basic.filter.AuthenticationSuccessFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest) servletRequest;

    final Optional<Cookie> optionalStringToken;

    if (req.getCookies() == null) {
        optionalStringToken = Optional.empty();
    } else {/*from  w w w .  j a v  a  2  s . c  o  m*/
        optionalStringToken = Arrays.stream(req.getCookies())
                .filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).findAny();
    }

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && !optionalStringToken.isPresent()) {
        // JWT signer
        final Map<String, Object> claims = new HashMap<>();
        claims.put(JWTClaims.ISSUER, jwtIssuer);

        final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        claims.put(JWTClaims.PERMISSIONS, userDetails.getAuthorities());
        claims.put(JWTClaims.SUBJECT, userDetails.getUsername());
        claims.put(JWTClaims.EMAIL, userDetails.getEmail());
        claims.put(JWTClaims.FIRSTNAME, userDetails.getFirstname());
        claims.put(JWTClaims.LASTNAME, userDetails.getLastname());

        final JWTSigner.Options options = new JWTSigner.Options();
        options.setExpirySeconds(jwtExpireAfter);
        options.setIssuedAt(true);
        options.setJwtId(true);

        final Cookie bearerCookie = jwtCookieGenerator
                .generate("Bearer " + new JWTSigner(jwtSecret).sign(claims, options));
        ((HttpServletResponse) servletResponse).addCookie(bearerCookie);
    }
    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:org.brekka.pegasus.core.services.impl.PegasusPrincipalServiceImpl.java

@Override
public PegasusPrincipal currentPrincipal(final boolean required) {
    PegasusPrincipal pegasusPrincipal = threadLocalPrincipals.get();
    if (pegasusPrincipal != null) {
        return pegasusPrincipal;
    }/*from w ww.  j a v  a 2s .c  o  m*/
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof PegasusPrincipalAware) {
            PegasusPrincipalAware tokenSource = (PegasusPrincipalAware) principal;
            pegasusPrincipal = tokenSource.getPegasusPrincipal();
        }
    }
    if (pegasusPrincipal == null && required) {
        throw new PegasusException(PegasusErrorCode.PG902,
                "No pegasus principal could be found in the current security context");
    }
    return pegasusPrincipal;
}

From source file:org.callistasoftware.netcare.api.rest.HealthPlanApi.java

@RequestMapping(value = "", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
@ResponseBody// w  w w. ja va2s  .c  o  m
public ServiceResult<HealthPlan> createHealthPlan(@RequestBody final HealthPlanImpl dto,
        final Authentication auth, HttpServletRequest request) {
    ServiceResult<HealthPlan> result = this.service.createNewHealthPlan(dto,
            (CareActorBaseView) auth.getPrincipal(), dto.getPatient().getId());
    this.logAccess("create", "health_plan", request, result.getData().getPatient(), result.getData().getName());
    return result;
}

From source file:uk.co.threeonefour.ifictionary.web.user.service.DaoUserService.java

public uk.co.threeonefour.ifictionary.web.user.model.User getLoggedInUser() {

    // TODO use session
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        String username = auth.getName();
        if (auth.isAuthenticated() && username != null && !username.equals("anonymousUser")) {
            org.springframework.security.core.userdetails.User userDetails = (org.springframework.security.core.userdetails.User) auth
                    .getPrincipal();/*from  w w  w .  java  2s  .  c  o  m*/
            User user = userDao.findUser(userDetails.getUsername());

            List<Role> roles = new ArrayList<Role>();
            for (GrantedAuthority authority : userDetails.getAuthorities()) {
                roles.add(Role.valueOf(authority.getAuthority()));
            }

            user.setRoles(roles);

            return user;
        }
    }
    return null;
}

From source file:com.rockagen.gnext.service.spring.security.extension.BasicConcurrentSessionControlStrategy.java

/**
 * Check authentication allowed.//from  w w w .ja  v  a 2 s  .  c om
 * 
 * @param authentication
 *            the authentication
 * @param request
 *            the request
 * @throws AuthenticationException
 *             the authentication exception
 */
private void checkAuthenticationAllowed(Authentication authentication, HttpServletRequest request)
        throws AuthenticationException {

    final List<SessionInformation> sessions = sessionRegistry.getAllSessions(authentication.getPrincipal(),
            false);

    int sessionCount = sessions.size();
    int allowedSessions = getMaximumSessionsForThisUser(authentication);

    if (sessionCount < allowedSessions) {
        // They haven't got too many login sessions running at present
        return;
    }

    if (allowedSessions == -1) {
        // We permit unlimited logins
        return;
    }

    if (sessionCount == allowedSessions) {
        HttpSession session = request.getSession(false);

        if (session != null) {
            // Only permit it though if this request is associated with one of the already registered sessions
            for (SessionInformation si : sessions) {
                if (si.getSessionId().equals(session.getId())) {
                    return;
                }
            }
        }
        // If the session is null, a new one will be created by the parent class, exceeding the allowed number
    }

    BasicPrincipal basicPrincipal = new BasicPrincipal(authentication);
    //
    // verify the ip value in the basicPrincipal
    //
    boolean sameIp = false;
    List<Object> allValidPrincipals = new ArrayList<Object>();
    for (SessionInformation sessionInformation : sessions) {
        allValidPrincipals.add(sessionInformation.getPrincipal());
    }

    for (Object savedPrincipal : allValidPrincipals) {
        if (basicPrincipal.equals(savedPrincipal)) {
            sameIp = basicPrincipal.equalsIp((BasicPrincipal) savedPrincipal);

            break;
        }
    }
    allowableSessionsExceeded(sessions, allowedSessions, sameIp, sessionRegistry);
}

From source file:com.searchbox.framework.web.FavoriteController.java

@RequestMapping(value = "/{searchbox}/{preset}/{process}/un_mark_favorite", method = RequestMethod.GET)
public String unMarkFavorite(@RequestParam String id, HttpServletRequest request, ModelAndView model,
        @PathVariable String process, @PathVariable PresetEntity preset,
        @ModelAttribute("collector") SearchCollector collector) throws ServletException, IOException {
    logger.info("===========Un Mark Favorite=============");
    logger.info("=====>opp id:" + id);
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        UserEntity user = (UserEntity) authentication.getPrincipal();

        service.unMarkFavorite(user, id);
    }/*from  ww  w.  j  a v a  2 s  .  c  o m*/
    String referer = request.getHeader("Referer");
    return "redirect:" + referer;
}

From source file:com.searchbox.framework.web.FavoriteController.java

public List<String> getFavoriteId() {
    List<String> param = new ArrayList();
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        UserEntity user = (UserEntity) authentication.getPrincipal();
        List<UserFavoriteEntity> list = service.findFavoriteByUserId(user);
        for (int i = 0; i < list.size(); i++) {
            UserFavoriteEntity u = list.get(i);
            String uid = u.getFavoriteId();
            param.add(uid);/*  w  w  w  . j ava 2 s  . c o  m*/
        }

    }
    return param;
}

From source file:ch.wisv.areafiftylan.users.controller.UserRestController.java

/**
 * Get the User currently logged in. Because our User model implements the Spring Security UserDetails, this can be
 * directly derived from the Authentication object which is automatically added. Returns a not-found entity if
 * there's no user logged in. Returns the user
 *
 * @param auth Current Authentication object, automatically taken from the SecurityContext
 *
 * @return The currently logged in User.
 *//*w w  w  . ja v  a 2  s.  com*/
@RequestMapping(value = "/current", method = RequestMethod.GET)
public ResponseEntity<?> getCurrentUser(Authentication auth) {
    // To prevent 403 errors on this endpoint, we manually handle unauthenticated users, instead of a
    // preauthorize tag.
    if (auth != null) {
        // Get the currently logged in user from the autowired Authentication object.
        UserDetails currentUser = (UserDetails) auth.getPrincipal();
        User user = userService.getUserByUsername(currentUser.getUsername()).get();
        return new ResponseEntity<>(user, HttpStatus.OK);
    } else {
        return createResponseEntity(HttpStatus.OK, "Not logged in");
    }
}

From source file:net.shibboleth.idp.oidc.flow.PreAuthorizeUserApprovalAction.java

/**
 * Gets user info claims for scopes./*from  w  ww .  j av a 2s . c  o  m*/
 *
 * @param sortedScopes the sorted scopes
 * @return the user info claims for scopes
 */
private Map<String, Map<String, String>> getUserInfoClaimsForScopes(final Set<SystemScope> sortedScopes) {

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    final Authentication authentication = securityContext.getAuthentication();
    final SubjectContext context = (SubjectContext) authentication.getPrincipal();

    final UserInfo user = userInfoService.getByUsername(context.getPrincipalName());
    log.debug("Located UserInfo object from principal name {}", context.getPrincipalName());

    final Map<String, Map<String, String>> claimsForScopes = new HashMap<>();
    if (user != null) {
        final JsonObject userJson = user.toJson();
        log.debug("UserInfo translated to JSON is:\n{}", userJson);

        for (final SystemScope systemScope : sortedScopes) {
            final Map<String, String> claimValues = new HashMap<>();

            final Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue());
            log.debug("Processing system scope {} for the following claims: {}", systemScope.getValue(),
                    claims);
            for (final String claim : claims) {
                final JsonElement element = userJson.get(claim);
                if (userJson.has(claim) && element.isJsonPrimitive()) {
                    claimValues.put(claim, element.getAsString());
                    log.debug("Added claim {} with value {}", claim, element.getAsString());
                }
            }
            log.debug("Final claims for system scope {} are", systemScope.getValue(), claimValues);
            claimsForScopes.put(systemScope.getValue(), claimValues);
        }
    }
    return claimsForScopes;
}