Java 类org.springframework.security.authentication.AnonymousAuthenticationToken 实例源码

项目:KPBlog    文件:ArticleController.java   
@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";
}
项目:Smart-Shopping    文件:RedirectWhenAuthenticatedInterceptor.java   
@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;
}
项目:sns-todo    文件:SecurityUtil.java   
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);
}
项目:nixmash-blog    文件:PostServiceImpl.java   
@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);
}
项目:grpc-spring-security-demo    文件:BasicAuthenticationInterceptor.java   
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;
}
项目:grpc-spring-security-demo    文件:AnonymousAuthenticationInterceptor.java   
@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);
}
项目:spring-cloud-dashboard    文件:SecurityController.java   
/**
 * 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;
}
项目:dawn-marketplace-server    文件:MarketplaceDAO.java   
/**
 * 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;
}
项目:oma-riista-web    文件:ExternalMooseDataCardImportApiResource.java   
@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()));
    }
}
项目:web-ui    文件:UserController.java   
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
    if (!model.containsAttribute("login")) {
        model.addAttribute("login", new AuthenticationRequest());
    }
    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("User logged in: " + currentUserName);

        try {
            model.addAttribute("accounts",accountService.getAccounts(currentUserName));
            model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
        User user = userService.getUser(currentUserName);
        model.addAttribute("user", user);
        model.addAttribute("accounts",accountService.getAccounts(currentUserName));
    }

    return "index";
}
项目:web-ui    文件:AccountsController.java   
@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";
}
项目:web-ui    文件:TradeController.java   
@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";
}
项目:web-ui    文件:PortfolioController.java   
@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";
}
项目:fiat    文件:FiatAuthenticationFilter.java   
@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);
}
项目:spring-tsers-auth    文件:SSOController.java   
@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:/";
        }
    }
}
项目:helicalinsight    文件:AdminController.java   
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;
}
项目:engerek    文件:MidpointRestSecurityQuestionsAuthenticator.java   
private List<SecurityQuestionDefinitionType> getQuestions(PrismObject<UserType> user) {
    return getSecurityEnforcer().runPrivileged(new Producer<List<SecurityQuestionDefinitionType>>() {

        @Override
        public List<SecurityQuestionDefinitionType> run() {
            Task task = getTaskManager().createTaskInstance("Search user by name");
            OperationResult result = task.getResult();
            SecurityPolicyType securityPolicyType = null;
            try {
                SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("rest_sec_q_auth", "REST", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
                securityPolicyType = modelInteractionService.getSecurityPolicy(user, task, result);
            } catch (ObjectNotFoundException | SchemaException e) {
                return null;
            } finally {
                SecurityContextHolder.getContext().setAuthentication(null);
            }
            if (securityPolicyType.getCredentials() != null && securityPolicyType.getCredentials().getSecurityQuestions() != null){
                return securityPolicyType.getCredentials().getSecurityQuestions().getQuestion();
            }
            return null;
        }
    });

}
项目:springBootTrader-aos    文件:UserController.java   
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
    if (!model.containsAttribute("login")) {
        model.addAttribute("login", new AuthenticationRequest());
    }
    model.addAttribute("marketSummary", marketService.getMarketSummary());

    //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);

        try {
            model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
        model.addAttribute("account",accountService.getAccount(currentUserName));
    }

    return "index";
}
项目:springBootTrader-aos    文件:TradeController.java   
@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());
        //TODO: add account summary?
        try {
            model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
    }

    return "trade";
}
项目:springBootTrader-aos    文件:TradeController.java   
@RequestMapping(value = "/order", method = RequestMethod.POST)
public String buy(Model model, @ModelAttribute("order") Order order) {
    model.addAttribute("search", new Search());

    // buy the order after setting attributes not set by the UI.
    //check if user is logged in!
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (!(authentication instanceof AnonymousAuthenticationToken)) {
                String currentUserName = authentication.getName();
                logger.debug("/order ORDER: " + order);
                order.setAccountId(currentUserName);
                order.setCompletionDate(new Date());

                Order result = marketService.sendOrder(order);
                model.addAttribute("savedOrder", result);
                model.addAttribute("order", new Order());
                try {
                    model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
                } catch (HttpServerErrorException e) {
                    model.addAttribute("portfolioRetrievalError",e.getMessage());
                }
            } else {
                //should never get here!!!
            }
    return "trade";
}
项目:springBootTrader-aos    文件:PortfolioController.java   
@RequestMapping(value = "/portfolio", method = RequestMethod.GET)
public String portfolio(Model model) {
    logger.debug("/portfolio");
    model.addAttribute("marketSummary", marketService.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",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            logger.debug("error retrieving portfolfio: " + e.getMessage());
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
        model.addAttribute("order", new Order());
    }

    return "portfolio";
}
项目:NetLicensing-Gateway    文件:SecurityHelper.java   
public Context getContext() {
    final Context context = new Context();
    context.setBaseUrl(nlicBaseUrl);
    context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
    context.setObject(RestProvider.Configuration.class, new GWClientConfiguration());

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        if (authentication instanceof AnonymousAuthenticationToken) {
            // TODO(2K): handle missing authentication (no cases so far)
            context.setUsername("");
            context.setPassword("");
        } else {
            context.setUsername(authentication.getPrincipal().toString());
            context.setPassword(authentication.getCredentials().toString());
        }
    }
    return context;
}
项目:java-spring-jspx-hibernate-template    文件:RootController.java   
@RequestMapping(value = Constants.Url.LOGIN, method = RequestMethod.GET)
public String showLoginPage(@RequestParam(value = Constants.RequestParam.ERROR, required = false) Boolean error,
                            @RequestParam(value = Constants.RequestParam.LOGOUT, required = false) Boolean logout,
                            Model model) {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    if (securityContext != null) {
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            return Constants.Url.REDIRECT + Constants.Url.ROOT;
        }
    }
    if (error != null) {
        model.addAttribute(Constants.ModelAttribute.ERROR, Constants.Messages.PAGE_LOGIN_ERROR_INVALID_USERNAME_AND_PASSWORD);
    }
    if (logout != null) {
        model.addAttribute(Constants.ModelAttribute.LOGOUT, Constants.Messages.PAGE_LOGIN_MESSAGE_LOGOUT);
    }
    return Constants.View.LOGIN;
}
项目:owsi-core-parent    文件:AbstractCoreSession.java   
/**
 * @see AbstractCoreSession#authenticate(String, String)
 */
public void signInAs(String username) throws UsernameNotFoundException {
    // on charge l'utilisateur
    // on le passe dans une méthode surchargeable -> implémentation par défaut à faire
    // Sitra -> revoir l'implémentation par défaut
    if (!hasSignInAsPermissions(getUser(), userService.getByUserName(username))) {
        throw new SecurityException("L'utilisateur n'a pas les permissions nécessaires");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    RunAsUserToken token = new RunAsUserToken(defaultJpaSecurityConfig.getRunAsKey(),
            userDetails, "runAs", userDetails.getAuthorities(), null);

    // On garde l'authentification de l'utilisateur pour pouvoir lui proposer de se reconnecter.
    Authentication previousAuthentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(previousAuthentication instanceof AnonymousAuthenticationToken)) {
        originalAuthentication = previousAuthentication;
    }

    signOut();

    Authentication authentication = authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    doInitializeSession();
    bind();
    signIn(true);
}
项目:data-acquisition    文件:PermissionAcquireFilter.java   
@Override protected void doFilterInternal(HttpServletRequest request,
    HttpServletResponse httpServletResponse, FilterChain filterChain)
    throws ServletException, IOException {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String authHeader = null;
    if(authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
        authHeader = tokenRetriever.getAuthToken(authentication);
    }

    if(authHeader == null) {
        LOGGER.debug("Request has no authorization header.");
        httpServletResponse.sendError(401, "Unauthorized.");
    }
    else {
        UUID[] ids = authorization.getAccessibleOrgs(request).stream()
                .map(org -> org.getOrganization().getGuid()).toArray(size -> new UUID[size]);
        request.setAttribute(ACCESSIBLE_ORGS, ids);

        if (ids.length > 0) {
            filterChain.doFilter(request, httpServletResponse);
        } else {
            LOGGER.debug("User access denied.");
            httpServletResponse.sendError(403, "Can't access this organization.");
        }
    }
}
项目:hotel_shop    文件:MainController.java   
/**
 * Accesss denied.
 *
 * @return the model and view
 */
@RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accesssDenied(HttpServletRequest request) {
    ModelAndView model = new ModelAndView();

    // check if user is login
    Authentication auth = SecurityContextHolder.getContext()
            .getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        UserDetails userDetail = (UserDetails) auth.getPrincipal();
        System.out.println(userDetail);

        model.addObject("username", userDetail.getUsername());

    }

    model.setViewName(checkName("403", request));
    return model;

}
项目:hotel_shop    文件:MainController.java   
/**
 * Not found.
 *
 * @return the model and view
 */
@RequestMapping(value = "/404", method = RequestMethod.GET)
public ModelAndView notFound(HttpServletRequest request) {

    ModelAndView model = new ModelAndView();

    // check if user is login
    Authentication auth = SecurityContextHolder.getContext()
            .getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        UserDetails userDetail = (UserDetails) auth.getPrincipal();
        System.out.println(userDetail);

        model.addObject("username", userDetail.getUsername());

    }

    model.setViewName(checkName("404", request));
    return model;

}
项目:webanno    文件:LoginPage.java   
private void redirectIfAlreadyLoggedIn()
{
    // If we are already logged in, redirect to the welcome page. This tries to a void a
    // situation where the user tries to access the login page directly and thus the
    // application would redirect the user to the login page after a successful login
    if (!(SecurityContextHolder.getContext()
            .getAuthentication() instanceof AnonymousAuthenticationToken)) {
        log.debug("Already logged in, forwarding to home page");
        throw new RestartResponseException(getApplication().getHomePage());
    }

    String redirectUrl = getRedirectUrl();
    if (redirectUrl == null) {
        log.debug("Authentication required");
    }
    else {
        log.debug("Authentication required (original URL: [{}])", redirectUrl);
    }
}
项目:workbenchauth    文件:HomeController.java   
@RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accesssDenied() {

  final ModelAndView model = new ModelAndView();

  // check if user is login
  final Authentication auth = SecurityContextHolder.getContext()
      .getAuthentication();
  if (!(auth instanceof AnonymousAuthenticationToken)) {
    final UserDetails userDetail = (UserDetails) auth.getPrincipal();
    model.addObject("username", userDetail.getUsername());
  }

  model.setViewName("403");
  return model;

}
项目:eds-starter6-jpa    文件:AppLocaleResolver.java   
@Override
public Locale resolveLocale(HttpServletRequest request) {
    Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
    if (authentication == null
            || authentication instanceof AnonymousAuthenticationToken) {
        return request.getLocale();
    }
    else if (authentication.getPrincipal() instanceof JpaUserDetails) {
        return ((JpaUserDetails) authentication.getPrincipal()).getLocale();
    }
    else if (getDefaultLocale() != null) {
        return getDefaultLocale();
    }
    else {
        return Locale.ENGLISH;
    }
}
项目:cf-SpringBootTrader    文件:UserController.java   
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
    if (!model.containsAttribute("login")) {
        model.addAttribute("login", new AuthenticationRequest());
    }
    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("User logged in: " + currentUserName);

        try {
            model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
        model.addAttribute("account",accountService.getAccount(currentUserName));
    }

    return "index";
}
项目:cf-SpringBootTrader    文件:TradeController.java   
@RequestMapping(value = "/trade", method = RequestMethod.GET)
public String showTrade(Model model) {
    logger.debug("/trade.GET");

    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());
        //TODO: add account summary?
        try {
            model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
    }

    return "trade";
}
项目:cf-SpringBootTrader    文件:TradeController.java   
@RequestMapping(value = "/order", method = RequestMethod.POST)
public String buy(Model model, @ModelAttribute("order") Order order) {
    model.addAttribute("search", new Search());

    // buy the order after setting attributes not set by the UI.
    //check if user is logged in!
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (!(authentication instanceof AnonymousAuthenticationToken)) {
                String currentUserName = authentication.getName();
                logger.debug("/order ORDER: " + order);
                order.setAccountId(currentUserName);
                order.setCompletionDate(new Date());

                Order result = marketService.sendOrder(order);
                model.addAttribute("savedOrder", result);
                model.addAttribute("order", new Order());
                try {
                    model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
                } catch (HttpServerErrorException e) {
                    model.addAttribute("portfolioRetrievalError",e.getMessage());
                }
            } else {
                //should never get here!!!
            }
    return "trade";
}
项目:cf-SpringBootTrader    文件:PortfolioController.java   
@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",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            logger.debug("error retrieving portfolfio: " + e.getMessage());
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
        model.addAttribute("order", new Order());
    }

    return "portfolio";
}
项目:eds-starter6-mongodb    文件:AppLocaleResolver.java   
@Override
public Locale resolveLocale(HttpServletRequest request) {
    Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
    if (authentication == null
            || authentication instanceof AnonymousAuthenticationToken) {
        return request.getLocale();
    }
    else if (authentication.getPrincipal() instanceof MongoUserDetails) {
        return ((MongoUserDetails) authentication.getPrincipal()).getLocale();
    }
    else if (getDefaultLocale() != null) {
        return getDefaultLocale();
    }
    else {
        return Locale.ENGLISH;
    }
}
项目:swagger-cxf-rest-skeleton    文件:LoginAuthenticationSuccessHandler.java   
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException, ServletException {

    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        final UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        final String token = authenticationTokenService.generateAuthenticationToken(userDetails.getUsername());

        final Cookie cookie = new Cookie("api_token", token);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);

        response.setStatus(HttpServletResponse.SC_OK);
    }
}
项目:cosmo    文件:CosmoSecurityContextImpl.java   
protected void processPrincipal() {  
    //anonymous principals do not have CosmoUserDetails and by
    //definition are not running as other principals
    if (getPrincipal() instanceof AnonymousAuthenticationToken) {
        setAnonymous(true);
    } else if (getPrincipal() instanceof UsernamePasswordAuthenticationToken) {
        CosmoUserDetails details = (CosmoUserDetails)
            ((Authentication) getPrincipal()).getPrincipal();
        setUser(details.getUser());
        setAdmin(details.getUser().getAdmin().booleanValue());
    } else if (getPrincipal() instanceof TicketAuthenticationToken) {
        Ticket ticket = (Ticket)((Authentication) getPrincipal()).getPrincipal();
        setTicket(ticket);
    } else {
        throw new CosmoException("Unknown principal type " + getPrincipal().getClass().getName(),
                new CosmoException());
    }
}
项目:midpoint    文件:MidpointRestSecurityQuestionsAuthenticator.java   
private List<SecurityQuestionDefinitionType> getQuestions(PrismObject<UserType> user) {
    return getSecurityContextManager().runPrivileged(new Producer<List<SecurityQuestionDefinitionType>>() {

        @Override
        public List<SecurityQuestionDefinitionType> run() {
            Task task = getTaskManager().createTaskInstance("Search user by name");
            OperationResult result = task.getResult();
            SecurityPolicyType securityPolicyType = null;
            try {
                SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("rest_sec_q_auth", "REST", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
                securityPolicyType = modelInteractionService.getSecurityPolicy(user, task, result);
            } catch (ObjectNotFoundException | SchemaException e) {
                return null;
            } finally {
                SecurityContextHolder.getContext().setAuthentication(null);
            }
            if (securityPolicyType.getCredentials() != null && securityPolicyType.getCredentials().getSecurityQuestions() != null){
                return securityPolicyType.getCredentials().getSecurityQuestions().getQuestion();
            }
            return null;
        }
    });

}
项目:spring-boot-security-saml-sample    文件:SSOController.java   
@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:/";
        }
    }
}
项目:spring-boot-security-saml-sample    文件:CommonTestSupport.java   
public MockHttpSession mockAnonymousHttpSession() {
    MockHttpSession mockSession = new MockHttpSession();

    SecurityContext mockSecurityContext = mock(SecurityContext.class);

    AnonymousAuthenticationToken principal =
            new AnonymousAuthenticationToken(
                    ANONYMOUS_USER_KEY,
                    ANONYMOUS_USER_PRINCIPAL,
                    AUTHORITIES);

    when(mockSecurityContext.getAuthentication()).thenReturn(principal);

    SecurityContextHolder.setContext(mockSecurityContext);
    mockSession.setAttribute(
            HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            mockSecurityContext);

    return mockSession;
}