Java Code Examples for org.springframework.security.core.context.SecurityContextHolder
The following are top voted examples for showing how to use
org.springframework.security.core.context.SecurityContextHolder. These examples are extracted from open source projects.
You can vote up the examples you like and your votes will be used in our system to generate
more good examples.
Example 1
Project: devoxxus-jhipster-microservices-demo File: UserJWTController.java View source code | 7 votes |
@PostMapping("/authenticate") @Timed public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); try { Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe(); String jwt = tokenProvider.createToken(authentication, rememberMe); response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); return ResponseEntity.ok(new JWTToken(jwt)); } catch (AuthenticationException ae) { log.trace("Authentication exception trace: {}", ae); return new ResponseEntity<>(Collections.singletonMap("AuthenticationException", ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED); } }
Example 2
Project: dhus-core File: TestCacheProductService.java View source code | 6 votes |
private void authenticate () { String name = "userTest"; Set<GrantedAuthority> roles = new HashSet<> (); roles.add (new SimpleGrantedAuthority (Role.DOWNLOAD.getAuthority ())); roles.add (new SimpleGrantedAuthority (Role.SEARCH.getAuthority ())); roles.add ( new SimpleGrantedAuthority (Role.DATA_MANAGER.getAuthority ())); SandBoxUser user = new SandBoxUser (name, name, true, 0, roles); Authentication auth = new UsernamePasswordAuthenticationToken ( user, user.getPassword (), roles); SecurityContextHolder.getContext ().setAuthentication (auth); logger.info ("userTest roles: " + auth.getAuthorities ()); }
Example 3
Project: Spring-5.0-Cookbook File: EmployeeServiceImpl.java View source code | 6 votes |
@Override public Mono<Double> getAveAge() { ToIntFunction<Employee> sizeEmpArr = (e) -> { System.out.println("flux:toIntFunction task executor: " + Thread.currentThread().getName()); System.out.println("flux:toIntFunction task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); return e.getAge(); }; Callable<Double> task = () ->{ System.out.println("flux:callable task executor: " + Thread.currentThread().getName()); System.out.println("flux:callable task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); return employeeDaoImpl.getEmployees().stream() .mapToInt(sizeEmpArr) .average() .getAsDouble(); }; Mono<Double> aveAge= Mono.fromCallable(task); return aveAge; }
Example 4
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 6 votes |
/** * 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; }
Example 5
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 6 votes |
/** * 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; }
Example 6
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 6 votes |
/** * 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; } User user = (User)authentication.getPrincipal(); String email = user.getUsername(); // 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); } return result; }
Example 7
Project: Towan File: ForumController.java View source code | 6 votes |
@RequestMapping(value = "/addEntry", method = RequestMethod.POST) public String addEntry(@Valid @ModelAttribute EntryModel newEntryModel, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { String errorMessage = ""; for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMessage += fieldError.getField() + " is invalid<br>"; } model.addAttribute("errorMessage", errorMessage); return "forward:/entry"; } //if (newEntryModel != null) { //model.addAttribute("errorMessage", "Entry already exists!<br>"); //} else { newEntryModel.setDate(new Timestamp(System.currentTimeMillis())); UserModel user = null; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); List<UserModel> userList = userRepository.findByUsername(auth.getName()); user = userList.get(0); newEntryModel.setUser(user); newEntryModel.setSubforum(null); entryRepository.save(newEntryModel); return "forum/entry"; }
Example 8
Project: ponto-inteligente-api File: AuthenticationController.java View source code | 6 votes |
/** * Gera e retorna um novo token JWT. * * @param authenticationDto * @param result * @return ResponseEntity<Response<TokenDto>> * @throws AuthenticationException */ @PostMapping public ResponseEntity<Response<TokenDto>> gerarTokenJwt( @Valid @RequestBody JwtAuthenticationDto authenticationDto, BindingResult result) throws AuthenticationException { Response<TokenDto> response = new Response<TokenDto>(); if (result.hasErrors()) { log.error("Erro validando lançamento: {}", result.getAllErrors()); result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } log.info("Gerando token para o email {}.", authenticationDto.getEmail()); Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( authenticationDto.getEmail(), authenticationDto.getSenha())); SecurityContextHolder.getContext().setAuthentication(authentication); UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationDto.getEmail()); String token = jwtTokenUtil.obterToken(userDetails); response.setData(new TokenDto(token)); return ResponseEntity.ok(response); }
Example 9
Project: chvote-protocol-poc File: JwtAuthenticationTokenFilter.java View source code | 6 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String authToken = httpRequest.getHeader(this.tokenHeader); String username = jwtTokenUtil.getUsernameFromToken(authToken); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); if (jwtTokenUtil.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest)); SecurityContextHolder.getContext().setAuthentication(authentication); } } chain.doFilter(request, response); }
Example 10
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 6 votes |
/** * 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; }
Example 11
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 6 votes |
/** * 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; }
Example 12
Project: spring-cloud-dashboard File: LoginController.java View source code | 6 votes |
@RequestMapping(value = "/authenticate", method = { RequestMethod.POST }) @ResponseBody public String authorize( @RequestBody AuthenticationRequest authenticationRequest, HttpServletRequest request) { final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( authenticationRequest.getUsername(), authenticationRequest.getPassword()); final Authentication authentication = this.authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); final HttpSession session = request.getSession(true); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); return session.getId(); }
Example 13
Project: Microservices-with-JHipster-and-Spring-Boot File: UserJWTController.java View source code | 6 votes |
@PostMapping("/authenticate") @Timed public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); try { Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe(); String jwt = tokenProvider.createToken(authentication, rememberMe); response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); return ResponseEntity.ok(new JWTToken(jwt)); } catch (AuthenticationException ae) { log.trace("Authentication exception trace: {}", ae); return new ResponseEntity<>(Collections.singletonMap("AuthenticationException", ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED); } }
Example 14
Project: esup-sgc File: UserCardController.java View source code | 6 votes |
@RequestMapping(method = RequestMethod.GET, value = "/payboxOk") public String getPaybox(@RequestParam String montant, @RequestParam String reference, @RequestParam(required = false) String auto, @RequestParam String erreur, @RequestParam String idtrans, @RequestParam String signature, HttpServletRequest request, final RedirectAttributes redirectAttributes) { String ip = request.getRemoteAddr(); String queryString = request.getQueryString(); if (payBoxService.payboxCallback(montant, reference, auto, erreur, idtrans, signature, queryString, ip)) { String eppn = SecurityContextHolder.getContext().getAuthentication().getName(); User user = User.findUser(eppn); try { cardService.sendMailCard(appliConfigService.getNoReplyMsg(),user.getEmail() ,appliConfigService.getListePpale(), appliConfigService.getSubjectAutoCard().concat(" -- ".concat(user.getEppn())), appliConfigService.getPayboxMessage()); } catch (Exception e) { log.error("Erreur lors de l'envoi du mail pour la carte de :" + user.getEppn(), e); } redirectAttributes.addFlashAttribute("messageSuccess", SUCCESS_MSG + "paybox"); } return "redirect:/user"; }
Example 15
Project: Spring-5.0-Cookbook File: EmployeeServiceImpl.java View source code | 6 votes |
@Async @Override public CompletableFuture<List<Employee>> readEmployees() { Supplier<List<Employee>> supplyListEmp = ()->{ System.out.println("service:readEmployees task executor: " + Thread.currentThread().getName()); System.out.println("processing for 5000 ms"); try { System.out.println("readEmployees Callable login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); Thread.sleep(6000); } catch (InterruptedException e) { e.printStackTrace(); } return employeeDaoImpl.getEmployees(); }; return CompletableFuture.supplyAsync(supplyListEmp); }
Example 16
Project: esup-sgc File: UserCardController.java View source code | 6 votes |
@RequestMapping(value="/card-request-form") public String viewCardRequestForm(Model uiModel, HttpServletRequest request, @RequestHeader("User-Agent") String userAgent) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String eppn = auth.getName(); User user = User.findUser(eppn); uiModel.addAttribute("user", user); Long id = Long.valueOf("-1"); if(!user.getCards().isEmpty()){ id = user.getCards().get(0).getId(); } uiModel.addAttribute("configUserMsgs", getConfigMsgsUser()); uiModel.addAttribute("lastId", id); uiModel.addAttribute("isEsupSgcUser", userService.isEsupSgcUser(eppn)); uiModel.addAttribute("cardMask", appliConfigService.getCardMask()); uiModel.addAttribute("cardLogo", appliConfigService.getCardLogo()); uiModel.addAttribute("isISmartPhone", userService.isISmartphone(userAgent)); Map<String, Boolean> displayFormParts = displayFormParts(eppn, user.getUserType()); log.debug("displayFormParts for " + eppn + " : " + displayFormParts); uiModel.addAttribute("displayFormParts", displayFormParts); return "user/card-request"; }
Example 17
Project: KPBlog File: ArticleController.java View source code | 6 votes |
@GetMapping("/article/{id}") public String details(Model model, @PathVariable Integer id) { if (!this.articleRepository.exists(id)) { return "redirect:/"; } if (!(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken)) { UserDetails user = (UserDetails) SecurityContextHolder .getContext() .getAuthentication() .getPrincipal(); User userEntity = this.userRepository.findByEmail(user.getUsername()); model.addAttribute("user", userEntity); } Article article = this.articleRepository.findOne(id); model.addAttribute("article", article); model.addAttribute("view", "article/details"); return "base-layout"; }
Example 18
Project: yadaframework File: YadaSecurityUtil.java View source code | 6 votes |
public Set<String> getCurrentRoles() { Set<String> roles = new HashSet<String>(); try { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth!=null && auth.isAuthenticated()) { Object principal = auth.getPrincipal(); if (principal instanceof UserDetails) { for (GrantedAuthority ga : ((UserDetails)principal).getAuthorities()) { roles.add(ga.getAuthority()); } } } } catch (Exception e) { log.error("Can't get roles", e); } return roles; }
Example 19
Project: springuni-particles File: JwtAuthenticationFilter.java View source code | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Authentication authentication = getAuthentication(request); if (authentication == null) { SecurityContextHolder.clearContext(); filterChain.doFilter(request, response); return; } try { SecurityContextHolder.getContext().setAuthentication(authentication); filterChain.doFilter(request, response); } finally { SecurityContextHolder.clearContext(); } }
Example 20
Project: rest-api-jwt-spring-security File: AuthenticationRestController.java View source code | 6 votes |
@RequestMapping(value = "/api/${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 = "Bearer "+jwtTokenUtil.generateToken(userDetails, device); // Return the token return ResponseEntity.ok(new JwtAuthenticationResponse(token)); }
Example 21
Project: plugin-redirect File: RedirectResourceTest.java View source code | 6 votes |
@Test public void handleRedirectAnonymousCookieNotMatch() throws URISyntaxException { SecurityContextHolder.clearContext(); final SystemUserSetting setting = new SystemUserSetting(); setting.setLogin(DEFAULT_USER); setting.setName(RedirectResource.PREFERRED_HASH); setting.setValue("-"); userSettingRepository.save(setting); em.flush(); em.clear(); final Response response = resource.handleRedirect(DEFAULT_USER + "|hash"); Assert.assertNull(response.getCookies().get(RedirectResource.PREFERRED_COOKIE_HASH)); Assert.assertEquals("http://localhost:8081/external", response.getHeaderString("location")); }
Example 22
Project: esup-sgc File: UserCardController.java View source code | 6 votes |
@RequestMapping(value="/enable", method = RequestMethod.POST) public String enableCard(@RequestParam("id") Long id, Model uiModel, final RedirectAttributes redirectAttributes) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String eppn = auth.getName(); Card card = Card.findCard(id); if(card != null && card.getEppn().equals(eppn)){ try { cardEtatService.setCardEtat(card, Etat.ENABLED, "Réactivation de la carte par l'utilisateur", null, false, false); redirectAttributes.addFlashAttribute("messageInfo", SUCCESS_MSG + "enable"); } catch (Exception e) { log.error("problème lors de la réactivation de la carte de " + eppn, e); redirectAttributes.addFlashAttribute("messageError", ERROR_MSG + "enable"); } } else{ log.info("Aucune carte valide trouvée pour activation"); redirectAttributes.addFlashAttribute("messageInfo", WARNING_MSG + "enable"); } return "redirect:/user"; }
Example 23
Project: springboot-rest-api-skeleton File: AuthController.java View source code | 6 votes |
@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)); }
Example 24
Project: yum File: SettingsService.java View source code | 6 votes |
@PreAuthorize("hasAuthority('hungry')") public User settingsGet() throws ApiException { User userDTO = new User(); com.jrtechnologies.yum.data.entity.User userDAO = userRepo.findById((Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal()); userDTO.setId(userDAO.getId()); userDTO.setFirstName(userDAO.getFirstName()); userDTO.setLastName(userDAO.getLastName()); userDTO.setEmail(userDAO.getEmail()); userDTO.setApproved(userDAO.isApproved()); LastEdit lastEdit = new LastEdit(); lastEdit.setTimeStamp(userDAO.getLastEdit()); lastEdit.setVersion(userDAO.getVersion()); userDTO.setLastEdit(lastEdit); userDTO.setRegistrationDate(userDAO.getRegistrationDate()); userDTO.setRole(userDAO.getUserRole().toString()); userDTO.setHasPicture(userDAO.hasPicture()); userDTO.setBalance(userDAO.getBalance()); userDTO.setOrderNtf(userDAO.isOrderNtf()); userDTO.setOrderModifyNtf(userDAO.isOrderModifyNtf()); userDTO.setAdminOrderNtf(userDAO.isAdminOrderNtf()); userDTO.setAdminOrderModifyNtf(userDAO.isAdminOrderModifyNtf()); userDTO.setBalanceNtf(userDAO.isBalanceNtf()); return userDTO; }
Example 25
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 6 votes |
/** * 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; }
Example 26
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 6 votes |
/** * 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; }
Example 27
Project: esup-sgc File: CardEtatService.java View source code | 6 votes |
public void updateEtatsAvailable4Card(Card card) { String eppn = "system"; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if(auth != null) { eppn = auth.getName(); } card.setEtatsAvailable(workflow.get(card.getEtat())); if(Etat.IN_PRINT.equals(card.getEtat()) || Etat.IN_ENCODE.equals(card.getEtat())) { if(!eppn.equals(card.getEtatEppn())) { card.setEtatsAvailable(new ArrayList<Etat>()); } } if(Etat.NEW.equals(card.getEtat()) && card.getUser()!=null && !card.getUser().isEditable()) { List<Etat> etatsAvailable = new ArrayList<Etat>(card.getEtatsAvailable()); etatsAvailable.remove(Etat.REQUEST_CHECKED); card.setEtatsAvailable(etatsAvailable); } }
Example 28
Project: spring-data-examples File: SecurityUtils.java View source code | 6 votes |
/** * Configures the Spring Security {@link SecurityContext} to be authenticated as the user with the given username and * password as well as the given granted authorities. * * @param username must not be {@literal null} or empty. * @param password must not be {@literal null} or empty. * @param roles */ public static void runAs(String username, String password, String... roles) { Assert.notNull(username, "Username must not be null!"); Assert.notNull(password, "Password must not be null!"); SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken(username, password, AuthorityUtils.createAuthorityList(roles))); }
Example 29
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 6 votes |
/** * 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; }
Example 30
Project: klask-io File: JWTFilter.java View source code | 6 votes |
@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); } }
Example 31
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 6 votes |
/** * 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; } User user = (User)authentication.getPrincipal(); String email = user.getUsername(); // 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); } return result; }
Example 32
Project: SaleWeb File: SaleWebController.java View source code | 5 votes |
@GetMapping("/tienda") public String tienda (Model model,HttpServletRequest request, HttpSession sesion){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String currentPrincipalName = authentication.getName(); sesion = request.getSession(); sesion.setAttribute("email", currentPrincipalName); model.addAttribute("articulos", articulo_repository.findAll()); model.addAttribute("admin",request.isUserInRole("ADMIN")); return "tienda"; }
Example 33
Project: forweaver2.0 File: WeaverService.java View source code | 5 votes |
public Weaver getCurrentWeaver() { // TODO Auto-generated method stub Authentication auth = SecurityContextHolder.getContext() .getAuthentication(); if (auth.getName().equals("anonymousUser")) return null; return (Weaver) auth.getPrincipal(); }
Example 34
Project: Microservices-with-JHipster-and-Spring-Boot File: SecurityUtilsUnitTest.java View source code | 5 votes |
@Test public void testIsAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isTrue(); }
Example 35
Project: Spring-Security-Third-Edition File: SpringSecurityUserContext.java View source code | 5 votes |
@Override public void setCurrentUser(CalendarUser user) { if (user == null) { throw new IllegalArgumentException("user cannot be null"); } UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); }
Example 36
Project: itweet-boot File: MainController.java View source code | 5 votes |
/** * 后台Main * @param model * @return */ @GetMapping(value = "/admin/system/main") public String main(Map<String, Object> model) { String username = SecurityContextHolder.getContext().getAuthentication().getName(); System.out.println("----------->"+username+"<-----------"); return "admin/system/main"; }
Example 37
Project: xm-commons File: TimelineInterceptor.java View source code | 5 votes |
private static OAuth2Authentication getAuthentication() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth instanceof OAuth2Authentication) { return (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication(); } return null; }
Example 38
Project: Taroco File: UCQueryApplication.java View source code | 5 votes |
@Bean public AuditorAware<String> auditorAware() { return new AuditorAware<String>() { @Override public String getCurrentAuditor() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated()) { return null; } return authentication.getName(); } }; }
Example 39
Project: c4sg-services File: JwtUtil.java View source code | 5 votes |
/** * Checks if one of the claim scopes hold an ADMIN role * @return True if admin */ public static boolean isAdmin() { AuthenticationJsonWebToken auth = (AuthenticationJsonWebToken) SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.getAuthorities() != null && auth.getAuthorities().contains(new SimpleGrantedAuthority("ADMIN"))) { return true; } return false; }
Example 40
Project: spring-backend-boilerplate File: SecurityContextImpl.java View source code | 5 votes |
@Override public User currentUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Object principal = authentication.getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUser(); } } logger.warn("Current User is not set, authentication: {}"); return null; }