类org.springframework.security.authentication.InsufficientAuthenticationException源码实例Demo

下面列出了怎么用org.springframework.security.authentication.InsufficientAuthenticationException的API类实例代码及写法,或者点击链接到github查看源代码。

@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());
    }

}
 
@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");
    }
}
 
/**
 * 通过传递的参数来决定用户是否有访问对应受保护对象的权限
 *
 * @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("当前访问没有权限");
    }
}
 
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;
}
 
/**
 * 判定是否拥有权限的决策方法
 * @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("没有权限访问");
}
 
源代码6 项目: mall-swarm   文件: DynamicAccessDecisionManager.java
@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("抱歉,您没有访问权限");
}
 
源代码7 项目: cola   文件: CaptchaAuthenticationFilter.java
@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);
		}
	}
}
 
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);
}
 
@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("访问被拒绝,权限不足");
}
 
源代码10 项目: mall   文件: DynamicAccessDecisionManager.java
@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("抱歉,您没有访问权限");
}
 
@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);
}
 
源代码12 项目: Groza   文件: RefreshTokenAuthenticationProvider.java
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;
}
 
源代码13 项目: api-layer   文件: AuthExceptionHandler.java
/**
 * 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);
    }
}
 
源代码14 项目: demo-project   文件: MyAccessDecisionManager.java
@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("无权限");
	}
 
源代码15 项目: airsonic   文件: JWTAuthenticationProvider.java
@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());
}
 
/**
 * @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!");
}
 
源代码17 项目: itweet-boot   文件: MyAccessDecisionManager.java
@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");
}
 
/**
 * @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!");
}
 
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;
}
 
@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());
}
 
源代码21 项目: maintain   文件: MyAccessDecisionManager.java
@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");
}
 
@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) {

    }
}
 
@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) {

    }
}
 
源代码24 项目: zxl   文件: ResourceAccessDecisionManager.java
@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("权限不足!");
}
 
源代码25 项目: hermes   文件: AccessDecisionManager.java
@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.");
}
 
/**
 * 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();
}
 
@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();
}
 
源代码28 项目: microservices-platform   文件: OauthTokenAspect.java
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
    try {
        Object[] args = joinPoint.getArgs();
        Principal principal = (Principal) args[0];
        if (!(principal instanceof Authentication)) {
            throw new InsufficientAuthenticationException(
                    "There is no client authentication. Try adding an appropriate authentication filter.");
        }
        String clientId = getClientId(principal);
        Map<String, String> parameters = (Map<String, String>) args[1];
        String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);

        //保存租户id
        TenantContextHolder.setTenant(clientId);
        Object proceed = joinPoint.proceed();
        if (SecurityConstants.AUTHORIZATION_CODE.equals(grantType)) {
            /*
             如果使用 @EnableOAuth2Sso 注解不能修改返回格式,否则授权码模式可以统一改
             因为本项目的 sso-demo/ss-sso 里面使用了 @EnableOAuth2Sso 注解,所以这里就不修改授权码模式的token返回值了
             */
            return proceed;
        } else {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            return ResponseEntity
                    .status(HttpStatus.OK)
                    .body(Result.succeed(body));
        }
    } catch (Exception e) {
        log.error("授权错误", e);
        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(Result.failed(e.getMessage()));
    } finally {
        TenantContextHolder.clear();
    }
}
 
源代码29 项目: microservices-platform   文件: OauthTokenAspect.java
private String getClientId(Principal principal) {
    Authentication client = (Authentication) principal;
    if (!client.isAuthenticated()) {
        throw new InsufficientAuthenticationException("The client is not authenticated.");
    }
    String clientId = client.getName();
    if (client instanceof OAuth2Authentication) {
        clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId();
    }
    return clientId;
}
 
/**
 * 判定是否拥有权限的决策方法
 * @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();
         if(url.equals(request.getRequestURI())){
            return;
         }
    }
    throw new AccessDeniedException("没有权限访问");
}
 
 同包方法