本文整理匯總了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);
}
}
示例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 ());
}
示例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;
}
示例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";
}
示例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);
}
示例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();
}
示例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";
}
示例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);
}
示例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";
}
示例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";
}
示例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;
}