org.springframework.security.authentication.AnonymousAuthenticationToken Java Examples
The following examples show how to use
org.springframework.security.authentication.AnonymousAuthenticationToken.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserUtils.java From syhthems-platform with MIT License | 8 votes |
/** * 从 Spring Security Context中获取 username 再获取 CustomUserDetails,若找不到则返回 null * * @return */ public CustomUserDetails getCustomUserDetailsFromSecurityContextHolderWithUsername() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { return null; } String username; if (authentication instanceof JwtAuthenticationToken) { username = ((JwtAuthenticationToken) authentication).getTokenAttributes().get("user_name").toString(); } else { username = authentication.getName(); } try { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (userDetails instanceof CustomUserDetails) { return ((CustomUserDetails) userDetails).erasePassword(); } return null; } catch (IllegalArgumentException e) { return null; } }
Example #2
Source File: CosmoSecurityContextImpl.java From cosmo with Apache License 2.0 | 6 votes |
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()); } }
Example #3
Source File: SecurityController.java From spring-cloud-dashboard with Apache License 2.0 | 6 votes |
/** * 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; }
Example #4
Source File: AnalyticsController.java From pivotal-bank-demo with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/analytics", method = RequestMethod.POST) public String showTrade(Model model, @ModelAttribute("search") Search search) { logger.debug("/analytics.POST - symbol: " + search.getName()); model.addAttribute("search", search); if (search.getName() == null || search.getName().equals("") ) { model.addAttribute("trades", new ArrayList<Trade>()); } else { model.addAttribute("trades", analyticsService.getTrades(search.getName())); } //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); } return "analytics"; }
Example #5
Source File: SSOController.java From spring-boot-security-saml-sample with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/discovery", method = RequestMethod.GET) public String idpSelection(HttpServletRequest request, Model model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null) LOG.debug("Current authentication instance from security context is null"); else LOG.debug("Current authentication instance from security context: " + this.getClass().getSimpleName()); if (auth == null || (auth instanceof AnonymousAuthenticationToken)) { Set<String> idps = metadata.getIDPEntityNames(); for (String idp : idps) LOG.info("Configured Identity Provider for SSO: " + idp); model.addAttribute("idps", idps); return "pages/discovery"; } else { LOG.warn("The current user is already logged."); return "redirect:/landing"; } }
Example #6
Source File: TradeController.java From cf-SpringBootTrader with Apache License 2.0 | 6 votes |
@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"; }
Example #7
Source File: AccountsController.java From pivotal-bank-demo with Apache License 2.0 | 6 votes |
@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"; }
Example #8
Source File: TradeController.java From cf-SpringBootTrader with Apache License 2.0 | 6 votes |
@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"; }
Example #9
Source File: TradeController.java From pivotal-bank-demo with Apache License 2.0 | 6 votes |
@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"; }
Example #10
Source File: LoginPage.java From webanno with Apache License 2.0 | 6 votes |
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); } }
Example #11
Source File: PortfolioController.java From cf-SpringBootTrader with Apache License 2.0 | 6 votes |
@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"; }
Example #12
Source File: PortfolioController.java From pivotal-bank-demo with Apache License 2.0 | 6 votes |
@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"; }
Example #13
Source File: RefreshTokenController.java From production-ready-microservices-starter with MIT License | 6 votes |
/** * Handle refresh token request. * * @param request the request * @param response the response * @param authentication the authentication * @return the response entity */ @GetMapping(value = "/refresh", produces = APPLICATION_JSON_VALUE) public ResponseEntity<Map<String, String>> refresh(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (authentication == null || authentication instanceof AnonymousAuthenticationToken || !authentication.isAuthenticated()) { log.debug("User should be authenticated in order to refresh token"); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } String authToken = authTokenBuilder.createAccessToken(authentication); Cookie authCookie = cookieUtil.getCookie(AUTH_COOKIE_NAME, urlUtil.utf8Encode("Bearer " + authToken)); authCookie.setPath("/"); authCookie.setHttpOnly(true); response.addCookie(authCookie); return new ResponseEntity<>(Collections.singletonMap("accessToken", authToken), HttpStatus.OK); }
Example #14
Source File: AccessManager.java From open-cloud with MIT License | 6 votes |
/** * 检查权限 * * @param exchange * @param authentication * @param requestPath * @return */ private boolean checkAuthorities(ServerWebExchange exchange, Authentication authentication, String requestPath) { Object principal = authentication.getPrincipal(); // 已认证身份 if (principal != null) { if (authentication instanceof AnonymousAuthenticationToken) { //check if this uri can be access by anonymous //return } if (authorityIgnores(requestPath)) { // 认证通过,并且无需权限 return true; } return mathAuthorities(exchange, authentication, requestPath); } return false; }
Example #15
Source File: AccessManager.java From open-cloud with MIT License | 6 votes |
/** * 检查权限 * * @param request * @param authentication * @param requestPath * @return */ private boolean checkAuthorities(HttpServletRequest request, Authentication authentication, String requestPath) { Object principal = authentication.getPrincipal(); // 已认证身份 if (principal != null) { if (authentication instanceof AnonymousAuthenticationToken) { //check if this uri can be access by anonymous //return } if (authorityIgnores(requestPath)) { // 认证通过,并且无需权限 return true; } return mathAuthorities(request, authentication, requestPath); } return false; }
Example #16
Source File: CrafterPageAccessManager.java From engine with GNU General Public License v3.0 | 6 votes |
/** * Checks if the user has sufficient rights to access the specified page: * * <ol> * <li>If the page doesn't contain any required role, no authentication is needed.</li> * <li>If the page has the role "Anonymous", no authentication is needed.</li> * <li>If the page has the role "Authenticated", just authentication is needed.</li> * <li>If the page has any other the roles, the user needs to have any of those roles.</li> * </ol> */ @RunIfSecurityEnabled public void checkAccess(SiteItem page) { String pageUrl = page.getStoreUrl(); Authentication auth = null; SecurityContext context = SecurityContextHolder.getContext(); if (context != null && context.getAuthentication() != null) { auth = context.getAuthentication(); } List<String> authorizedRoles = getAuthorizedRolesForPage(page); if (CollectionUtils.isNotEmpty(authorizedRoles) && !containsRole("anonymous", authorizedRoles)) { // If auth == null it is anonymous if (auth == null || auth instanceof AnonymousAuthenticationToken) { throw new AccessDeniedException("User is anonymous but page '" + pageUrl + "' requires authentication"); } if (!containsRole("authenticated", authorizedRoles) && !hasAnyRole(auth, authorizedRoles)) { throw new AccessDeniedException("User '" + auth.getName() + "' is not authorized " + "to view page '" + pageUrl + "'"); } } }
Example #17
Source File: LoginContextSpringSecutiryImpl.java From Guns with GNU Lesser General Public License v3.0 | 5 votes |
@Override public boolean hasLogin() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return false; } else { if (authentication instanceof AnonymousAuthenticationToken) { return false; } else { return true; } } }
Example #18
Source File: JWTAuthorisationFilter.java From yes-cart with Apache License 2.0 | 5 votes |
/** * Determine if authentication is required. * * @param username username * * @return true if need to authenticate */ protected boolean authenticationIsRequired(String username) { // Only reauthenticate if username doesn't match SecurityContextHolder and user // isn't authenticated // (see SEC-53) Authentication existingAuth = SecurityContextHolder.getContext() .getAuthentication(); if (existingAuth == null || !existingAuth.isAuthenticated()) { return true; } // Limit username comparison to providers which use usernames (ie // UsernamePasswordAuthenticationToken) // (see SEC-348) if (existingAuth instanceof UsernamePasswordAuthenticationToken && !existingAuth.getName().equals(username)) { return true; } // Handle unusual condition where an AnonymousAuthenticationToken is already // present // This shouldn't happen very often, as BasicProcessingFitler is meant to be // earlier in the filter // chain than AnonymousAuthenticationFilter. Nevertheless, presence of both an // AnonymousAuthenticationToken // together with a BASIC authentication request header should indicate // reauthentication using the // BASIC protocol is desirable. This behaviour is also consistent with that // provided by form and digest, // both of which force re-authentication if the respective header is detected (and // in doing so replace // any existing AnonymousAuthenticationToken). See SEC-610. if (existingAuth instanceof AnonymousAuthenticationToken) { return true; } return false; }
Example #19
Source File: SecurityContextFilter.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return (authentication instanceof AnonymousAuthenticationToken) ? null : authentication; } @Override public boolean isUserInRole(final String role) { return SecurityContextHolder.getContext().getAuthentication().getAuthorities() .stream().anyMatch((Predicate<GrantedAuthority>) grantedAuthority -> grantedAuthority.getAuthority().equalsIgnoreCase(role)); } @Override public boolean isSecure() { return requestContext.getUriInfo().getRequestUri().getScheme().equalsIgnoreCase("https"); } @Override public String getAuthenticationScheme() { return requestContext.getUriInfo().getRequestUri().getScheme(); } }); }
Example #20
Source File: SecurityContextFilter.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return (authentication instanceof AnonymousAuthenticationToken) ? null : authentication; } @Override public boolean isUserInRole(final String role) { return SecurityContextHolder.getContext().getAuthentication().getAuthorities() .stream().anyMatch((Predicate<GrantedAuthority>) grantedAuthority -> grantedAuthority.getAuthority().equalsIgnoreCase(role)); } @Override public boolean isSecure() { return requestContext.getUriInfo().getRequestUri().getScheme().equalsIgnoreCase("https"); } @Override public String getAuthenticationScheme() { return requestContext.getUriInfo().getRequestUri().getScheme(); } }); }
Example #21
Source File: UniTimeAnonymousAuthenticationFilter.java From unitime with Apache License 2.0 | 5 votes |
@Override protected Authentication createAuthentication(HttpServletRequest request) { try { AnonymousUserContext user = new AnonymousUserContext(); if (!user.getAuthorities().isEmpty()) return new AnonymousAuthenticationToken("guest", user, user.getAuthorities()); else return super.createAuthentication(request); } catch (Throwable t) { return super.createAuthentication(request); } }
Example #22
Source File: Oauth2AuthenticationInterceptor.java From grpc-spring-security-demo with MIT License | 5 votes |
private boolean authenticationIsRequired() { Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); if (Objects.isNull(existingAuth) || !existingAuth.isAuthenticated()) { return true; } if (existingAuth instanceof AnonymousAuthenticationToken) { return true; } return false; }
Example #23
Source File: AbstractServiceFunctionalIntegrationTest.java From cia with Apache License 2.0 | 5 votes |
/** * Sets the authenticated adminuser. */ protected final void setAuthenticatedAdminuser() { final Collection<SimpleGrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(ROLE_ADMIN)); authorities.add(new SimpleGrantedAuthority(ROLE_ANONYMOUS)); SecurityContextHolder.getContext() .setAuthentication(new AnonymousAuthenticationToken(KEY, PRINCIPAL, authorities)); }
Example #24
Source File: LoginController.java From auth-server with Apache License 2.0 | 5 votes |
/** * <p> * Return login page or redirect user to profile if already logged in. * </p> */ @GetMapping("/login") public String login() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { // The user is logged in return "redirect:/profile"; } return "login"; }
Example #25
Source File: DefaultAuthenticatingServerInterceptor.java From grpc-spring-boot-starter with MIT License | 5 votes |
@Override public void onHalfClose() { try { super.onHalfClose(); } catch (final AccessDeniedException e) { if (this.authentication instanceof AnonymousAuthenticationToken) { throw new BadCredentialsException("No credentials found in the request", e); } else { throw e; } } }
Example #26
Source File: ResourceUtil.java From secure-data-service with Apache License 2.0 | 5 votes |
/** * Analyzes security context to get SLIPrincipal for user. * * @return SLIPrincipal from security context */ public static SLIPrincipal getSLIPrincipalFromSecurityContext() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth instanceof AnonymousAuthenticationToken || auth.getPrincipal() instanceof String || !auth.isAuthenticated()) { throw new InsufficientAuthenticationException("Login Required"); } // lookup security/login information SLIPrincipal principal = (SLIPrincipal) auth.getPrincipal(); return principal; }
Example #27
Source File: LogoutService.java From cia with Apache License 2.0 | 5 votes |
@Override @Secured({ "ROLE_USER", "ROLE_ADMIN" }) public LogoutResponse processService(final LogoutRequest serviceRequest) { final LogoutResponse inputValidation = inputValidation(serviceRequest); if (inputValidation != null) { return inputValidation; } final CreateApplicationEventRequest eventRequest = createApplicationEventForService(serviceRequest); final UserAccount userAccount = getUserAccountFromSecurityContext(); LogoutResponse response; if (userAccount != null) { eventRequest.setElementId(userAccount.getEmail()); final Collection<SimpleGrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_ANONYMOUS")); final AnonymousAuthenticationToken anonymousAuthenticationToken = new AnonymousAuthenticationToken( serviceRequest.getSessionId(), "ROLE_ANONYMOUS", authorities); SecurityContextHolder.getContext().setAuthentication(anonymousAuthenticationToken); response=new LogoutResponse(ServiceResult.SUCCESS); } else { response= new LogoutResponse(ServiceResult.FAILURE); } eventRequest.setApplicationMessage(response.getResult().toString()); createApplicationEventService.processService(eventRequest); LOGGER.info("Event: {}",eventRequest); return response; }
Example #28
Source File: AppAnonAuthFilter.java From Spring-5.0-Cookbook with MIT License | 5 votes |
@Override protected Authentication createAuthentication(HttpServletRequest request) { System.out.println("ANON FILTER"); if(principal.equalsIgnoreCase(request.getParameter("username")) ){ AnonymousAuthenticationToken authTok = new AnonymousAuthenticationToken(key, principal, authorities); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(authTok); return authTok; } return null; }
Example #29
Source File: AppAnonAuthFilter.java From Spring-5.0-Cookbook with MIT License | 5 votes |
@Override protected Authentication createAuthentication(HttpServletRequest request) { System.out.println("ANON FILTER"); if(principal.equalsIgnoreCase(request.getParameter("username")) ){ AnonymousAuthenticationToken authTok = new AnonymousAuthenticationToken(key, principal, authorities); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(authTok); return authTok; } return null; }
Example #30
Source File: SupportResourceTest.java From secure-data-service with Apache License 2.0 | 5 votes |
@Test public void testGetEmailFailure() throws Exception { assertNotNull(resource); AnonymousAuthenticationToken anon = new AnonymousAuthenticationToken("anon", "anon", Arrays.<GrantedAuthority>asList(Right.ANONYMOUS_ACCESS)); anon.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(anon); try { resource.getEmail(); assertFalse(true); } catch (InsufficientAuthenticationException e) { assertTrue(true); } }