org.springframework.security.core.Authentication Java Examples
The following examples show how to use
org.springframework.security.core.Authentication.
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 Project: sakai Author: sakaiproject File: JwtAuthenticationTokenFilter.java License: Educational Community License v2.0 | 7 votes |
/** * Attempt to authenticate request - basically just pass over to another method to authenticate request headers */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { String header = request.getHeader(tokenHeader); if (header == null || !header.startsWith("Bearer ")) { throw new JwtTokenMissingException("No JWT token found in request headers"); } String authToken = header.substring(7); if (SecurityContextHolder.getContext().getAuthentication() == null) { JwtAuthenticationToken authentication = new JwtAuthenticationToken(authToken); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } return SecurityContextHolder.getContext().getAuthentication(); }
Example #2
Source Project: nifi Author: apache File: KerberosService.java License: Apache License 2.0 | 6 votes |
public Authentication validateKerberosTicket(HttpServletRequest request) { // Only support Kerberos login when running securely if (!request.isSecure()) { return null; } String header = request.getHeader(AUTHORIZATION_HEADER_NAME); if (isValidKerberosHeader(header)) { if (logger.isDebugEnabled()) { logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header); } byte[] base64Token = header.substring(header.indexOf(" ") + 1).getBytes(StandardCharsets.UTF_8); byte[] kerberosTicket = Base64.decode(base64Token); KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket); authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request)); return kerberosServiceAuthenticationProvider.authenticate(authenticationRequest); } else { return null; } }
Example #3
Source Project: maintain Author: zhaopei8948 File: MyAccessDecisionManager.java License: MIT License | 6 votes |
@Override public void decide(Authentication authentication, Object obj, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (null == configAttributes || configAttributes.size() <= 0) { logger.info("decide == return"); return; } ConfigAttribute c; String needRole; for (Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext();) { c = iter.next(); needRole = c.getAttribute(); logger.info("need======" + needRole.trim() + " size=" + authentication.getAuthorities()); for (GrantedAuthority ga : authentication.getAuthorities()) { logger.info("needRole==" + needRole.trim() + " [] = authority=" + ga.getAuthority()); // authentication 为在注释1 中循环添加到 GrantedAuthority 对象中的权限信息集合 if (needRole.trim().equals(ga.getAuthority())) { return; } } } throw new AccessDeniedException("no right"); }
Example #4
Source Project: onetwo Author: wayshall File: DefaultJwtSecurityTokenService.java License: Apache License 2.0 | 6 votes |
@Override public Authentication createAuthentication(String token) throws BadCredentialsException { Claims claims = createClaimsFromToken(token); DateTime expireation = new DateTime(claims.getExpiration()); if(expireation.isBeforeNow()){ return null; } String authorityString = claims.get(JwtSecurityUtils.CLAIM_AUTHORITIES).toString(); List<GrantedAuthority> authorities = GuavaUtils.splitAsStream(authorityString, ",").map(auth->{ return new SimpleGrantedAuthority(auth); }) .collect(Collectors.toList()); Authentication authentication = buildAuthentication(claims, authorities); return authentication; }
Example #5
Source Project: Spring-Security-Third-Edition Author: PacktPublishing File: SpringSecurityUserContext.java License: MIT License | 6 votes |
/** * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our * application Spring Security usernames are email addresses). */ @Override public CalendarUser getCurrentUser() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); if (authentication == null) { return null; } CalendarUser user = (CalendarUser) authentication.getPrincipal(); String email = user.getEmail(); if (email == null) { return null; } CalendarUser result = calendarService.findUserByEmail(email); if (result == null) { throw new IllegalStateException( "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email); } logger.info("CalendarUser: {}", result); return result; }
Example #6
Source Project: hauth-java Author: hzwy23 File: CustomAuthenticationProvider.java License: MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // 获取认证的用户名 & 密码 String name = authentication.getName(); Object pd = authentication.getCredentials(); if (pd == null) { return new UsernamePasswordAuthenticationToken(name, "", new ArrayList<>()); } String password = pd.toString(); UserLoginEntity userLoginEntity = loginService.loginValidator(name, password); // 认证逻辑 if (userLoginEntity.isFlag()) { return getRole(name, password); } else { logger.info("登录失败,原因是:账号 {}: {}", userLoginEntity.getUsername(), userLoginEntity.getMessage()); throw new BadCredentialsException(new GsonBuilder().create().toJson(userLoginEntity)); } }
Example #7
Source Project: todo-spring-angular Author: aksakalli File: AjaxLogoutSuccessHandler.java License: MIT License | 6 votes |
@Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // Request the token String token = request.getHeader("authorization"); if (token != null && token.startsWith(BEARER_AUTHENTICATION)) { final OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(StringUtils.substringAfter(token, BEARER_AUTHENTICATION)); if (oAuth2AccessToken != null) { tokenStore.removeAccessToken(oAuth2AccessToken); } } response.setStatus(HttpServletResponse.SC_OK); }
Example #8
Source Project: herd Author: FINRAOS File: UserNamespaceAuthorizationServiceTest.java License: Apache License 2.0 | 6 votes |
@Test public void testUpdateUserNamespaceAuthorizationLowerCaseParameters() { // Override the security context to return an application user populated with test values. Authentication originalAuthentication = overrideSecurityContext(); // Create a user namespace authorization key. UserNamespaceAuthorizationKey key = new UserNamespaceAuthorizationKey(USER_ID, NAMESPACE); // Create and persist the relative database entities. UserNamespaceAuthorizationEntity userNamespaceAuthorizationEntity = userNamespaceAuthorizationDaoTestHelper .createUserNamespaceAuthorizationEntity(key, Arrays.asList(NamespacePermissionEnum.READ, NamespacePermissionEnum.WRITE)); // Update a user namespace authorization using lowercase input parameters. UserNamespaceAuthorization resultUserNamespaceAuthorization = userNamespaceAuthorizationService .updateUserNamespaceAuthorization(new UserNamespaceAuthorizationKey(key.getUserId().toLowerCase(), key.getNamespace().toLowerCase()), new UserNamespaceAuthorizationUpdateRequest(SUPPORTED_NAMESPACE_PERMISSIONS)); // Validate the returned object. assertEquals(new UserNamespaceAuthorization(userNamespaceAuthorizationEntity.getId(), key, SUPPORTED_NAMESPACE_PERMISSIONS), resultUserNamespaceAuthorization); // Restore the original authentication. restoreSecurityContext(originalAuthentication); }
Example #9
Source Project: alf.io Author: alfio-event File: ReservationApiV2Controller.java License: GNU General Public License v3.0 | 6 votes |
private ResponseEntity<Void> handleReservationWith(String eventName, String reservationId, Authentication authentication, BiFunction<Event, TicketReservation, ResponseEntity<Void>> with) { ResponseEntity<Void> notFound = ResponseEntity.notFound().build(); ResponseEntity<Void> badRequest = ResponseEntity.badRequest().build(); return eventRepository.findOptionalByShortName(eventName).map(event -> { if(canAccessReceiptOrInvoice(event, authentication)) { return ticketReservationManager.findById(reservationId).map(ticketReservation -> with.apply(event, ticketReservation)).orElse(notFound); } else { return badRequest; } } ).orElse(notFound); }
Example #10
Source Project: demo-project Author: FleyX File: MyAccessDecisionManager.java License: MIT License | 6 votes |
@Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { //无需验证放行 if(configAttributes==null || configAttributes.size()==0) return; log.info("开始验证"); // if(!authentication.isAuthenticated()){ if(authenticationTrustResolver.isAnonymous(authentication)){ throw new InsufficientAuthenticationException("未登录"); } Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for(ConfigAttribute attribute : configAttributes){ if(!(attribute instanceof MyConfigAttribute)) continue; MyConfigAttribute urlConfigAttribute = (MyConfigAttribute)attribute; for(GrantedAuthority authority: authorities){ if(!(authority instanceof MyGrantedAuthority)) continue; MyGrantedAuthority myGrantedAuthority = (MyGrantedAuthority)authority; if(urlConfigAttribute.getMyGrantedAuthority().equals(myGrantedAuthority)) return; } } throw new AccessDeniedException("无权限"); }
Example #11
Source Project: jhipster-ribbon-hystrix Author: xetys File: _CustomPersistentRememberMeServices.java License: GNU General Public License v3.0 | 6 votes |
/** * When logout occurs, only invalidate the current token, and not all user sessions. * <p> * The standard Spring Security implementations are too basic: they invalidate all tokens for the * current user, so when he logs out from one browser, all his other sessions are destroyed. */ @Override @Transactional public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { String rememberMeCookie = extractRememberMeCookie(request); if (rememberMeCookie != null && rememberMeCookie.length() != 0) { try { String[] cookieTokens = decodeCookie(rememberMeCookie); PersistentToken token = getPersistentToken(cookieTokens); persistentTokenRepository.delete(token); } catch (InvalidCookieException ice) { log.info("Invalid cookie, no persistent token could be deleted"); } catch (RememberMeAuthenticationException rmae) { log.debug("No persistent token found, so no token could be deleted"); } } super.logout(request, response, authentication); }
Example #12
Source Project: camunda-bpm-identity-keycloak Author: camunda File: KeycloakAuthenticationFilter.java License: Apache License 2.0 | 6 votes |
/** * {@inheritDoc} */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Get the Bearer Token and extract claims Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails(); String accessToken = details.getTokenValue(); String claims = JwtHelper.decode(accessToken).getClaims(); // Extract user ID from Token claims -depending on Keycloak Identity Provider configuration // String userId = Spin.JSON(claims).prop("sub").stringValue(); String userId = Spin.JSON(claims).prop("email").stringValue(); // useEmailAsCamundaUserId = true // String userId = Spin.JSON(claims).prop("preferred_username").stringValue(); // useUsernameAsCamundaUserId = true LOG.debug("Extracted userId from bearer token: {}", userId); try { identityService.setAuthentication(userId, getUserGroups(userId)); chain.doFilter(request, response); } finally { identityService.clearAuthentication(); } }
Example #13
Source Project: Spring-Security-Third-Edition Author: PacktPublishing File: CalendarUserAuthenticationProvider.java License: MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String email = token.getName(); CalendarUser user = email == null ? null : calendarService.findUserByEmail(email); if(user == null) { throw new UsernameNotFoundException("Invalid username/password"); } // Database Password already encrypted: String password = user.getPassword(); boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password); if(!passwordsMatch) { throw new BadCredentialsException("Invalid username/password"); } Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities); return usernamePasswordAuthenticationToken; }
Example #14
Source Project: document-management-system Author: openkm File: DbAuthModule.java License: GNU General Public License v2.0 | 6 votes |
@Override public String getName(String token, String user) throws PrincipalAdapterException { String name = null; Authentication oldAuth = null; try { if (token == null) { PrincipalUtils.getAuthentication(); } else { oldAuth = PrincipalUtils.getAuthentication(); PrincipalUtils.getAuthenticationByToken(token); } name = CommonAuthModule.getName(user); } catch (AccessDeniedException e) { throw new PrincipalAdapterException(e.getMessage(), e); } finally { if (token != null) { PrincipalUtils.setAuthentication(oldAuth); } } return name; }
Example #15
Source Project: batch-scheduler Author: hzwy23 File: CustomAuthenticationProvider.java License: MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // 获取认证的用户名 & 密码 String name = authentication.getName(); Object pd = authentication.getCredentials(); if (pd == null) { return new UsernamePasswordAuthenticationToken(name, "", new ArrayList<>()); } String password = pd.toString(); UserLoginEntity userLoginEntity = loginService.loginValidator(name, password); // 认证逻辑 if (userLoginEntity.isFlag()) { return getRole(name, password); } else { logger.info("登录失败,原因是:账号 {}: {}", userLoginEntity.getUsername(), userLoginEntity.getMessage()); throw new BadCredentialsException(new GsonBuilder().create().toJson(userLoginEntity)); } }
Example #16
Source Project: flowable-engine Author: flowable File: RemoteIdmAuthenticationProvider.java License: Apache License 2.0 | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { RemoteUser user = remoteIdmService.authenticateUser(authentication.getPrincipal().toString(), authentication.getCredentials().toString()); if (user == null) { throw new FlowableException("user not found " + authentication.getPrincipal()); } Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String privilege : user.getPrivileges()) { grantedAuthorities.add(new SimpleGrantedAuthority(privilege)); } Authentication auth = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities); return auth; }
Example #17
Source Project: spring-boot-samples Author: joedayz File: CfpControllerTest.java License: Apache License 2.0 | 6 votes |
@WithMockUser("jsmith") @Test public void submitTalk() throws Exception { Authentication authentication = new TestingAuthenticationToken( new User("jsmith", "John Smith"), "secret", "ROLE_USER"); given(this.submissionService.create(any())).willReturn(new Submission()); this.mvc.perform(post("/submit") .param("title", "Alice in Wonderland") .param("summary", "my abstract") .param("track", Track.ALTERNATE_LANGUAGES.getId()) .param("notes", "this rocks") .with(authentication(authentication)) .with(csrf())) .andExpect(status().isFound()) .andExpect(header().string(HttpHeaders.LOCATION, "/submit?navSection=submit")); verify(this.submissionService).create(any()); }
Example #18
Source Project: Spring-Security-Third-Edition Author: PacktPublishing File: SpringSecurityUserContext.java License: MIT License | 6 votes |
/** * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our * application Spring Security usernames are email addresses). */ @Override public CalendarUser getCurrentUser() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); if (authentication == null) { return null; } CalendarUser user = (CalendarUser) authentication.getPrincipal(); String email = user.getEmail(); if (email == null) { return null; } CalendarUser result = calendarService.findUserByEmail(email); if (result == null) { throw new IllegalStateException( "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email); } logger.info("CalendarUser: {}", result); return result; }
Example #19
Source Project: SpringAll Author: wuyouzhuguli File: SmsAuthenticationProvider.java License: MIT License | 5 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication; UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal()); if (userDetails == null) throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户"); SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities()); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; }
Example #20
Source Project: cloud-security-xsuaa-integration Author: SAP File: SpringSecurityContext.java License: Apache License 2.0 | 5 votes |
/** * Returns the token using {@link SecurityContextHolder}. * * * @return the token or <code>null</code> if {@link SecurityContext} is empty or * does not contain a token of this type. */ @Nullable public static Token getToken() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (Objects.nonNull(authentication) && authentication.isAuthenticated() && authentication.getDetails() instanceof OAuth2AuthenticationDetails) { OAuth2AuthenticationDetails authDetails = (OAuth2AuthenticationDetails) authentication.getDetails(); String tokenValue = authDetails.getTokenValue(); // TODO IAS Support return new XsuaaTokenWithGrantedAuthorities(tokenValue, authentication.getAuthorities()); } return null; }
Example #21
Source Project: spring-security-jwt-csrf Author: alexatiks File: JWTAuthenticationFilter.java License: MIT License | 5 votes |
@Override protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { try { Authentication authentication = TokenAuthenticationHelper.getAuthentication(request); SecurityContextHolder.getContext().setAuthentication(authentication); filterChain.doFilter(request, response); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired"); } }
Example #22
Source Project: spring-cloud-gray Author: SpringCloud File: Oauth2Service.java License: Apache License 2.0 | 5 votes |
public String getUserPrincipal(){ SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); String userPrincipal = null; if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); userPrincipal = springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { userPrincipal = (String) authentication.getPrincipal(); } } return userPrincipal; }
Example #23
Source Project: full-teaching Author: pabloFuente File: UserRepositoryAuthProvider.java License: Apache License 2.0 | 5 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = (String) authentication.getCredentials(); User user = userRepository.findByName(username); if (user == null) { throw new BadCredentialsException("User not found"); } if (!new BCryptPasswordEncoder().matches(password, user.getPasswordHash())) { throw new BadCredentialsException("Wrong password"); } else { userComponent.setLoggedUser(user); List<GrantedAuthority> roles = new ArrayList<>(); for (String role : user.getRoles()) { roles.add(new SimpleGrantedAuthority(role)); } return new UsernamePasswordAuthenticationToken(username, password, roles); } }
Example #24
Source Project: onetwo Author: wayshall File: SecurityArgumentResolver.java License: Apache License 2.0 | 5 votes |
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Object result = null; if(Authentication.class.isAssignableFrom(parameter.getParameterType())){ result = SecurityContextHolder.getContext().getAuthentication(); }else if(User.class.isAssignableFrom(parameter.getParameterType())){ result = SecurityUtils.getCurrentLoginUser(); }else if(UserDetail.class.isAssignableFrom(parameter.getParameterType())){ result = (UserDetail)SecurityUtils.getCurrentLoginUser(); } return result; }
Example #25
Source Project: auth0-spring-security-api Author: auth0 File: JwtAuthenticationProviderTest.java License: MIT License | 5 votes |
@Test public void shouldFailToAuthenticateUsingJWKIfTokenHasExpired() throws Exception { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, -10); Date tenSecondsAgo = calendar.getTime(); Jwk jwk = mock(Jwk.class); JwkProvider jwkProvider = mock(JwkProvider.class); KeyPair keyPair = RSAKeyPair(); when(jwkProvider.get(eq("key-id"))).thenReturn(jwk); when(jwk.getPublicKey()).thenReturn(keyPair.getPublic()); JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience"); Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id"); String token = JWT.create() .withAudience("test-audience") .withIssuer("test-issuer") .withHeader(keyIdHeader) .withExpiresAt(tenSecondsAgo) .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate())); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); exception.expect(BadCredentialsException.class); exception.expectMessage("Not a valid token"); exception.expectCause(Matchers.<Throwable>instanceOf(TokenExpiredException.class)); provider.authenticate(authentication); }
Example #26
Source Project: molgenis Author: molgenis File: SecurityUtils.java License: GNU Lesser General Public License v3.0 | 5 votes |
/** * Returns the username of the current authentication. * * @return username or <tt>null</tt> if 1) the current authentication is null or 2) the currently * authenticated principal is the system. */ public static @Nullable @CheckForNull String getCurrentUsername() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return null; } return getUsername(authentication); }
Example #27
Source Project: JetfireCloud Author: jorrellz File: AuthenticationService.java License: Apache License 2.0 | 5 votes |
/** * @param authRequest 访问的url,method * @return 有权限true, 无权限或全局资源中未找到请求url返回否 */ @Override public boolean decide(HttpServletRequest authRequest) { log.debug("正在访问的url是:{},method:{}", authRequest.getServletPath(), authRequest.getMethod()); //获取用户认证信息 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); //获取此url,method访问对应的权限资源信息 ConfigAttribute urlConfigAttribute = findConfigAttributesByUrl(authRequest); if (NONEXISTENT_URL.equals(urlConfigAttribute.getAttribute())) log.debug("url未在资源池中找到,拒绝访问"); //获取此访问用户所有角色拥有的权限资源 Set<Resource> userResources = findResourcesByAuthorityRoles(authentication.getAuthorities()); //用户拥有权限资源 与 url要求的资源进行对比 return isMatch(urlConfigAttribute, userResources); }
Example #28
Source Project: gpmr Author: k8s-for-greeks File: SecurityUtils.java License: Apache License 2.0 | 5 votes |
/** * If the current user has a specific authority (security role). * <p> * <p>The name of this method comes from the isUserInRole() method in the Servlet API</p> * * @param authority the authorithy to check * @return true if the current user has the authority, false otherwise */ public static boolean isCurrentUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); return springSecurityUser.getAuthorities().contains(new SimpleGrantedAuthority(authority)); } } return false; }
Example #29
Source Project: tutorials Author: eugenp File: CustomPermissionEvaluator.java License: MIT License | 5 votes |
@Override public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) { if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)) { return false; } final String targetType = targetDomainObject.getClass().getSimpleName().toUpperCase(); return hasPrivilege(auth, targetType, permission.toString().toUpperCase()); }
Example #30
Source Project: ExamStack Author: imalexyang File: AuthenticationFilter.java License: GNU General Public License v2.0 | 5 votes |
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if(!request.getMethod().equals("POST")){ throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } String username = this.obtainUsername(request); String password = this.obtainPassword(request); //加盐 String sh1Password = password + "{" + username + "}"; PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1(); String result = passwordEncoder.encode(sh1Password); log.info(result); UserInfo userDetails = (UserInfo) userDetailsService.loadUserByUsername(username); /*this.checkValidateCode(request);*/ if(!passwordEncoder.matches(userDetails.getPassword(), result) || "0".equals(userDetails.getEnabled()) || userDetails == null){ //System.out.println("用户名或密码错误!"); throw new AuthenticationServiceException("用户名或密码错误!"); } if(!userDetails.getRolesName().contains("ROLE_ADMIN") && !userDetails.getRolesName().contains("ROLE_TEACHER")){ throw new AuthenticationServiceException("非管理用户,操作无效!"); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); this.setDetails(request, authRequest); Authentication authentication = null; try{ authentication = this.getAuthenticationManager().authenticate(authRequest); }catch(Exception e){ e.printStackTrace(); } return authentication; }