List of usage examples for org.springframework.security.core Authentication getAuthorities
Collection<? extends GrantedAuthority> getAuthorities();
AuthenticationManager
to indicate the authorities that the principal has been granted. From source file:eu.freme.broker.tools.ratelimiter.RateLimitingFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (rateLimiterEnabled) { HttpServletRequest request = (HttpServletRequest) req; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); username = auth.getName();//from w w w . java2 s . c o m if (username.equals("anonymousUser")) { username = req.getRemoteAddr(); } else { User user = ((User) auth.getPrincipal()); username = user.getName(); } userRole = ((SimpleGrantedAuthority) auth.getAuthorities().toArray()[0]).getAuthority(); long size = req.getContentLength(); if (size == 0) { try { size = request.getHeader("input").length(); } catch (NullPointerException e) { //Then the size is truly 0 } } try { rateLimiterInMemory.addToStoredRequests(username, new Date().getTime(), size, request.getRequestURI(), userRole); } catch (TooManyRequestsException e) { HttpServletResponse response = (HttpServletResponse) res; exceptionHandlerService.writeExceptionToResponse(request, response, e); return; } } chain.doFilter(req, res); }
From source file:com.stormpath.spring.security.authz.permission.evaluator.WildcardPermissionEvaluator.java
@Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { String domainObjectString = ""; if (targetDomainObject != null) { domainObjectString = targetDomainObject + WildcardPermission.PART_DIVIDER_TOKEN; }// ww w . ja v a2 s .c o m //Let's construct a WildcardPermission out of the given parameters Permission toMatch = new WildcardPermission(domainObjectString + permission); Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (GrantedAuthority authority : authorities) { //This evaluator only compares WildcardPermissions if (authority instanceof WildcardPermission) { WildcardPermission wp = (WildcardPermission) authority; //Let's delegate the actual comparison to the WildcardPermission if (wp.implies(toMatch)) { return true; } } } return false; }
From source file:org.apache.nifi.minifi.c2.security.authorization.GrantedAuthorityAuthorizer.java
@Override public void authorize(Authentication authentication, UriInfo uriInfo) throws AuthorizationException { if (authentication == null) { throw new AuthorizationException("null authentication object provided."); }// w w w . jav a 2 s. c om if (!authentication.isAuthenticated()) { throw new AuthorizationException(authentication + " not authenticated."); } Set<String> authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority) .collect(Collectors.toSet()); String defaultAction = as(String.class, grantedAuthorityMap.getOrDefault(DEFAULT_ACTION, DENY)); String path = uriInfo.getAbsolutePath().getPath(); Map<String, Object> pathAuthorizations = as(Map.class, grantedAuthorityMap.get("Paths")); if (pathAuthorizations == null && !ALLOW.equalsIgnoreCase(defaultAction)) { throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow"); } Map<String, Object> pathAuthorization = as(Map.class, pathAuthorizations.get(path)); if (pathAuthorization == null && !ALLOW.equalsIgnoreCase(defaultAction)) { throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow"); } defaultAction = as(String.class, pathAuthorization.getOrDefault(DEFAULT_ACTION, defaultAction)); List<Map<String, Object>> actions = as(List.class, pathAuthorization.get("Actions")); MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); for (Map<String, Object> action : actions) { String ruleAction = as(String.class, action.get("Action")); if (ruleAction == null || !(ALLOW.equalsIgnoreCase(ruleAction) || DENY.equalsIgnoreCase(ruleAction))) { throw new AuthorizationException("Expected Action key of allow or deny for " + action); } String authorization = as(String.class, action.get("Authorization")); if (authorization != null && !authorities.contains(authorization)) { continue; } Map<String, Object> parameters = as(Map.class, action.get("Query Parameters")); if (parameters != null) { boolean foundParameterMismatch = false; for (Map.Entry<String, Object> parameter : parameters.entrySet()) { Object value = parameter.getValue(); if (value instanceof String) { value = Arrays.asList((String) value); } if (!Objects.equals(queryParameters.get(parameter.getKey()), value)) { foundParameterMismatch = true; break; } } if (foundParameterMismatch) { continue; } } if (ALLOW.equalsIgnoreCase(ruleAction)) { if (logger.isDebugEnabled()) { logger.debug("Action " + action + "matched which resulted in " + ruleAction); } return; } else { throw new AuthorizationException("Action " + action + " matched which resulted in " + ruleAction); } } if (ALLOW.equalsIgnoreCase(defaultAction)) { if (logger.isDebugEnabled()) { logger.debug("Found no matching actions so falling back to default action " + defaultAction); } } else { throw new AuthorizationException("Didn't find authorizations for " + path + " and default policy is " + defaultAction + " instead of allow"); } }
From source file:eu.supersede.fe.rest.ApplicationRest.java
@RequestMapping("/page") public List<ApplicationGrouped> getUserAuthenticatedApplicationsPage(Authentication auth, Locale locale) { String lang = locale.getLanguage(); Map<String, ApplicationGrouped> appsMap = new HashMap<>(); Map<String, Map<String, Page>> appsPagesMap = new HashMap<>(); List<ApplicationGrouped> applications = new ArrayList<>(); List<String> authNames = new ArrayList<>(); Collection<? extends GrantedAuthority> authorities = auth.getAuthorities(); for (GrantedAuthority ga : authorities) { authNames.add(ga.getAuthority().substring(5)); }//from w ww . j av a 2s. c o m List<Profile> profList = profiles.findByNameIn(authNames); // make data nicer for frontend for (Profile p : profList) { Set<ApplicationPage> apps = applicationUtil.getApplicationsPagesByProfileName(p.getName()); for (ApplicationPage app : apps) { ApplicationGrouped ag; if (!appsMap.containsKey(app.getApplicationName())) { Application a = applicationUtil.getApplication(app.getApplicationName()); String appLabel = a.getLocalizedApplicationLabel(lang); ag = new ApplicationGrouped(app.getApplicationName(), appLabel); ag.setHomePage(a.getHomePage()); applications.add(ag); appsMap.put(app.getApplicationName(), ag); appsPagesMap.put(app.getApplicationName(), new HashMap<String, Page>()); } else { ag = appsMap.get(app.getApplicationName()); } Page page; if (!appsPagesMap.get(app.getApplicationName()).containsKey(app.getApplicationPage())) { page = new Page(app.getApplicationPage(), app.getLocalizedApplicationPageLabel(lang)); ag.getPages().add(page); appsPagesMap.get(app.getApplicationName()).put(app.getApplicationPage(), page); } } } return applications; }
From source file:shiver.me.timbers.spring.security.jwt.JwtPrincipalAuthenticationConverterTest.java
@Test @SuppressWarnings("unchecked") public void Can_convert_an_authentication_with_a_user_details_to_a_jwt_principle() { final Authentication authentication = mock(Authentication.class); final UserDetails userDetails = mock(UserDetails.class); final String username = someString(); final Collection<GrantedAuthority> authorities = mock(Collection.class); final List<String> roles = mock(List.class); // Given// ww w . j a v a2s. co m given(authentication.getPrincipal()).willReturn(userDetails); given(userDetails.getUsername()).willReturn(username); given(authentication.getAuthorities()).willReturn((Collection) authorities); given(grantedAuthorityConverter.convert(authorities)).willReturn(roles); // When final JwtPrincipal actual = converter.convert(authentication); // Then assertThat(actual.getUsername(), is(username)); assertThat(actual.getRoles(), is(roles)); }
From source file:com.himanshu.poc.h2.springboot.AuthenticationProviderImpl.java
@Override public Authentication authenticate(Authentication arg0) throws AuthenticationException { System.out.println(" User name is : " + arg0.getName()); //arg0.setAuthenticated(false); //return arg0; if (dummyUsernamePwdMap.get(arg0.getPrincipal()) != null && dummyUsernamePwdMap.get(arg0.getPrincipal()).equals(arg0.getCredentials())) { System.out.println("Auth success"); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(arg0.getPrincipal(), arg0.getCredentials(), arg0.getAuthorities()); return token; }/*from ww w .ja v a 2 s . co m*/ System.out.println("Auth failed"); return null; }
From source file:com.khs.sherpa.spring.SpringAuthentication.java
public String[] authenticate(String username, String password, HttpServletRequest request, HttpServletResponse response) {/* w w w . j a v a 2 s . c om*/ UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); Authentication authentication = null; try { authentication = authenticationManager.authenticate(token); } catch (AuthenticationException e) { throw new SherpaInvalidUsernamePassword("username and/or password is incorrect"); } if (authentication.isAuthenticated() == false) { throw new SherpaInvalidUsernamePassword("username and/or password is incorrect"); } List<String> roles = new ArrayList<String>(); for (GrantedAuthority auth : authentication.getAuthorities()) { roles.add(auth.getAuthority()); } SecurityContextImpl context = new SecurityContextImpl(); context.setAuthentication(authentication); SecurityContextHolder.setContext(context); request.getSession().setAttribute("SPRING_SECURITY_CONTEXT_KEY", context); return roles.toArray(new String[roles.size()]); }
From source file:ch.wisv.areafiftylan.teams.controller.TeamRestController.java
/** * The method to handle POST requests on the /teams endpoint. This creates a new team. Users can only create new * Teams with themselves as Captain. Admins can also create Teams with other Users as Captain. * * @param teamDTO Object containing the Team name and Captain username. When coming from a user, username should * equal their own username. * @param auth Authentication object from Spring Security * * @return Return status message of the operation *//*from w w w.ja v a 2 s . c o m*/ @PreAuthorize("isAuthenticated() and @currentUserServiceImpl.hasAnyTicket(principal)") @JsonView(View.Public.class) @RequestMapping(method = RequestMethod.POST) ResponseEntity<?> add(@Validated @RequestBody TeamDTO teamDTO, Authentication auth) { if (teamService.teamnameUsed(teamDTO.getTeamName())) { return createResponseEntity(HttpStatus.CONFLICT, "Team with name \"" + teamDTO.getTeamName() + "\" already exists."); } Team team; // Users can only create teams with themselves as Captain if (auth.getAuthorities().contains(Role.ROLE_ADMIN)) { team = teamService.create(teamDTO.getCaptainUsername(), teamDTO.getTeamName()); } else { // If the DTO contains another username as the the current user, return an error. if (!auth.getName().equalsIgnoreCase(teamDTO.getCaptainUsername())) { return createResponseEntity(HttpStatus.BAD_REQUEST, "Can not create team with another user as Captain"); } team = teamService.create(auth.getName(), teamDTO.getTeamName()); } HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") .buildAndExpand(team.getId()).toUri()); return createResponseEntity(HttpStatus.CREATED, httpHeaders, "Team successfully created at " + httpHeaders.getLocation(), team); }
From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityAccessDeniedHandler.java
protected List<Set<String>> getCombinationsOfAdditionalProviderIds() { Authentication existingAuthentication = SecurityContextHolder.getContext().getAuthentication(); Set<String> unconnectedProviders = new HashSet<String>(); for (String registeredProviderId : connectionFactoryLocator.registeredProviderIds()) { GrantedAuthority providerAuthority = userAuthoritiesService.getProviderAuthority(registeredProviderId); if (existingAuthentication == null || !existingAuthentication.getAuthorities().contains(providerAuthority)) { unconnectedProviders.add(registeredProviderId); }/*from w w w .j av a2 s . c o m*/ } CombinationHelper<String> combinationHelper = new CombinationHelper<String>(unconnectedProviders); return combinationHelper.getCombinations(); }
From source file:rashjz.info.com.az.util.UserLoginSuccessHandler.java
@Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { HttpSession session = httpServletRequest.getSession(); UserDetails authUser = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // AppUser localUser = new AppUser(null, authUser.getUsername(), authUser.getUsername(), true, true, true, true, authUser.getAuthorities()); // SecurityUtil.authenticateUser(localUser); session.setAttribute("username", authUser.getUsername()); session.setAttribute("authorities", authentication.getAuthorities()); //set our response to OK status httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.sendRedirect("admin"); }