@Override public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException { Assert.notNull(objectIdentity, "Object Identity required"); // Check this object identity hasn't already been persisted if (retrieveObjectIdentityPrimaryKey(objectIdentity) != null) { throw new AlreadyExistsException("Object identity '" + objectIdentity + "' already exists"); } // Need to retrieve the current principal, in order to know who "owns" this ACL (can be changed later on) Authentication auth = SecurityContextHolder.getContext().getAuthentication(); PrincipalSid sid = new PrincipalSid(auth); // Create the acl_object_identity row createObjectIdentity(objectIdentity, sid); // Retrieve the ACL via superclass (ensures cache registration, proper retrieval etc) Acl acl = readAclById(objectIdentity); Assert.isInstanceOf(MutableAcl.class, acl, "MutableAcl should be been returned"); return (MutableAcl) acl; }
@RequestMapping(value = "auth", method = RequestMethod.POST) public ResponseEntity<?> auth(@RequestBody AuthRequest ar) { final Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(ar.getUsername(), ar.getPassword()) ); SecurityContextHolder.getContext().setAuthentication(authentication); User u = userRepository.findByUsername(ar.getUsername()); if (u != null) { String token = jwtTokenUtil.generateToken(u); return ResponseEntity.ok(new AuthResponse(token)); } else { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } }
@PostMapping("/authenticate") @Timed public ResponseEntity<?> authorize(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword()); try { Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); boolean rememberMe = (loginDTO.isRememberMe() == null) ? false : loginDTO.isRememberMe(); String jwt = tokenProvider.createToken(authentication, rememberMe); response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); return ResponseEntity.ok(new JWTToken(jwt)); } catch (AuthenticationException exception) { return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String jwt = resolveToken(httpServletRequest); if (StringUtils.hasText(jwt)) { if (this.tokenProvider.validateToken(jwt)) { Authentication authentication = this.tokenProvider.getAuthentication(jwt); SecurityContextHolder.getContext().setAuthentication(authentication); } } filterChain.doFilter(servletRequest, servletResponse); } catch (ExpiredJwtException eje) { log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String email = token.getName(); CalendarUser user = email == null ? null : calendarService.findUserByEmail(email); if(user == null) { throw new UsernameNotFoundException("Invalid username/password"); } // Database Password already encrypted: String password = user.getPassword(); boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password); if(!passwordsMatch) { throw new BadCredentialsException("Invalid username/password"); } Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities); return usernamePasswordAuthenticationToken; }
@Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String username = jwtTokenUtil.getUsername(request); System.out.println("checking authentication " + username); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { if (jwtTokenUtil.validate(request)) { Authentication authentication = jwtTokenUtil. getAuthentication(request); System.out.println("authenticated user " + username + ", setting security context"); SecurityContextHolder.getContext().setAuthentication(authentication); KeyUserInfo keyUserInfo = userRepository.findByEmail(username).get(0); System.out.println(keyUserInfo.getId()); ZuulFilterConfig.setUid(keyUserInfo.getId()); } } chain.doFilter(request, response); }
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST) public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException { // Perform the security final Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( authenticationRequest.getUsername(), authenticationRequest.getPassword() ) ); SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails, device); // Return the token return ResponseEntity.ok(new JwtAuthenticationResponse(token)); }
@Override protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { String login = successfulAuthentication.getName(); log.debug("Creating new persistent login for user {}", login); PersistentToken token = userRepository.findOneByLogin(login).map(u -> { PersistentToken t = new PersistentToken(); t.setSeries(RandomUtil.generateSeriesData()); t.setUser(u); t.setTokenValue(RandomUtil.generateTokenData()); t.setTokenDate(LocalDate.now()); t.setIpAddress(request.getRemoteAddr()); t.setUserAgent(request.getHeader("User-Agent")); return t; }).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the database")); try { persistentTokenRepository.saveAndFlush(token); addCookie(token, request, response); } catch (DataAccessException e) { log.error("Failed to save persistent token ", e); } }
/** * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our * application Spring Security usernames are email addresses). */ @Override public CalendarUser getCurrentUser() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); if (authentication == null) { return null; } CalendarUser user = (CalendarUser) authentication.getPrincipal(); String email = user.getEmail(); if (email == null) { return null; } CalendarUser result = calendarService.findUserByEmail(email); if (result == null) { throw new IllegalStateException( "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email); } logger.info("CalendarUser: {}", result); return result; }
@Override public String createJwtToken(Authentication authentication, int minutes) { Claims claims = Jwts.claims() .setId(String.valueOf(IdentityGenerator.generate())) .setSubject(authentication.getName()) .setExpiration(new Date(currentTimeMillis() + minutes * 60 * 1000)) .setIssuedAt(new Date()); String authorities = authentication.getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .map(String::toUpperCase) .collect(Collectors.joining(",")); claims.put(AUTHORITIES, authorities); return Jwts.builder() .setClaims(claims) .signWith(HS512, secretkey) .compact(); }
public String createToken(Authentication authentication, Boolean rememberMe) { String authorities = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity; if (rememberMe) { validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); } else { validity = new Date(now + this.tokenValidityInMilliseconds); } return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .signWith(SignatureAlgorithm.HS512, secretKey) .setExpiration(validity) .compact(); }
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { super.handle(request, response, authentication); if (authentication == null) { logger.info("authentication is null"); return; } String tenantId = tenantHolder.getTenantId(); String userId = this.getUserId(authentication); String sessionId = this.getSessionId(authentication); LogoutEvent logoutEvent = new LogoutEvent(authentication, userId, sessionId, tenantId); ctx.publishEvent(logoutEvent); }
public Authentication authenticate(final Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; } UaaRelyingPartyToken auth = (UaaRelyingPartyToken) authentication; Map<String, Object> tokenObj = UaaFilterUtils.verifiedToken(auth.getToken(), publicKey); UaaUserDetails userDetails = new UaaUserDetails(); userDetails.setUsername(tokenObj.get(Properties.USER_NAME).toString()); userDetails.setGrantedAuthorities(scopeToGrantedAuthority((List<String>) tokenObj.get(Properties.SCOPE))); if (!userDetails.isEnabled()) { throw new AuthenticationServiceException("User is disabled"); } return createSuccessfulAuthentication(userDetails); }
@PreAuthorize("hasRole('ROLE_MANAGER')") @RequestMapping(value="/action/{cardId}", method=RequestMethod.POST) @Transactional public String actionEtat(@PathVariable("cardId") Long cardId, @RequestParam Etat etatFinal, @RequestParam(required=false) String comment, Model uiModel) { Card card = Card.findCard(cardId); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String eppn = auth.getName(); if(Etat.IN_PRINT.equals(etatFinal) && (Etat.REQUEST_CHECKED.equals(card.getEtat()) || eppn.equals(card.getEtatEppn()))) { if(cardEtatService.setCardEtat(card, etatFinal, comment, comment, true, false)) { uiModel.addAttribute("cards", Arrays.asList(new Card[]{card})); } uiModel.addAttribute("cardMask", appliConfigService.getCardMask()); uiModel.addAttribute("cardLogo", appliConfigService.getCardLogo()); return "manager/print-card"; } else { uiModel.asMap().clear(); cardEtatService.setCardEtat(card, etatFinal, comment, comment, true, false); return "redirect:/manager/" + card.getId(); } }
/** * 查找用户已经参加的活动 * * @param auth * @param page * @return */ @RequestMapping("/user/findRegisterActive") @ResponseBody public Message findRegisterActive(Authentication auth, PageAndSorted page) { Message message = new Message(); ListDto<EduActive> dto = new ListDto<>(); TzUserDetails user = (TzUserDetails) auth.getPrincipal(); if (user == null) { return null; } dto.setCount(this.eduRegisterService.countActiveByType(user.getUid())); dto.setData(this.eduRegisterService.findActiveByType(user.getUid(), page)); message.setData(dto); message.setStatus(1); return message; }
/** * Simulate a request with authenticated user with specified username for a * specified duration in nanoseconds. * * @param username * the username * @param durationInNanoseconds * the duration in nanoseconds */ protected void request(String username, long durationInNanoseconds) { long now = 1510373758000000000L; when(registry.getNanos()).thenReturn(now, now + durationInNanoseconds); if (username != null) { User user = new User(username, "", new ArrayList<GrantedAuthority>()); Authentication auth = new UsernamePasswordAuthenticationToken(user, null); SecurityContextHolder.getContext().setAuthentication(auth); } try { filter.doFilterInternal(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(FilterChain.class)); } catch (ServletException | IOException e) { e.printStackTrace(); } }
/** * When logout occurs, only invalidate the current token, and not all user sessions. * <p> * The standard Spring Security implementations are too basic: they invalidate all tokens for the * current user, so when he logs out from one browser, all his other sessions are destroyed. */ @Override @Transactional public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { String rememberMeCookie = extractRememberMeCookie(request); if (rememberMeCookie != null && rememberMeCookie.length() != 0) { try { String[] cookieTokens = decodeCookie(rememberMeCookie); PersistentToken token = getPersistentToken(cookieTokens); persistentTokenRepository.delete(token); } catch (InvalidCookieException ice) { log.info("Invalid cookie, no persistent token could be deleted", ice); } catch (RememberMeAuthenticationException rmae) { log.debug("No persistent token found, so no token could be deleted", rmae); } } super.logout(request, response, authentication); }
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { UserContext userContext = (UserContext) authentication.getPrincipal(); JwtToken accessToken = tokenFactory.createAccessJwtToken(userContext); JwtToken refreshToken = tokenFactory.createRefreshToken(userContext); Map<String, String> tokenMap = new HashMap<String, String>(); tokenMap.put("token", accessToken.getToken()); tokenMap.put("refreshToken", refreshToken.getToken()); response.setStatus(HttpStatus.OK.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); mapper.writeValue(response.getWriter(), tokenMap); clearAuthenticationAttributes(request); }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String tokenPayload = request.getHeader(WebSecurityConfig.JWT_TOKEN_HEADER_PARAM); RawAccessJwtToken token = new RawAccessJwtToken(tokenExtractor.extract(tokenPayload)); return getAuthenticationManager().authenticate(new JwtAuthenticationToken(token)); }
/** * If the current user has a specific authority (security role). * <p> * The name of this method comes from the isUserInRole() method in the Servlet API * * @param authority the authority to check * @return true if the current user has the authority, false otherwise */ public static boolean isCurrentUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null) { return authentication.getAuthorities().stream() .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority)); } return false; }
@Override protected void successfulAuthentication( HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException { JwtService.addAuthentication(res, auth.getName()); }
private boolean hasPermission(Authentication authentication, Event event, Object permission) { if(event == null) { return true; } String currentUserEmail = authentication.getName(); String ownerEmail = extractEmail(event.getOwner()); if("write".equals(permission)) { return currentUserEmail.equals(ownerEmail); } else if("read".equals(permission)) { String attendeeEmail = extractEmail(event.getAttendee()); return currentUserEmail.equals(attendeeEmail) || currentUserEmail.equals(ownerEmail); } throw new IllegalArgumentException("permission "+permission+" is not supported."); }
@Override public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { if (!CookiesDAO.checkCookiesExistsAndDeleteIfNo(request, response)) return null; if (CookiesDAO.isCookieStillActualDeleteIfNo(request, response)) return null; Cookies a = null; Cookies a1 = null; User user = null; if (request.getCookies().length < 2) return null; for (Cookie x : request.getCookies()) if (x.getName().equals("remember")) { a = RepositoriesAccess.cookiesRepository.findByValue(x.getValue()); a1 = RepositoriesAccess.cookiesRepository.findByName(x.getValue()); user = CookiesDAO.findConnectUserWithCookie(a1); } if (a == null || a1 == null || user == null) return null; if (user.getCookieCode().equals(a1.getValue())) if (a1.getName().equals(a.getValue())) return UserDAO.login(user.getLogin(), user.getPassword()); return null; }
/** * Get the login of the current user. * * @return the login of the current user */ public static String getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); String userName = null; if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); userName = springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { userName = (String) authentication.getPrincipal(); } } return userName; }
/** * Verifie si le user est un personnel * * @return true si le user est un personnel */ public Boolean isPersonnel(Authentication auth) { if (auth == null) { return false; } return auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).filter(Predicate .isEqual(ConstanteUtils.ROLE_SCOL_CENTRALE) .or(Predicate.isEqual(ConstanteUtils.ROLE_ADMIN).or(Predicate.isEqual(ConstanteUtils.ROLE_ADMIN_TECH)) .or(Predicate.isEqual(ConstanteUtils.ROLE_CENTRE_CANDIDATURE)) .or(Predicate.isEqual(ConstanteUtils.ROLE_COMMISSION)) .or(Predicate.isEqual(ConstanteUtils.ROLE_GESTION_CANDIDAT)) .or(Predicate.isEqual(ConstanteUtils.ROLE_GESTION_CANDIDAT_LS)))) .findAny().isPresent(); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { Authentication authentication = TokenAuthenticationService .getAuthentication((HttpServletRequest)request); SecurityContextHolder.getContext().setAuthentication(authentication); filterChain.doFilter(request,response); }
public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, "", authorities); // Claims claims = Jwts.parser() // .setSigningKey(secretKey) // .parseClaimsJws(token) // .getBody(); // // String principal = claims.getSubject(); // // // CHANGES START HERE // String roles = claims.get(AUTHORITIES_KEY, Map.class).get("roles").toString(); // if(roles != null && roles.length() > 0) { // roles = roles.substring(1, roles.length() - 1); // } // // Collection<? extends GrantedAuthority> authorities = // Arrays.asList(roles.split(",")).stream() // .map(authority -> new SimpleGrantedAuthority("ROLE_" + authority.toUpperCase())) // .collect(Collectors.toList()); // // return new UsernamePasswordAuthenticationToken(principal, token, authorities); }
private void checkUpdatePermission(Person person) { if (SecurityContextHolder.getContext() == null) { throw new UnauthorizedClientException("Unauthorized"); } Authentication auth = SecurityContextHolder.getContext().getAuthentication(); BrowserUser user = (BrowserUser) auth.getPrincipal(); if ((!person.getId().equals(user.getPerson().getId()) || person.getRole().equals(PersonRole.ROLE_ADMIN)) && !user.getAuthorities().contains(new SimpleGrantedAuthority(PersonRole.ROLE_ADMIN.name()))) { throw new UnauthorizedClientException("Only admin can do this"); } }
/** * If the current user has a specific authority (security role). * <p> * The name of this method comes from the isUserInRole() method in the Servlet API * * @param authority the authority to check * @return true if the current user has the authority, false otherwise */ public static boolean isCurrentUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null) { return authentication.getAuthorities() .stream() .anyMatch(grantedAuthority -> grantedAuthority.getAuthority() .equals(authority)); } return false; }
@Override public void saveAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication, OAuth2AccessToken accessToken) { Calendar expirationDate = Calendar.getInstance(); expirationDate.setTime(accessToken.getExpiration()); ClientUser clientUser = getClientUser(authentication); clientUser.setAccessToken(accessToken.getValue()); clientUser.setAccessTokenValidity(expirationDate); users.save(clientUser); }