当前位置: 首页>>代码示例>>Java>>正文


Java SecurityContextHolder类代码示例

本文整理汇总了Java中org.springframework.security.core.context.SecurityContextHolder的典型用法代码示例。如果您正苦于以下问题:Java SecurityContextHolder类的具体用法?Java SecurityContextHolder怎么用?Java SecurityContextHolder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


SecurityContextHolder类属于org.springframework.security.core.context包,在下文中一共展示了SecurityContextHolder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: authorize

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:mraible,项目名称:devoxxus-jhipster-microservices-demo,代码行数:21,代码来源:UserJWTController.java

示例2: authenticate

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
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 ());
}
 
开发者ID:SentinelDataHub,项目名称:dhus-core,代码行数:17,代码来源:TestCacheProductService.java

示例3: getAveAge

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
@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;
}
 
开发者ID:PacktPublishing,项目名称:Spring-5.0-Cookbook,代码行数:20,代码来源:EmployeeServiceImpl.java

示例4: getCurrentUser

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:28,代码来源:SpringSecurityUserContext.java

示例5: getCurrentUser

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:26,代码来源:SpringSecurityUserContext.java

示例6: getCurrentUser

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
/**
     * 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;
    }
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:27,代码来源:SpringSecurityUserContext.java

示例7: addEntry

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
@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";
}
 
开发者ID:imaTowan,项目名称:Towan,代码行数:27,代码来源:ForumController.java

示例8: gerarTokenJwt

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:m4rciosouza,项目名称:ponto-inteligente-api,代码行数:32,代码来源:AuthenticationController.java

示例9: doFilter

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
@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);
}
 
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:19,代码来源:JwtAuthenticationTokenFilter.java

示例10: authorize

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
@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();
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-dashboard,代码行数:17,代码来源:LoginController.java

示例11: getPaybox

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
@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";
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:19,代码来源:UserCardController.java

示例12: readEmployees

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
@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);
}
 
开发者ID:PacktPublishing,项目名称:Spring-5.0-Cookbook,代码行数:20,代码来源:EmployeeServiceImpl.java

示例13: viewCardRequestForm

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
@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";
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:22,代码来源:UserCardController.java

示例14: details

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
@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";
}
 
开发者ID:kplachkov,项目名称:KPBlog,代码行数:23,代码来源:ArticleController.java

示例15: getCurrentRoles

import org.springframework.security.core.context.SecurityContextHolder; //导入依赖的package包/类
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;
}
 
开发者ID:xtianus,项目名称:yadaframework,代码行数:18,代码来源:YadaSecurityUtil.java


注:本文中的org.springframework.security.core.context.SecurityContextHolder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。