本文整理汇总了Java中org.springframework.security.authentication.AnonymousAuthenticationToken类的典型用法代码示例。如果您正苦于以下问题:Java AnonymousAuthenticationToken类的具体用法?Java AnonymousAuthenticationToken怎么用?Java AnonymousAuthenticationToken使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
AnonymousAuthenticationToken类属于org.springframework.security.authentication包,在下文中一共展示了AnonymousAuthenticationToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: details
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的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";
}
示例2: preHandle
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
boolean isAuthenticated;
if (authentication != null) {
isAuthenticated = authentication instanceof AnonymousAuthenticationToken ? false
: authentication.isAuthenticated();
if (isAuthenticated) {
response.setContentType("text/plain");
sendRedirect(request, response);
return false; // no need to proceed with the chain as we already dealt with the response
}
}
return true;
}
示例3: getUserName
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
public static String getUserName() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof UsernamePasswordAuthenticationToken) {
return authentication.getName();
}
if (authentication instanceof OAuth2Authentication) {
log.info("third part login.authentication:{}, user {},from {}", authentication, authentication.getName(), NetworkUtil.getRemoteIp());
return authentication.getName();
}
if (authentication instanceof AnonymousAuthenticationToken) {
log.warn(" user {} not login,from {}", authentication.getName(), NetworkUtil.getRemoteIp());
return authentication.getName();
}
log.warn("{} isAuthenticated():{},name:{},details:{}", Flag.BizLogFlag.WARN_CHECK, authentication.isAuthenticated(), authentication.getName(), authentication.getDetails());
throw new ApiBizException(GlobalCode.UNKNOWN);
}
示例4: canUpdatePost
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
@Override
public boolean canUpdatePost(Authentication authentication, Long postId) {
if (authentication instanceof AnonymousAuthenticationToken)
return false;
CurrentUser currentUser = (CurrentUser) authentication.getPrincipal();
Post post = null;
try {
post = getPostById(postId);
} catch (PostNotFoundException e) {
logger.error("Post not found for PostId {} ", postId);
return false;
}
Long postUserId = post.getUserId();
return currentUser.getId().equals(postUserId);
}
示例5: authenticationIsRequired
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
private boolean authenticationIsRequired(String username) {
Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
if (Objects.isNull(existingAuth) || !existingAuth.isAuthenticated()) {
return true;
}
if (existingAuth instanceof UsernamePasswordAuthenticationToken
&& !existingAuth.getName().equals(username)) {
return true;
}
if (existingAuth instanceof AnonymousAuthenticationToken) {
return true;
}
return false;
}
示例6: interceptCall
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
if (Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken(key,
"anonymousUser", Collections.singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));
log.debug("Populated SecurityContextHolder with anonymous token: {}",
SecurityContextHolder.getContext().getAuthentication());
} else {
log.debug("SecurityContextHolder not populated with anonymous token, as it already contained: {}",
SecurityContextHolder.getContext().getAuthentication());
}
return next.startCall(call, headers);
}
示例7: getSecurityInfo
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
/**
* Return security information. E.g. is security enabled? Which user do you represent?
*/
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public SecurityInfoResource getSecurityInfo() {
final boolean authenticationEnabled = securityProperties.getBasic().isEnabled();
final SecurityInfoResource securityInfo = new SecurityInfoResource();
securityInfo.setAuthenticationEnabled(authenticationEnabled);
securityInfo.add(ControllerLinkBuilder.linkTo(SecurityController.class).withSelfRel());
if (authenticationEnabled && SecurityContextHolder.getContext() != null) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
securityInfo.setAuthenticated(authentication.isAuthenticated());
securityInfo.setUsername(authentication.getName());
}
}
return securityInfo;
}
示例8: canEdit
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
/**
* Tests whether or not the current user have access to edit the solution
* with the given identifier. The user must be an administrator or own the
* solution.
*
* @param identifier
* the identifier of the solution
* @return <code>true</code> if editable
*/
public boolean canEdit(Long identifier) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
return false;
}
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
return true;
}
}
// new solution
if (identifier == null) {
return true;
}
Account account = accountRepository.findOne(authentication.getName());
Account a = accountRepository.findAccountBySolutionId(identifier);
if (account.getUsername().equals(a.getUsername())) {
return true;
}
return false;
}
示例9: importMooseDataCard
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
@CacheControl(policy = CachePolicy.NO_CACHE)
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> importMooseDataCard(
@RequestParam final MultipartFile xmlFile, @RequestParam final MultipartFile pdfFile) {
LOG.debug("Moose data card upload request received via anonymous API");
final SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(new AnonymousAuthenticationToken(
"key", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
if (LOG.isDebugEnabled()) {
LOG.debug("Populated SecurityContextHolder with anonymous token: '" + sc.getAuthentication() + "'");
}
try {
return ResponseEntity.ok(toMap(importFeature.importMooseDataCardWithSpecialPrivilege(xmlFile, pdfFile)));
} catch (final MooseDataCardImportException e) {
return ResponseEntity.badRequest().body(toMap(e.getMessages()));
}
}
开发者ID:suomenriistakeskus,项目名称:oma-riista-web,代码行数:23,代码来源:ExternalMooseDataCardImportApiResource.java
示例10: accounts
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
@RequestMapping(value = "/accounts", method = RequestMethod.GET)
public String accounts(Model model) {
logger.debug("/accounts");
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("accounts: User logged in: " + currentUserName);
try {
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
} catch (HttpServerErrorException e) {
logger.debug("error retrieving accounts: " + e.getMessage());
model.addAttribute("accountsRetrievalError",e.getMessage());
}
}
return "accounts";
}
示例11: showTrade
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
@RequestMapping(value = "/trade", method = RequestMethod.GET)
public String showTrade(Model model) {
logger.debug("/trade.GET");
//model.addAttribute("marketSummary", marketService.getMarketSummary());
model.addAttribute("search", new Search());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("User logged in: " + currentUserName);
model.addAttribute("order", new Order());
try {
model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
}
return "trade";
}
示例12: portfolio
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
@RequestMapping(value = "/portfolio", method = RequestMethod.GET)
public String portfolio(Model model) {
logger.debug("/portfolio");
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("portfolio: User logged in: " + currentUserName);
//TODO: add account summary.
try {
model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
} catch (HttpServerErrorException e) {
logger.debug("error retrieving portfolfio: " + e.getMessage());
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
model.addAttribute("order", new Order());
}
return "portfolio";
}
示例13: doFilter
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Authentication auth = AuthenticatedRequest
.getSpinnakerUser()
.map(username -> (Authentication) new PreAuthenticatedAuthenticationToken(username,
null,
new ArrayList<>()))
.orElseGet(() -> new AnonymousAuthenticationToken(
"anonymous",
"anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")
));
val ctx = SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(auth);
SecurityContextHolder.setContext(ctx);
log.debug("Set SecurityContext to user: {}", auth.getPrincipal().toString());
chain.doFilter(request, response);
}
示例14: idpSelection
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
@RequestMapping(value = "/idpSelection", method = RequestMethod.GET)
public String idpSelection(HttpServletRequest request, Model model) {
if (!(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken)) {
LOG.warn("The current user is already logged.");
return "redirect:/landing";
} else {
if (isForwarded(request)) {
Set<String> idps = metadata.getIDPEntityNames();
for (String idp : idps)
LOG.info("Configured Identity Provider for SSO: " + idp);
model.addAttribute("idps", idps);
return "saml/idpselection";
} else {
LOG.warn("Direct accesses to '/idpSelection' route are not allowed");
return "redirect:/";
}
}
}
示例15: whenUserHasValidSession
import org.springframework.security.authentication.AnonymousAuthenticationToken; //导入依赖的package包/类
private String whenUserHasValidSession(Authentication authentication, HttpSession session) {
String redirectUrl = null;
if (!(authentication instanceof AnonymousAuthenticationToken)) {
List<String> userRoles = AuthenticationUtils.getUserRoles();
if (userRoles.contains(this.namesConfigurer.getRoleAdmin())) {
String roleAdmin = namesConfigurer.getRoleAdmin();
session.setAttribute("superAdminRole", roleService.findRoleByName(roleAdmin));
redirectUrl = "./admin.html";
} else if (userRoles.contains(this.namesConfigurer.getRoleUser())) {
redirectUrl = "./hi.html";
} else {
redirectUrl = "./welcome.html";
}
}
return redirectUrl;
}