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

项目:Fetax-AI    文件:MainAccessDecisionManager.java   
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    //System.err.println(" ---------------MaxAccessDecisionManager decide--------------- ");
    if(configAttributes == null) {
        return;
    }
    //所请求的资源拥有的权限(一个资源对多个权限)
    Iterator<ConfigAttribute> iterator = configAttributes.iterator();
    while(iterator.hasNext()) {
        ConfigAttribute configAttribute = iterator.next();
        //访问所请求资源所需要的权限
        String needPermission = configAttribute.getAttribute();
        //System.out.println("NEED-> "+needPermission);
        //用户所拥有的权限authentication
        for(GrantedAuthority ga : authentication.getAuthorities()) {
            //System.out.println("USER-> "+ga.getAuthority());
            if(needPermission.equals(ga.getAuthority())) {
                //System.out.println("pass");
                return;
            }
        }
    }
    //没有权限
    throw new AccessDeniedException("Access Denide!");
}
项目:data-migration    文件:OwnAccessDecisionManager.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");
}
项目:busi-support    文件:CustomerAccessDecisionManager.java   
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection)
        throws AccessDeniedException, InsufficientAuthenticationException {
    if (collection == null) {
        return;
    }
    String needRole;
    //遍历需要的角色,如果一样,则通过
    CustomerUserDetail userDetail = (CustomerUserDetail) authentication.getPrincipal();
    List<Role> userRoleList = securityService.getUserRoleList(userDetail.getUsername(), userDetail.getAccountType());
    for (ConfigAttribute configAttribute : collection) {
        needRole = configAttribute.getAttribute();
        for (Role role : userRoleList) {
            if (needRole.equals(role.getRoleCode())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("Cannot Access!");
}
项目:esup-ecandidat    文件:UserController.java   
/**
 * @param viewClass
 * @return true si l'utilisateur peut accéder à la vue
 */
public boolean canCurrentUserAccessView(Class<? extends View> viewClass, Authentication auth) {
    if (auth == null) {
        return false;
    }
    MethodInvocation methodInvocation = MethodInvocationUtils.createFromClass(viewClass, "enter");
    Collection<ConfigAttribute> configAttributes = methodSecurityInterceptor.obtainSecurityMetadataSource()
            .getAttributes(methodInvocation);
    /* Renvoie true si la vue n'est pas sécurisée */
    if (configAttributes.isEmpty()) {
        return true;
    }
    /* Vérifie que l'utilisateur a les droits requis */
    try {
        methodSecurityInterceptor.getAccessDecisionManager().decide(auth, methodInvocation, configAttributes);
    } catch (InsufficientAuthenticationException | AccessDeniedException e) {
        return false;
    }
    return true;
}
项目: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");
}
项目:springbootWeb    文件:CustomerAccessDecisionManager.java   
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection)
        throws AccessDeniedException, InsufficientAuthenticationException {
    if (collection == null) {
        return;
    }
    String needRole;
    //遍历需要的角色,如果一样,则通过,避免角色信息变了,从数据库取
    CustomerUserDetail userDetail = (CustomerUserDetail) authentication.getPrincipal();
    List<Role> roleList = securityService.getUserRoleList(userDetail.getUsername(), userDetail.getAccountType());
    for (ConfigAttribute configAttribute : collection) {
        needRole = configAttribute.getAttribute();
        for (Role aRoleList : roleList) {
            if (aRoleList != null && needRole.equals(aRoleList.getRoleCode())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("Cannot Access!");
}
项目:SpringBootStudy    文件:DemoAccessDecisionManager.java   
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if (configAttributes == null) {
        return;
    }

    for (ConfigAttribute ca : configAttributes) {
        String needRole = ca.getAttribute();
        //ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            if (needRole.trim().equals(ga.getAuthority().trim())) {
                return;
            }
        }
    }

    throw new AccessDeniedException("没有权限进行操作!");
}
项目:infotaf    文件:AjaxAuthenticationProvider.java   
@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());
}
项目:awe-awesomesky    文件:MainAccessDecisionManager.java   
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    //System.err.println(" ---------------MaxAccessDecisionManager decide--------------- ");
    if(configAttributes == null) {
        return;
    }
    //所请求的资源拥有的权限(一个资源对多个权限)
    Iterator<ConfigAttribute> iterator = configAttributes.iterator();
    while(iterator.hasNext()) {
        ConfigAttribute configAttribute = iterator.next();
        //访问所请求资源所需要的权限
        String needPermission = configAttribute.getAttribute();
        //System.out.println("NEED-> "+needPermission);
        //用户所拥有的权限authentication
        for(GrantedAuthority ga : authentication.getAuthorities()) {
            //System.out.println("USER-> "+ga.getAuthority());
            if(needPermission.equals(ga.getAuthority())) {
                //System.out.println("pass");
                return;
            }
        }
    }
    //没有权限
    throw new AccessDeniedException("Access Denide!");
}
项目:bdf2    文件:UrlAccessDecisionManager.java   
@SuppressWarnings("unchecked")
public void decide(Authentication authentication, Object object,Collection<ConfigAttribute> configAttributes)throws AccessDeniedException, InsufficientAuthenticationException {
    if((authentication.getPrincipal() instanceof IUser)){
        IUser loginUser=(IUser)authentication.getPrincipal();
        if(loginUser.isAdministrator())return;          
    }
    int result=10;
    for (AccessDecisionVoter<Object> voter : getDecisionVoters()) {
        result = voter.vote(authentication, object, configAttributes);
        if(result==AccessDecisionVoter.ACCESS_ABSTAIN){
            continue;
        }
        if(result==AccessDecisionVoter.ACCESS_DENIED){
            throw new AccessDeniedException("Access is denied");
        }
        if(result==AccessDecisionVoter.ACCESS_GRANTED){
            break;
        }
    }
    if(result==AccessDecisionVoter.ACCESS_ABSTAIN && configAttributes.size()>0){
        throw new AccessDeniedException("Access is denied");
    }
}
项目:iotplatform    文件: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;
}
项目:Shop    文件:MyAccessDecisionManager.java   
@Override
public void decide(Authentication authentication, Object object,Collection<ConfigAttribute> configAttributes)

        throws AccessDeniedException, InsufficientAuthenticationException {

    if(configAttributes == null){
        return  ;
    }
    Iterator<ConfigAttribute> ite = configAttributes.iterator();
    while(ite.hasNext()){

        ConfigAttribute ca = ite.next();

        String needRole = ((SecurityConfig)ca).getAttribute();

        for(GrantedAuthority grantedAuthority : authentication.getAuthorities()){
            if(needRole.trim().equals(grantedAuthority.getAuthority().trim())){
                return;
            }
        }
    }
    //û��Ȩ�޷���
    throw new AccessDeniedException("û��Ȩ�޷��ʣ�");

}
项目:interview-preparation    文件:JSONPayloadAuthenticationFilter.java   
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException,
ServletException {

    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        throw new InsufficientAuthenticationException("Invalid HTTP Method. it accepts only POST ");
    }

    if (!isContentTypeValid(request)) {
        throw new InsufficientAuthenticationException("Invalid content type. It accepts JSON only.");
    }

    final LoginRequest loginRequest = getLoginRequest(request);

    System.err.println("attemptAuthentication");
    final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());

    // Allow subclasses to set the "details" property
    // setDetails(request, authRequest);

    return getAuthenticationManager().authenticate(authRequest);
}
项目:interview-preparation    文件:WebSecurityConfig.java   
/**
 * Decide.
 *
 * @param authentication
 *            the authentication
 * @param object
 *            the object
 * @param configAttributes
 *            the configuration attributes
 * @throws AccessDeniedException
 *             the access denied exception
 * @throws InsufficientAuthenticationException
 *             the insufficient authentication exception
 */
@Override
public void decide(final Authentication authentication, final Object object, final Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {

    boolean allowAccess = false;

    for (final GrantedAuthority grantedAuthority : authentication.getAuthorities()) {

        for (final ConfigAttribute attribute : configAttributes) {
            allowAccess = attribute.getAttribute().equals(grantedAuthority.getAuthority());
            if (allowAccess) {
                break;// this loop
            }
        }

    }

    if (!allowAccess) {
        throw new AccessDeniedException("Access is denied");
    }
}
项目:interview-preparation    文件:WebSecurityConfig.java   
/**
 * Decide.
 *
 * @param authentication
 *            the authentication
 * @param object
 *            the object
 * @param configAttributes
 *            the configuration attributes
 * @throws AccessDeniedException
 *             the access denied exception
 * @throws InsufficientAuthenticationException
 *             the insufficient authentication exception
 */
@Override
public void decide(final Authentication authentication, final Object object, final Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {

    boolean allowAccess = false;

    for (final GrantedAuthority grantedAuthority : authentication.getAuthorities()) {

        for (final ConfigAttribute attribute : configAttributes) {
            allowAccess = attribute.getAttribute().equals(grantedAuthority.getAuthority());
            if (allowAccess) {
                break;// this loop
            }
        }

    }

    if (!allowAccess) {
        throw new AccessDeniedException("Access is denied");
    }
}
项目:SpringSecurity    文件:DefaultAccessDecisionManager.java   
/**
 * 自定义访问策略
 * 
 * @param authentication
 *            用户及用户权限信息
 * @param object
 * @param configAttributes
 *            访问资源需要的权限
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 * @see org.springframework.security.access.AccessDecisionManager#decide(org.springframework.security.core.Authentication,
 *      java.lang.Object, java.util.Collection)
 */
public void decide(Authentication authentication, Object object,
        Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    SysUserVO user = (SysUserVO) authentication.getPrincipal();
    logger.info("访问资源的用户为" + user.getUsername());
    // 如果访问资源不需要任何权限则直接通过
    if (configAttributes == null) {
        return;
    }
    Iterator<ConfigAttribute> ite = configAttributes.iterator();
    // 遍历configAttributes看用户是否有访问资源的权限
    while (ite.hasNext()) {
        ConfigAttribute ca = ite.next();
        String needRole = ((SecurityConfig) ca).getAttribute();
        // ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            if (needRole.trim().equals(ga.getAuthority().trim())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("没有权限访问! ");
}
项目:tgi-commons    文件:AspectSecurity.java   
private void securityCheck(String signatureName, ProceedingJoinPoint pjp) throws Exception {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    final UserClass theUser = getUser(authentication);
    if (theUser != null) {
        Collection<? extends SecurityPolicy> rules = securityCache.retrieve(theUser, signatureName);
        if (!checkRules(pjp, theUser, rules)) {
            throw new InsufficientAuthenticationException(
                    "Access to method "
                      //      + AspectSecurityUtils.getSignatureString(pjp)
                            + " is not allowed!");
        }
    } else {
        if (!getChecker(defaultPolicy).check(pjp, null)) {
            throw new InsufficientAuthenticationException(
                    "Access to method "
                      //      + AspectSecurityUtils.getSignatureString(pjp)
                            + " is not allowed!");

        }
    }
}
项目:prometheus    文件:CustomAccessDecisionManager.java   
/**
 * 如果用户拥有访问权限,则直接return。如果没有访问权限,那么抛出AccessDeniedException异常
 * 这个异常会被spring security检测到,从而引导到403页面
 * @param authentication 当前用户
 * @param o
 * @param collection 当前用户所访问的资源需要的权限
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 */
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {

    if(collection == null || collection.isEmpty())//如果不需要角色权限
        return;

    //当前用户所拥有的权限
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

    if(authentication.getName().equals("admin"))//超级管理员拥有所有权限
        return;

    //遍历,判断当前用户是否具有访问权限
    for(ConfigAttribute ca : collection){
        for (GrantedAuthority ga : authorities){
            if(ca.getAttribute().equals(ga.getAuthority()))
                return;
        }
    }

    throw new AccessDeniedException("没有访问权限!");
}
项目:hawkbit    文件:PreAuthTokenSourceTrustAuthenticationProviderTest.java   
@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) {

    }
}
项目:hawkbit    文件:PreAuthTokenSourceTrustAuthenticationProviderTest.java   
@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) {

    }
}
项目:pie    文件:PieAccessDecisionManager.java   
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {

    if (!(object instanceof MethodInvocation)) {
        throw new IllegalStateException("Only operates on methods.");
    }
    MethodInvocation methodInvocation = (MethodInvocation)object;

    Role role = null;
    if (authentication != null && authentication.getAuthorities().size() > 0) {
        role = Role.valueOf(authentication.getAuthorities().iterator().next().getAuthority());
    }
    if (role == null) {
        throw new AccessDeniedException("Secured method must have an authenticated role.");
    }

    if (!policyEnforcer.getPolicy().implies(role, methodInvocation.getThis().getClass(), methodInvocation.getMethod())) {
        policyEnforcer.getPolicy().logViolation(role, methodInvocation.getThis().getClass(), methodInvocation.getMethod());
        if (!policyEnforcer.getPolicyConfig().isReportOnlyMode()) {
            throw new AccessDeniedException("Access Denied");
        }
    }
}
项目:artifactory    文件:AccessFilterTest.java   
public void testAuthenticationChallenge() throws IOException, ServletException {
    ArtifactoryHome.bind(new ArtifactoryHome(new File("./target/test/testAuthenticationChallenge")));
    ArtifactoryHome.get().getArtifactoryProperties().setProperty(
            ConstantValues.locksTimeoutSecs.getPropertyName(), "10");
    ArtifactoryBasicAuthenticationEntryPoint authenticationEntryPoint =
            new ArtifactoryBasicAuthenticationEntryPoint();
    HttpServletRequest request = createMock(HttpServletRequest.class);

    HttpServletResponse response = createMock(HttpServletResponse.class);
    response.addHeader("WWW-Authenticate", "Basic realm=\"Artifactory Realm\"");
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(401);
    PrintWriter printWriter = createMock(PrintWriter.class);
    printWriter.write(anyObject(String.class));
    expect(response.getWriter()).andReturn(printWriter);
    expect(request.getRequestURI()).andReturn("testuri");
    expect(request.getHeader("Request-Agent")).andStubReturn("xx");
    replay(request, response, printWriter);
    authenticationEntryPoint.commence(request, response,
            new InsufficientAuthenticationException("Authentication required"));
    verify(response);
}
项目:gomall.la    文件:MyAccessDecisionManager.java   
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    log.debug("decide calling {},{}", object, configAttributes);
    if (configAttributes == null) {
        return;
    }
    System.out.println("decide " + object.toString()); // object is a URL.
    Iterator<ConfigAttribute> ite = configAttributes.iterator();
    while (ite.hasNext()) {
        ConfigAttribute ca = ite.next();
        String needRole = ((SecurityConfig) ca).getAttribute();
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            if (needRole.equals(ga.getAuthority())) { // ga is user's role.
                return;
            }
        }
    }
    throw new AccessDeniedException("no right");
}
项目:karaku    文件:KarakuUserService.java   
/**
 * Localiza al usuario basándose en el nombre del usuario.
 * 
 * @param username
 *            el nombre del usuario que identifica al usuario cuyos datos se
 *            requiere.
 * @return la información del usuario.
 */
@Override
public UserDetails loadUserByUsername(String uid) {

    KarakuUser user = new KarakuUser();
    user.setUserName(uid);
    user.addRoles(loadAuthoritiesByDn(uid));

    String permiso = propertiesUtil.get(BASIC_PERMISSION_KEY,
            BASIC_PERMISSION_KEY_DEFAULT);

    boolean allow = false;
    for (GrantedAuthority o : user.getAuthorities()) {
        if (o.getAuthority().equals(permiso)) {
            allow = true;
        }
    }
    if (!allow) {
        throw new InsufficientAuthenticationException(
                "No posee privilegios para este sistema");
    }
    return user;
}
项目: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("权限不足!");
}
项目:secure-data-service    文件:SecuritySessionResource.java   
/**
 * 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();
}
项目:secure-data-service    文件:InsufficientAuthenticationHandler.java   
@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();
}
项目:mmt    文件:MMTAccessDecisionManager.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();
        // 用户所拥有的权限authentication
        for (GrantedAuthority ga : authentication.getAuthorities())
            if (needPermission.equals(ga.getAuthority()))
                return;
    }
    // 没有权限
    throw new AccessDeniedException("拒绝访问。");
}
项目:users-service    文件:RegisterController.java   
@PostMapping("/{userId}/cancel")
ResponseEntity<Void> registerCancel(@PathVariable String userId,
                                    @RequestBody(required = false) VerifyDto verification,
                                    Authentication auth) {

    // If no verification code is specified:
    if (verification == null) {
        if (can(auth, "CANCEL_CREATE_USER")) {
            if (!mongo.remove(
                query(where("id").is(userId)
                    .and("confirmed").is(false)
                ), User.class
            ).isUpdateOfExisting()) {
                throw new UserNotFoundException();
            }
        } else {
            throw new InsufficientAuthenticationException(
                "Either a verification code or the role " +
                "'CANCEL_CREATE_USER' is required for this action."
            );
        }
    } else {
        if (!mongo.remove(
            query(where("id").is(userId)
                .and("userCreationCode").is(verification.getCode())
            ), User.class
        ).isUpdateOfExisting()) {
            throw new InvalidVerificationCodeException();
        }
    }

    // TODO: Send out email to user

    LOGGER.info("User '" + userId + "' cancelled registration.");
    return new ResponseEntity<>(OK);
}
项目:airsonic    文件:JWTAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    JWTAuthenticationToken authentication = (JWTAuthenticationToken) auth;
    if(authentication.getCredentials() == null || !(authentication.getCredentials() instanceof String)) {
        logger.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/")) {
        logger.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());
}
项目:iotplatform    文件:RestAuthenticationProvider.java   
private Authentication authenticateByUsernameAndPassword(UserPrincipal userPrincipal, String username,
    String password) {
  User user = userService.findUserByEmail(username);
  if (user == null) {
    throw new UsernameNotFoundException("User not found: " + username);
  }

  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 (!encoder.matches(password, userCredentials.getPassword())) {
    throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
  }

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

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

  return new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
}
项目:c2mon-web-ui    文件:RbacDecisionManager.java   
@Override
public void decide(final Authentication authentication, final Object secureObject, final Collection attributes)
    throws AccessDeniedException, InsufficientAuthenticationException {

  // The supports method ensures we are dealing with FilterInvocations
  //  so we can safely cast the secure object
  FilterInvocation invocation = (FilterInvocation) secureObject;

  // The url that the user tries to access
  String username = (String) authentication.getPrincipal();
  String pageUrl = invocation.getRequestUrl();
  log.debug(username + " tries to access url:" + pageUrl);

  RbacAuthorizationDetails details = getRequiredPermissions(pageUrl);
  if (details == null) { // no special permissions required!
    log.debug("no special permissions required to access: " + pageUrl);
    return;
  }

  if (!sessionService.isUserLogged(username)) {
    log.debug(username + " tried to access: " + pageUrl + " but is not logged in.");
    authentication.setAuthenticated(false);
    throw new AccessDeniedException("User not logged in");

  } else {
    if (!sessionService.isAuthorized(username, details)) {
      log.debug(username + " tried to access: " + pageUrl + " but does not have permission.");
      throw new AccessDeniedException("Permission denied");
    }
  }

  log.info(username + " successfully authorised to access: " + pageUrl);
}
项目:pivotal-cla    文件:SecurityConfig.java   
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    User currentUser = getUser(SecurityContextHolder.getContext().getAuthentication());

    if (currentUser == null || currentUser.isAdminAccessRequested()) {
        deniedHandler.handle(request, response, accessDeniedException);
        return;
    }

    new HttpSessionRequestCache().saveRequest(request, response);
    entryPoint.commence(request, response,
            new InsufficientAuthenticationException("Additional OAuth Scopes required", accessDeniedException));
}
项目:cuba    文件:IdpAuthController.java   
@PostMapping(value = "/v2/idp/token")
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
                                                         @RequestParam Map<String, String> parameters,
                                                         HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    // we cannot perform brute-force check here, since we don't know username

    String idpTicket = parameters.get("idp_ticket");
    String ipAddress = request.getRemoteAddr();

    OAuth2AccessTokenResult tokenResult =
            authenticate(idpTicket, request.getLocale(), ipAddress, parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}
项目:cuba    文件:LdapAuthController.java   
@RequestMapping(value = "/v2/ldap/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
                                                         @RequestParam Map<String, String> parameters,
                                                         HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!ldapConfig.getLdapEnabled()) {
        log.debug("LDAP authentication is disabled. Property cuba.rest.ldap.enabled is false");

        throw new InvalidGrantException("LDAP is not supported");
    }

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
    if (!"password".equals(grantType)) {
        throw new InvalidGrantException("grant type not supported for ldap/token endpoint");
    }

    String username = parameters.get("username");

    if (restApiConfig.getStandardAuthenticationUsers().contains(username)) {
        log.info("User {} is not allowed to use external login in REST API", username);
        throw new BadCredentialsException("Bad credentials");
    }

    String ipAddress = request.getRemoteAddr();

    String password = parameters.get("password");

    OAuth2AccessTokenResult tokenResult =
            authenticate(username, password, request.getLocale(), ipAddress, parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}
项目:credhub    文件:OAuth2ExtraValidationFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
  Authentication authentication = tokenExtractor.extract(request);

  try {
    if (authentication != null) {
      String token = (String) authentication.getPrincipal();
      OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
      Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
      String issuer = (String) additionalInformation.getOrDefault("iss", "");

      if (!issuer.equals(oAuth2IssuerService.getIssuer())) {
        tokenStore.removeAccessToken(accessToken);

        String errorMessage = messageSourceAccessor.getMessage("error.oauth.invalid_issuer");
        throw new OAuth2Exception(errorMessage);
        //        AuthenticationServiceException authException = new AuthenticationServiceException(errorMessage);
        //        oAuth2AuthenticationExceptionHandler.commence(request, response, authException);
      }

    }

    filterChain.doFilter(request, response);
  } catch (OAuth2Exception exception) {
    SecurityContextHolder.clearContext();
    InsufficientAuthenticationException authException = new InsufficientAuthenticationException(exception.getMessage(), exception);
    eventPublisher.publishAuthenticationFailure(new BadCredentialsException(exception.getMessage(), exception),
        new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
    oAuth2AuthenticationExceptionHandler.commence(request, response, authException);
  }
}
项目:hawkbit    文件:PreAuthTokenSourceTrustAuthenticationProvider.java   
private boolean checkSourceIPAddressIfNeccessary(final Object tokenDetails) {
    boolean success = authorizedSourceIps == null;
    String remoteAddress = null;
    // controllerIds in URL path and request header are the same but is the
    // request coming
    // from a trustful source, like the reverse proxy.
    if (authorizedSourceIps != null) {
        if (!(tokenDetails instanceof TenantAwareWebAuthenticationDetails)) {
            // is not of type WebAuthenticationDetails, then we cannot
            // determine the remote address!
            LOGGER.error(
                    "Cannot determine the controller remote-ip-address based on the given authentication token - {} , token details are not TenantAwareWebAuthenticationDetails! ",
                    tokenDetails);
            success = false;
        } else {
            remoteAddress = ((TenantAwareWebAuthenticationDetails) tokenDetails).getRemoteAddress();
            if (authorizedSourceIps.contains(remoteAddress)) {
                // source ip matches the given pattern -> authenticated
                success = true;
            }
        }
    }

    if (!success) {
        throw new InsufficientAuthenticationException("The remote source IP address " + remoteAddress
                + " is not in the list of trusted IP addresses " + authorizedSourceIps);
    }

    // no trusted IP check, because no authorizedSourceIPs configuration
    return true;
}
项目:enhanced-snapshots    文件:XhrSAMLEntryPoint.java   
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
                     AuthenticationException e) throws IOException, ServletException {
    if (isXmlHttpRequest(request) && e instanceof InsufficientAuthenticationException) {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(401);
        response.getWriter().write("{\"loginMode\":\"SSO\"}");
        return;
    }
    super.commence(request, response, e);
}
项目:artifactory    文件:AccessFilter.java   
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
private void useAnonymousIfPossible(HttpServletRequest request, HttpServletResponse response,
        FilterChain chain, SecurityContext securityContext) throws IOException, ServletException {
    boolean anonAccessEnabled = context.getAuthorizationService().isAnonAccessEnabled();
    if (anonAccessEnabled || authInterceptors.accept(request)) {
        log.debug("Using anonymous");
        Authentication authentication = getNonUiCachedAuthentication(request);
        if (authentication == null) {
            log.debug("Creating the Anonymous token");
            final UsernamePasswordAuthenticationToken authRequest =
                    new UsernamePasswordAuthenticationToken(UserInfo.ANONYMOUS, "");
            AuthenticationDetailsSource ads = new HttpAuthenticationDetailsSource();
            //noinspection unchecked
            authRequest.setDetails(ads.buildDetails(request));
            // explicitly ask for the default spring authentication manager by name (we have another one which
            // is only used by the basic authentication filter)
            AuthenticationManager authenticationManager =
                    context.beanForType("authenticationManager", AuthenticationManager.class);
            authentication = authenticationManager.authenticate(authRequest);
            if (authentication != null && authentication.isAuthenticated() && !RequestUtils.isUiRequest(request)) {
                AuthCacheKey authCacheKey = new AuthCacheKey(authFilter.getCacheKey(request),
                        request.getRemoteAddr());
                nonUiAuthCache.put(authCacheKey, authentication);
                log.debug("Added anonymous authentication {} to cache", authentication);
            }
        } else {
            log.debug("Using cached anonymous authentication");
        }
        useAuthentication(request, response, chain, authentication, securityContext);
    } else {
        if (authFilter.acceptEntry(request)) {
            log.debug("Sending request requiring authentication");
            authFilter.commence(request, response,
                    new InsufficientAuthenticationException("Authentication is required"));
        } else {
            log.debug("No filter or entry just chain");
            chain.doFilter(request, response);
        }
    }
}
项目:spring-json-sms-gateway    文件:SmsDaoHibernate.java   
@Override
public void update(SMS sms) throws GatewayException {
    SMS onBD = getSMS(sms.getId());

    if (onBD.getUser_id() != sms.getUser_id())
        throw new InsufficientAuthenticationException("Sorry, this user is not the SMS owner");

    onBD.setSubid(sms.getSubid());
    onBD.setMsisdn(sms.getMsisdn());
    onBD.setDatetimeScheduled(sms.getDatetimeScheduled());
    onBD.setText(sms.getText());
    onBD.setSender(sms.getSender());
    onBD.setIdSMSC(sms.getIdSMSC());
}