org.springframework.security.authentication.InsufficientAuthenticationException Java Examples

The following examples show how to use org.springframework.security.authentication.InsufficientAuthenticationException. 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: MyAccessDecisionManager.java    From maintain with MIT License 6 votes vote down vote up
@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 #2
Source File: ServerEndpointFilterUtil.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
void writeErrorResponse(HttpServletResponse httpServletResponse, RuntimeException e) throws IOException {
    ErrorResponse errorResponse;
    int statusCode;
    if (e instanceof InsufficientAuthenticationException) {
        errorResponse = new ErrorResponse("Anonymous access is prohibited");
        statusCode = HttpServletResponse.SC_FORBIDDEN;
    } else if (e instanceof AuthenticationException || e instanceof IllegalArgumentException) {
        errorResponse = new ErrorResponse("Authentication failed");
        statusCode = HttpServletResponse.SC_FORBIDDEN;
    } else {
        errorResponse = new ErrorResponse("The server encountered an internal error");
        statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    String errorResponseText = jsonConverter.writeValueAsString(errorResponse);
    httpServletResponse.setContentType("application/json");
    httpServletResponse.getWriter().print(errorResponseText);
    httpServletResponse.setStatus(statusCode);
}
 
Example #3
Source File: RefreshTokenAuthenticationProvider.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
private SecurityUser authenticateByUserId(Long userId) {
    UserEntity user = userService.findUserById(userId);
    if (user == null) {
        throw new UsernameNotFoundException("User not found by refresh token");
    }

    UserCredentialsEntity userCredentials = userService.findUserCredentialsByUserId(user.getId());
    if (userCredentials == null) {
        throw new UsernameNotFoundException("User credentials not found");
    }

    if (!userCredentials.isEnabled()) {
        throw new DisabledException("User is not active");
    }

    if (user.getAuthority() == null) {
        throw new InsufficientAuthenticationException("User has no authority assigned");
    }

    UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());

    SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal);

    return securityUser;
}
 
Example #4
Source File: MyAccessDecisionManager.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通过传递的参数来决定用户是否有访问对应受保护对象的权限
 *
 * @param authentication 包含了当前的用户信息,包括拥有的权限。这里的权限来源就是前面登录时UserDetailsService中设置的authorities。
 * @param object  就是FilterInvocation对象,可以得到request等web资源
 * @param configAttributes configAttributes是本次访问需要的权限
 */
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if (null == configAttributes || 0 >= configAttributes.size()) {
        return;
    } else {
        String needRole;
        for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {
            needRole = iter.next().getAttribute();

            for(GrantedAuthority ga : authentication.getAuthorities()) {
                if(needRole.trim().equals(ga.getAuthority().trim())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("当前访问没有权限");
    }
}
 
Example #5
Source File: SecurityAccessDecisionManager.java    From cola-cloud with MIT License 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if(null== configAttributes || configAttributes.size() <=0) {
        return;
    }
    ConfigAttribute c;
    String needRole;
    for (ConfigAttribute configAttribute : configAttributes) {
        c = configAttribute;
        needRole = c.getAttribute();
        //authentication 为在注释1 中循环添加到 GrantedAuthority 对象中的权限信息集合
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            if (needRole.trim().equals(ga.getAuthority())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("访问被拒绝,权限不足");
}
 
Example #6
Source File: JwtAuthenticationEntryPoint.java    From SpringBootLearn with Apache License 2.0 6 votes vote down vote up
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
    StringBuilder msg = new StringBuilder("请求访问: ");
    msg.append(httpServletRequest.getRequestURI()).append(" 接口, 经jwt 认证失败,无法访问系统资源.");
    log.info(msg.toString());
    log.info(e.toString());
    // 用户登录时身份认证未通过
    if (e instanceof BadCredentialsException) {
        log.info("用户登录时身份认证失败.");
        ResultUtil.writeJavaScript(httpServletResponse, ResultCode.UNAUTHORIZED, msg.toString());
    } else if (e instanceof InsufficientAuthenticationException) {
        log.info("缺少请求头参数,Authorization传递是token值所以参数是必须的.");
        ResultUtil.writeJavaScript(httpServletResponse, ResultCode.NO_TOKEN, msg.toString());
    } else {
        log.info("用户token无效.");
        ResultUtil.writeJavaScript(httpServletResponse, ResultCode.TOKEN_INVALID, msg.toString());
    }

}
 
Example #7
Source File: InsufficientAuthenticationHandler.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Override
public Response toResponse(InsufficientAuthenticationException exception) {
    Status status = Response.Status.UNAUTHORIZED;
    String wwwAuthHeader = this.authUrl;
    URI requestUri = (uriInfo == null) ? null : uriInfo.getRequestUri();

    //If we have an embedded OAuth exception, then put the error information in the www-auth header per oauth spec 
    //http://tools.ietf.org/html/rfc6750 see sec 3
    //Otherwise put the auth url in the header
    if (exception.getCause() != null && exception.getCause() instanceof OAuthAccessException) {
        OAuthAccessException oauthEx = (OAuthAccessException) exception.getCause();
        wwwAuthHeader = "Bearer error=\"" + oauthEx.getType().toString() + "\", error_description=\"" + oauthEx.getMessage() + "\"";
    }
    
    MediaType errorType = MediaType.APPLICATION_JSON_TYPE;
    if(this.headers.getMediaType() == MediaType.APPLICATION_XML_TYPE) {
        errorType = MediaType.APPLICATION_XML_TYPE;
    }

    auditLogger.audit(securityEventBuilder.createSecurityEvent(getThrowingClassName(exception), requestUri, "Access Denied: "
            + exception.getMessage(), false));

    return Response.status(status).entity(new ErrorResponse(status.getStatusCode(), status.getReasonPhrase(),
            "Access DENIED: " + exception.getMessage())).header(HttpHeaders.WWW_AUTHENTICATE, wwwAuthHeader).type(errorType).build();
}
 
Example #8
Source File: CustomAccessDecisionManager.java    From spring-security with Apache License 2.0 6 votes vote down vote up
/**
 * 判定是否拥有权限的决策方法
 * @param authentication CustomUserDetailsService类loadUserByUsername()方法中返回值
 * @param o 包含客户端发起的请求的request信息。
 * @param collection CustomFilterInvocationSecurityMetadataSource类的getAttribute()方法返回值
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 */
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
    HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
    String url;
    for (GrantedAuthority ga : authentication.getAuthorities()) {
         url = ga.getAuthority();
         // security 默认角色
         if(url.equals("ROLE_ANONYMOUS")){
            return;
         }
         if(CommonUtil.matchers(url, request)){
            return;
         }
    }
    throw new AccessDeniedException("没有权限访问");
}
 
Example #9
Source File: MyAccessDecisionManager.java    From base-admin with MIT License 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    int deny = 0;

    for (AccessDecisionVoter voter : getDecisionVoters()) {
        int result = voter.vote(authentication, object, configAttributes);

        if (logger.isDebugEnabled()) {
            logger.debug("Voter: " + voter + ", returned: " + result);
        }

        switch (result) {
            case AccessDecisionVoter.ACCESS_GRANTED:
                return;

            case AccessDecisionVoter.ACCESS_DENIED:
                deny++;

                break;

            default:
                break;
        }
    }

    if (deny > 0) {
        throw new AccessDeniedException(messages.getMessage(
                "AbstractAccessDecisionManager.accessDenied", "Access is denied"));
    }

    // To get this far, every AccessDecisionVoter abstained
    checkAllowIfAllAbstainDecisions();
}
 
Example #10
Source File: CaptchaAuthenticationFilter.java    From cola with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) req;
	HttpServletResponse response = (HttpServletResponse) res;

	AuthenticationFailureHandler authenticationFailureHandler = requiresAuthentication(request, response);
	if (authenticationFailureHandler == null) {
		chain.doFilter(request, response);
		return;
	}

	Object captcha = request.getSession().getAttribute(LOGIN_CAPTCHA_SESSION_KEY);

	if (captcha == null) {
		chain.doFilter(request, response);
	} else {
		if (!String.valueOf(captcha).equalsIgnoreCase(request.getParameter(LOGIN_CAPTCHA_PARAM_NAME))) {
			authenticationFailureHandler.onAuthenticationFailure(request, response, new InsufficientAuthenticationException("验证码错误"));
		} else {
			chain.doFilter(request, response);
		}
	}
}
 
Example #11
Source File: DynamicAccessDecisionManager.java    From mall-swarm with Apache License 2.0 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object,
                   Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    // 当接口未被配置资源时直接放行
    if (CollUtil.isEmpty(configAttributes)) {
        return;
    }
    Iterator<ConfigAttribute> iterator = configAttributes.iterator();
    while (iterator.hasNext()) {
        ConfigAttribute configAttribute = iterator.next();
        //将访问所需资源或用户拥有资源进行比对
        String needAuthority = configAttribute.getAttribute();
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("抱歉,您没有访问权限");
}
 
Example #12
Source File: SecuritySessionResource.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Method processing HTTP GET requests to debug resource, producing "application/json" MIME
 * media
 * type.
 *
 * @return SecurityContext that will be send back as a response of type "application/json".
 */
@GET
@Path("debug")
public SecurityContext sessionDebug() {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth == null) {
        throw new InsufficientAuthenticationException("User must be logged in");
    } else if (auth instanceof OAuth2Authentication) {
        if (((OAuth2Authentication) auth).getUserAuthentication() instanceof AnonymousAuthenticationToken) {
            throw new InsufficientAuthenticationException("User must be logged in");
        }
    } else if (auth instanceof AnonymousAuthenticationToken) {
        throw new InsufficientAuthenticationException("User must be logged in");
    }

    return SecurityContextHolder.getContext();
}
 
Example #13
Source File: DynamicAccessDecisionManager.java    From mall with Apache License 2.0 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object,
                   Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    // 当接口未被配置资源时直接放行
    if (CollUtil.isEmpty(configAttributes)) {
        return;
    }
    Iterator<ConfigAttribute> iterator = configAttributes.iterator();
    while (iterator.hasNext()) {
        ConfigAttribute configAttribute = iterator.next();
        //将访问所需资源或用户拥有资源进行比对
        String needAuthority = configAttribute.getAttribute();
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("抱歉,您没有访问权限");
}
 
Example #14
Source File: LDAccessDecisionManager.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> properties)
		throws AccessDeniedException, InsufficientAuthenticationException {

	if (authentication instanceof AnonymousAuthenticationToken) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
				.getRequest();
		if ("login".equals(request.getParameter("anonymous"))) {
			String tenant = "default";
			if (StringUtils.isNotEmpty(request.getParameter("tenant")))
				tenant = request.getParameter("tenant");

			ContextProperties config = Context.get().getProperties();
			boolean enabled = "true".equals(config.get(tenant + ".anonymous.enabled"));
			if (enabled) {
				return;
			}
		}
	}

	super.decide(authentication, object, properties);
}
 
Example #15
Source File: RefreshTokenAuthenticationProvider.java    From Groza with Apache License 2.0 6 votes vote down vote up
private SecurityUser authenticateByUserId(UserId userId) {
    User user = userService.findUserById(userId);
    if (user == null) {
        throw new UsernameNotFoundException("User not found by refresh token");
    }

    UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
    if (userCredentials == null) {
        throw new UsernameNotFoundException("User credentials not found");
    }

    if (!userCredentials.isEnabled()) {
        throw new DisabledException("User is not active");
    }

    if (user.getAuthority() == null) throw new InsufficientAuthenticationException("User has no authority assigned");

    UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());

    SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal);

    return securityUser;
}
 
Example #16
Source File: AuthExceptionHandler.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Entry method that takes care about the exception passed to it
 *
 * @param request  Http request
 * @param response Http response
 * @param ex       Exception to be handled
 * @throws ServletException Fallback exception if exception cannot be handled
 */
@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, RuntimeException ex) throws ServletException {
    if (ex instanceof InsufficientAuthenticationException) {
        handleAuthenticationRequired(request, response, ex);
    } else if (ex instanceof BadCredentialsException) {
        handleBadCredentials(request, response, ex);
    } else if (ex instanceof AuthenticationCredentialsNotFoundException) {
        handleAuthenticationCredentialsNotFound(request, response, ex);
    } else if (ex instanceof AuthMethodNotSupportedException) {
        handleAuthMethodNotSupported(request, response, ex);
    } else if (ex instanceof TokenNotValidException) {
        handleTokenNotValid(request, response, ex);
    } else if (ex instanceof TokenNotProvidedException) {
        handleTokenNotProvided(request, response, ex);
    } else if (ex instanceof TokenExpireException) {
        handleTokenExpire(request, response, ex);
    } else if (ex instanceof InvalidCertificateException) {
        handleInvalidCertificate(response, ex);
    } else if (ex instanceof AuthenticationException) {
        handleAuthenticationException(request, response, ex);
    } else {
        throw new ServletException(ex);
    }
}
 
Example #17
Source File: MyAccessDecisionManager.java    From demo-project with MIT License 6 votes vote down vote up
@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 #18
Source File: JWTAuthenticationProvider.java    From airsonic with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    JWTAuthenticationToken authentication = (JWTAuthenticationToken) auth;
    if (authentication.getCredentials() == null || !(authentication.getCredentials() instanceof String)) {
        LOG.error("Credentials not present");
        return null;
    }
    String rawToken = (String) auth.getCredentials();
    DecodedJWT token = JWTSecurityService.verify(jwtKey, rawToken);
    Claim path = token.getClaim(JWTSecurityService.CLAIM_PATH);
    authentication.setAuthenticated(true);

    // TODO:AD This is super unfortunate, but not sure there is a better way when using JSP
    if (StringUtils.contains(authentication.getRequestedPath(), "/WEB-INF/jsp/")) {
        LOG.warn("BYPASSING AUTH FOR WEB-INF page");
    } else if (!roughlyEqual(path.asString(), authentication.getRequestedPath())) {
        throw new InsufficientAuthenticationException("Credentials not valid for path " + authentication
                .getRequestedPath() + ". They are valid for " + path.asString());
    }

    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("IS_AUTHENTICATED_FULLY"));
    authorities.add(new SimpleGrantedAuthority("ROLE_TEMP"));
    return new JWTAuthenticationToken(authorities, rawToken, authentication.getRequestedPath());
}
 
Example #19
Source File: AccessDecisionManager.java    From hermes with Apache License 2.0 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
	// 判断目标是否在权限控制内
	if (configAttributes == null) return;
	
	// 遍历权限
	for (ConfigAttribute configAttribute: configAttributes) {
		// 将权限与用户角色进行匹配
		String role = configAttribute.getAttribute();
		for (GrantedAuthority grantedAuthority: authentication.getAuthorities()) {
			Logger.debug("match between %s and %s.", role, grantedAuthority.getAuthority());
			if (Strings.equals(role, grantedAuthority.getAuthority())) {
				Logger.debug("matched! access allow.");
				return;
			}
		}
	}
	
	// 无法匹配权限抛出异常
	Logger.info("denied!");
	throw new AccessDeniedException("no authority.");
}
 
Example #20
Source File: SecurityAccessDecisionManager.java    From Auth-service with MIT License 6 votes vote down vote up
/**
 * @param authentication 用户权限
 * @param o              url
 * @param collection     所需要的权限
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 */
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
    logger.info("decide url and permission");
    if (collection == null) {
        return;
    }

    Iterator<ConfigAttribute> ite = collection.iterator();
    //判断用户所拥有的权限,是否符合对应的Url权限,如果实现了UserDetailsService,则用户权限是loadUserByUsername返回用户所对应的权限
    while (ite.hasNext()) {
        ConfigAttribute ca = ite.next();
        String needRole = ca.getAttribute();
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            logger.info("GrantedAuthority: {}", ga);
            if (needRole.equals(ga.getAuthority())) {
                return;
            }
        }
    }
    logger.error("AccessDecisionManager: no right!");
    throw new AccessDeniedException("no right!");
}
 
Example #21
Source File: MyAccessDecisionManager.java    From itweet-boot with Apache License 2.0 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

    if(null== configAttributes || configAttributes.size() <=0) {
        return;
    }
    ConfigAttribute c;
    String needRole;
    for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {
        c = iter.next();
        needRole = c.getAttribute();
        for(GrantedAuthority ga : authentication.getAuthorities()) {
            if(needRole.trim().equals(ga.getAuthority())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("no right");
}
 
Example #22
Source File: SecurityAccessDecisionManager.java    From microservice-integration with MIT License 6 votes vote down vote up
/**
 * @param authentication 用户权限
 * @param o              url
 * @param collection     所需要的权限
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 */
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
    logger.info("decide url and permission");
    if (collection == null) {
        return;
    }

    Iterator<ConfigAttribute> ite = collection.iterator();
    //判断用户所拥有的权限,是否符合对应的Url权限,如果实现了UserDetailsService,则用户权限是loadUserByUsername返回用户所对应的权限
    while (ite.hasNext()) {
        ConfigAttribute ca = ite.next();
        String needRole = ca.getAttribute();
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            logger.info("GrantedAuthority: {}", ga);
            if (needRole.equals(ga.getAuthority())) {
                return;
            }
        }
    }
    logger.error("AccessDecisionManager: no right!");
    throw new AccessDeniedException("no right!");
}
 
Example #23
Source File: RefreshTokenAuthenticationProvider.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
private SecurityUser authenticateByUserId(UserId userId) {
  User user = userService.findUserById(userId);
  if (user == null) {
    throw new UsernameNotFoundException("User not found by refresh token");
  }

  UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
  if (userCredentials == null) {
    throw new UsernameNotFoundException("User credentials not found");
  }

  if (!userCredentials.isEnabled()) {
    throw new DisabledException("User is not active");
  }

  if (user.getAuthority() == null)
    throw new InsufficientAuthenticationException("User has no authority assigned");

  UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());

  SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal);

  return securityUser;
}
 
Example #24
Source File: ResourceAccessDecisionManager.java    From zxl with Apache License 2.0 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
	if (configAttributes == null) {
		return;
	}
	Iterator<ConfigAttribute> iterator = configAttributes.iterator();
	while (iterator.hasNext()) {
		ConfigAttribute configAttribute = iterator.next();
		String needPermission = configAttribute.getAttribute();
		for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
			if (needPermission.equals(grantedAuthority.getAuthority())) {
				return;
			}
		}
	}
	throw new AccessDeniedException("权限不足!");
}
 
Example #25
Source File: AjaxAuthenticationProvider.java    From springboot-security-jwt with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");

    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();

    User user = userService.getByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
    
    if (!encoder.matches(password, user.getPassword())) {
        throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
    }

    if (user.getRoles() == null) throw new InsufficientAuthenticationException("User has no roles assigned");
    
    List<GrantedAuthority> authorities = user.getRoles().stream()
            .map(authority -> new SimpleGrantedAuthority(authority.getRole().authority()))
            .collect(Collectors.toList());
    
    UserContext userContext = UserContext.create(user.getUsername(), authorities);
    
    return new UsernamePasswordAuthenticationToken(userContext, null, userContext.getAuthorities());
}
 
Example #26
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test(expected = InsufficientAuthenticationException.class)
public void principalAndCredentialsAreTheSameSourceIpListNotMatches() {
    final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", "192.168.1.3" };
    final String principal = "controllerId";
    final String credentials = "controllerId";
    final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
            Arrays.asList(credentials));
    token.setDetails(webAuthenticationDetailsMock);

    when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP);

    final PreAuthTokenSourceTrustAuthenticationProvider underTestWithList = new PreAuthTokenSourceTrustAuthenticationProvider(
            trustedIPAddresses);

    // test, should throw authentication exception
    final Authentication authenticate = underTestWithList.authenticate(token);
    try {
        assertThat(authenticate.isAuthenticated()).isTrue();
        fail("as source is not trusted.");
    } catch (final InsufficientAuthenticationException e) {

    }
}
 
Example #27
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Testing that the controllerId in the URI request match with the controllerId in the request header but the request are not coming from a trustful source.")
public void priniciapAndCredentialsAreTheSameButSourceIpRequestNotMatching() {
    final String remoteAddress = "192.168.1.1";
    final String principal = "controllerId";
    final String credentials = "controllerId";
    final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
            Arrays.asList(credentials));
    token.setDetails(webAuthenticationDetailsMock);

    when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(remoteAddress);

    // test, should throw authentication exception

    try {
        underTestWithSourceIpCheck.authenticate(token);
        fail("as source is not trusted.");
    } catch (final InsufficientAuthenticationException e) {

    }
}
 
Example #28
Source File: SonosLinkSecurityInterceptor.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void check(DecodedJWT jwt) throws InsufficientAuthenticationException {
    AuthenticationType authenticationType = AuthenticationType.valueOf(settingsService.getSonosLinkMethod());
    // no need for extra checks because there isn't a link code
    if (authenticationType == AuthenticationType.ANONYMOUS) {
        return;
    }
    String linkcode = jwt.getClaim(CLAIM_LINKCODE).asString();
    SonosLink sonosLink = sonosLinkDao.findByLinkcode(linkcode);

    if (!StringUtils.equals(jwt.getSubject(), sonosLink.getUsername())
            || !StringUtils.equals(linkcode, sonosLink.getLinkcode())
            || !StringUtils.equals(jwt.getClaim(CLAIM_HOUSEHOLDID).asString(), sonosLink.getHouseholdId())) {
        throw new InsufficientAuthenticationException("Sonos creds not valid");
    }
}
 
Example #29
Source File: PreAuthorizeSpringViewProviderAccessDelegate.java    From Vaadin4Spring-MVP-Sample-SpringSecurity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAccessGranted(String beanName, UI ui) {
	
	final PreAuthorize viewSecured = applicationContext.findAnnotationOnBean(beanName, PreAuthorize.class);
				
	if (viewSecured != null) {

		final Class<?> targetClass = AopUtils.getTargetClass(applicationContext.getBean(beanName));
		final Method method = ClassUtils.getMethod(AopUtils.getTargetClass(applicationContext.getBean(beanName)), "enter", com.vaadin.navigator.ViewChangeListener.ViewChangeEvent.class);								
		final MethodInvocation methodInvocation = MethodInvocationUtils.createFromClass(targetClass, method.getName());
								
		final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		final AccessDecisionManager accessDecisionManager = applicationContext.getBean(AccessDecisionManager.class);			        	        	        	       	        	       
        final ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory(new DefaultMethodSecurityExpressionHandler());
        
		Collection<ConfigAttribute> atributi = new ArrayList<ConfigAttribute>();
		atributi.add(attributeFactory.createPreInvocationAttribute(null, null, viewSecured.value()));
		
        try {
            accessDecisionManager.decide(authentication, methodInvocation, atributi);
            return true;
        } catch (AccessDeniedException | InsufficientAuthenticationException ex) {
            return false;
        }
		
	} else {
		return true;
	}
	
}
 
Example #30
Source File: InsufficientAuthenticationHandlerTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void checkResponse() throws Exception {
    SecurityEventBuilder mockSecurityEventBuilder = Mockito.mock(SecurityEventBuilder.class);
    AuditLogger mockAuditLogger = Mockito.mock(AuditLogger.class);

    handler = new InsufficientAuthenticationHandler();
    handler.setSecurityEventBuilder(mockSecurityEventBuilder);
    handler.setAuditLogger(mockAuditLogger);

    SecurityEvent secEvt = new SecurityEvent();

    Mockito.when(mockSecurityEventBuilder.createSecurityEvent(Mockito.anyString(), Mockito.any(URI.class), Mockito.anyString(), Mockito.anyBoolean())).thenReturn(secEvt);

    HttpHeaders headers = Mockito.mock(HttpHeaders.class);
    Mockito.when(headers.getMediaType()).thenReturn(MediaType.APPLICATION_JSON_TYPE);
    
    //  DONE BY WHAT IS CALLED AN "EXPERT"
    //  DO NOT TRY THIS AT HOME
    Field f = handler.getClass().getDeclaredField("headers");
    f.setAccessible(true);
    f.set(handler, headers);

    Response resp = handler.toResponse(new InsufficientAuthenticationException("Invalid Token"));
    assertTrue(resp != null);
    Object entity = resp.getEntity();
    
    // No exception has been thrown.
    assertTrue(entity != null);
    
}