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:com.healthcit.cacure.security.AuthenticationProcessingFilter.java
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try {//from www . j a v a 2 s. c o m //call to daoAuthenticationProvider Authentication auth = super.attemptAuthentication(request, response); //store currentUser in HttpSession UserCredentials currentUser = userService.findByName(auth.getName()); request.getSession().setAttribute(Constants.CURRENT_USER, currentUser); //display info about currentUser Collection<GrantedAuthority> gs = auth.getAuthorities(); StringBuilder sb = new StringBuilder("===== Authentification Succesful : userName = " + auth.getName()); sb.append(" with roles: "); for (GrantedAuthority x : gs) { sb.append(x.getAuthority()).append(","); } log.info(sb); return auth; } catch (AuthenticationException e) { log.info("Login wasn't successful for " + obtainUsername(request)); throw e; } }
From source file:com.nec.harvest.servlet.interceptor.BackOriginGroupInterceptor.java
@Override @SuppressWarnings("unchecked") public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { final User userPricipal = AuthenticatedUserDetails.getUserPrincipal(); if (userPricipal == null || userPricipal.getOrganization() == null) { if (logger.isDebugEnabled()) { logger.debug("Please login again with right permission"); }/*from w ww . j a va2 s.com*/ logger.info("Sorry, you don't have permission to access this url"); // Sorry, you don't have permission to access this url. Please login again with right permission response.setContentType(HttpServletContentType.PLAN_TEXT); response.sendRedirect(request.getContextPath() + "/logout"); response.flushBuffer(); return false; } final HandlerMethod handlerMethod = (org.springframework.web.method.HandlerMethod) handler; final Object controller = handlerMethod.getBean(); if (controller instanceof MenuController) { return super.preHandle(request, response, handler); } final Map<String, Object> pathVariables = (Map<String, Object>) request .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); final String PRO_GROUP_NO = "proGNo"; final String proGroupNo = (String) pathVariables.get(PRO_GROUP_NO); final boolean hasMenuGroups = menuGroupService .hasMenuGroupByUserRoleAndSpecificGroup(userPricipal.getUsrKbn(), proGroupNo); if (!hasMenuGroups) { logger.info("Sorry, you don't have permission to access this url"); // Sorry, you don't have permission to access this url. Please login again with right permission response.setContentType(HttpServletContentType.PLAN_TEXT); response.sendRedirect(request.getContextPath() + "/logout"); response.flushBuffer(); return false; } final String ORG_CODE = "orgCode"; final HttpSession session = request.getSession(); // Get active original code String orgCode = (String) pathVariables.get(ORG_CODE); if (StringUtils.isNotEmpty(orgCode)) { final String userOrgCode = (String) session.getAttribute(Constants.SESS_ORGANIZATION_CODE); if (!userOrgCode.equals(orgCode)) { logger.info("Sorry, you don't have permission to access this url"); // Sorry, you don't have permission to access this url. Please login again with right permission response.setContentType(HttpServletContentType.PLAN_TEXT); response.sendRedirect(request.getContextPath() + "/logout"); response.flushBuffer(); return false; } } // All of original groups String[] processGroupNumbers = null; if (controller instanceof DailyReportingProGroup) { processGroupNumbers = ((DailyReportingProGroup) controller).getProcessGroupNumber(); } else if (controller instanceof MasterManagementProGroup) { processGroupNumbers = ((MasterManagementProGroup) controller).getProcessGroupNumber(); } else if (controller instanceof ProfitAndLossManagementProGroup) { processGroupNumbers = ((ProfitAndLossManagementProGroup) controller).getProcessGroupNumber(); } // If the end-user already logged in into Harvest system, but have an error occurred // when trying to set some information into SESSION then we can reset again that // information into SESSION orgCode = (String) session.getAttribute(Constants.SESS_ORGANIZATION_CODE); if (orgCode == null) { session.setAttribute(Constants.SESS_ORGANIZATION_CODE, userPricipal.getOrganization().getStrCode()); } final Object businessDay = session.getAttribute(Constants.SESS_BUSINESS_DAY); if (businessDay == null) { BusinessDayService businessDayService = ContextAwareContainer.getInstance() .getComponent(BusinessDayService.class); final BusinessDay businessDate = businessDayService.findLatest(); // session.setAttribute(Constants.SESS_BUSINESS_DAY, businessDate.getEigDate()); } // Granted authority of user logged-in final String grantedAuthority = userPricipal.getUsrKbn(); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); for (GrantedAuthority authority : authentication.getAuthorities()) { logger.info("User {} was logged-in with granted role {}", authentication.getName(), authority.getAuthority()); } /** * ? * * 1?2?3??4 */ logger.info( "Granted authority of logged user: {}, NOTE: 1?2?3??4", grantedAuthority); // if (StringUtils.isNotEmpty(grantedAuthority)) { if (ArrayUtils.isNotEmpty(processGroupNumbers)) { // Trying to store the original group menu into the REQUEST final String processGroupNumber = processGroupNumbers[Integer.valueOf(grantedAuthority) - 1]; request.setAttribute(Constants.SESS_ORIGINAL_GROUP, processGroupNumber); // logger.info("Were are trying to handle the sub-menu of group {}", processGroupNumber); } } return super.preHandle(request, response, handler); }
From source file:com.formkiq.core.service.SpringSecurityService.java
/** * Whether User is admin.//from w w w. j a v a2s . co m * @return boolean */ public boolean isAdmin() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { for (GrantedAuthority grantedAuthority : auth.getAuthorities()) { if (UserRole.ROLE_ADMIN.name().equals(grantedAuthority.getAuthority())) { return true; } } } return false; }
From source file:shiver.me.timbers.spring.security.jwt.JwtPrincipalAuthenticationConverterTest.java
@Test @SuppressWarnings("unchecked") public void Can_convert_an_authentication_with_a_username_to_a_jwt_principle() { final Authentication authentication = mock(Authentication.class); final String username = someString(); final Collection<GrantedAuthority> authorities = mock(Collection.class); final List<String> roles = mock(List.class); // Given/*from ww w. java2 s . com*/ given(authentication.getPrincipal()).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.javaeeeee.components.JpaAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Optional<User> optional = usersRepository.findByUsernameAndPassword(authentication.getName(), authentication.getCredentials().toString()); if (optional.isPresent()) { return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), authentication.getAuthorities()); } else {//from www .j a va2 s .com throw new AuthenticationCredentialsNotFoundException("Wrong credentials."); } }
From source file:org.vaadin.spring.security.Security.java
/** * Checks if the current user has the specified authority. This method works with static authorities (such as roles). * If you need more dynamic authorization (such as ACLs or EL expressions), use {@link #hasAccessToObject(Object, String...)}. * * @param authority the authority to check, must not be {@code null}. * @return true if the current {@link org.springframework.security.core.context.SecurityContext} contains an authenticated {@link org.springframework.security.core.Authentication} * token that has a {@link org.springframework.security.core.GrantedAuthority} whose string representation matches the specified {@code authority}. * @see org.springframework.security.core.Authentication#getAuthorities() * @see org.springframework.security.core.GrantedAuthority#getAuthority() *//*ww w. j a v a2s . c om*/ public boolean hasAuthority(String authority) { final Authentication authentication = getAuthentication(); if (authentication == null || !authentication.isAuthenticated()) { return false; } for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) { if (authority.equals(grantedAuthority.getAuthority())) { return true; } } return false; }
From source file:nu.localhost.tapestry5.springsecurity.components.IfRole.java
@SuppressWarnings("unchecked") private Collection<GrantedAuthority> getPrincipalAuthorities() { Authentication currentUser = null; currentUser = SecurityContextHolder.getContext().getAuthentication(); if (null == currentUser) { return Collections.emptyList(); }/*from w ww .j a v a2s .c om*/ if ((null == currentUser.getAuthorities()) || (currentUser.getAuthorities().size() < 1)) { return Collections.emptyList(); } return (Collection<GrantedAuthority>) currentUser.getAuthorities(); }
From source file:de.itsvs.cwtrpc.sample1.server.service.SampleServiceImpl.java
public String getInfo() { final StringBuilder info = new StringBuilder(); final Authentication auth; boolean first; auth = SecurityContextHolder.getContext().getAuthentication(); log.info("User '" + auth.getName() + "' is requesting info"); info.append("Number of Requests: " + (++infoCount) + "\n"); info.append("User Name: " + auth.getName() + "\n"); info.append("Roles: "); first = true;//from w w w .j av a 2 s . c o m for (GrantedAuthority ga : auth.getAuthorities()) { if (!first) { info.append(", "); } first = false; info.append(ga.getAuthority()); } return info.toString(); }
From source file:edu.uiowa.icts.authentication.AuthHandle.java
/** {@inheritDoc} */ @Override/*from w w w. j a va 2 s . c o m*/ public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth) throws IOException, ServletException { log.debug("successfully authenticated " + String.valueOf(auth.getPrincipal())); if (req.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION") != null) { req.getSession().removeAttribute("SPRING_SECURITY_LAST_EXCEPTION"); } for (GrantedAuthority ga : auth.getAuthorities()) { log.debug(ga.getAuthority()); } HttpSession session = req.getSession(); String username = req.getParameter("j_username"); session.setAttribute("username", username); AuditLogger.info(session.getId(), username, "logged in from", req.getRemoteHost()); target.onAuthenticationSuccess(req, res, auth); }