当前位置: 首页 > 知识库问答 >
问题:

出现意外错误(类型=禁止,状态=403)。拒绝访问

夏侯旻
2023-03-14

出现意外错误(类型=禁止,状态=403)。访问被拒绝。当我试图从邮递员或浏览器中访问URL时,我收到了一个错误,即出现了一个意外错误(类型=禁止,状态=403)。访问被拒绝。

1) 网络安全类:-

import javax.servlet.Filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.photoapp.users.service.ApiUserService;

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
     
    private Environment environment;
    private ApiUserService apiUserService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    
    @Autowired
    public WebSecurity(Environment environment , ApiUserService apiUserService , BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.environment = environment;
        this.apiUserService = apiUserService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/**").hasIpAddress(environment.getProperty("gateway.ip"))
        .and()
        .addFilter(getAuthenticationFilter());
        http.headers().frameOptions().disable();
    }

    private AuthenticationFilter getAuthenticationFilter() throws Exception {
        // TODO Auto-generated method stub
        AuthenticationFilter authenticationFilter = new AuthenticationFilter();
        authenticationFilter.setAuthenticationManager(authenticationManager());
        return authenticationFilter;
    }
    
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(apiUserService).passwordEncoder(bCryptPasswordEncoder);
    }
}

2) 身份验证筛选器类:-

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.photoapp.users.model.LoginRequestModel;

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public Authentication attemptAuthentiation(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
        
        try {
            LoginRequestModel creds = new ObjectMapper()
                    .readValue(req.getInputStream() , LoginRequestModel.class);
            
            return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken (
                    creds.getEmail(),
                    creds.getPassword(),
                    new ArrayList<>()));
        }
        catch(IOException e) {
            throw new RuntimeException(e);
        }
    }
    
    protected void succeddfulAuthentication(HttpServletRequest req, HttpServletResponse res , FilterChain chain , Authentication auth) throws IOException , ServletException {
        
    }
}

3)控制器类:-

import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.photoapp.users.dto.UserDto;
import com.photoapp.users.model.CreateUserRequestModel;
import com.photoapp.users.model.CreateUserResponseModel;
import com.photoapp.users.service.ApiUserService;

@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private ApiUserService apiUserService;
    
    @GetMapping("/status/check")
    public String status() {
        return "Working";
    }

    @PostMapping( consumes = {MediaType.APPLICATION_XML_VALUE , MediaType.APPLICATION_JSON_VALUE } ,
                  produces = {MediaType.APPLICATION_XML_VALUE , MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<CreateUserResponseModel> createUser(@RequestBody CreateUserRequestModel userDetails) {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        UserDto userDto = modelMapper.map(userDetails, UserDto.class);
        UserDto createdUser = apiUserService.createUser(userDto);
        CreateUserResponseModel responseModel = modelMapper.map(createdUser , CreateUserResponseModel.class);
        return ResponseEntity.status(HttpStatus.CREATED).body(responseModel);
    }
}

4) 服务实现类:-

import java.util.ArrayList;
import java.util.UUID;

import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.photoapp.users.dao.UserRepository;
import com.photoapp.users.dto.UserDto;
import com.photoapp.users.entity.UserEntity;

@Service
public class ApiUserServiceImpl implements ApiUserService{

    UserRepository userRepository;
    
    BCryptPasswordEncoder bCryptPasswordEncoder;
    
    @Autowired
    public ApiUserServiceImpl(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }
    
    @Override
    public UserDto createUser(UserDto userDetails) {
        
        userDetails.setUserId(UUID.randomUUID().toString());
        userDetails.setEncryptedPassword(bCryptPasswordEncoder.encode(userDetails.getPassword()));
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        UserEntity userEntity = modelMapper.map(userDetails, UserEntity.class);
        userRepository.save(userEntity);
        return userDetails;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        UserEntity userEntity = userRepository.findByEmail(username);
        
        if(userEntity == null) throw new  UsernameNotFoundException(username);
        return new User(userEntity.getEmail() , userEntity.getEncryptedPassword() , true ,true ,true ,true , new ArrayList<>());
    }
}

共有3个答案

慕容灿
2023-03-14

您必须允许所有与招摇过市相关的网址。

http.authorizeRequests().antMatchers(
            "/swagger-ui.html/**",
            "/webjars/springfox-swagger-ui/**",
            "/swagger-resources/**",
            "/swagger-ui/**",
            "/v2/api-docs/**"
).permitAll();
楚宏胜
2023-03-14

在我的应用程序中,我在spring boot security config中配置AuthenticationEntryPoint,因为如果发生任何错误(甚至我的自定义404-项都找不到),spring boot会捕获错误并返回401(在我的情况下),但我记得有些人告诉我403。所以我认为403可以向你隐瞒真正的错误

因此,您可以尝试通过配置异常处理来捕获错误

. ExctionHandling()。

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().sameOrigin();
        http.cors();
        http.csrf().disable()
            .authorizeRequests().antMatchers("/", "/callback", "/login**", "/webjars/**", "/error**").permitAll()
            .and()
            .authorizeRequests().antMatchers("/api/**").authenticated()
            .and()
            .authorizeRequests().antMatchers("/h2-console/**").permitAll()
            .and()
            .authorizeRequests().antMatchers("/swagger-ui.html").permitAll()
            .and()
            .authorizeRequests().antMatchers("/swagger-ui/**").permitAll()
            .and()
            .exceptionHandling().authenticationEntryPoint(new AppAuthenticationEntryPoint())
            .and()
            .logout().permitAll().logoutSuccessUrl("/");
    }
    
    @Bean
    public PrincipalExtractor getPrincipalExtractor(){
        return new KeyCloakUserInfoExtractorService();
    }
    
    @Autowired
    private ResourceServerTokenServices resourceServerTokenServices;
}

我的身份验证入口点看起来像:

@ControllerAdvice
public class AppAuthenticationEntryPoint implements AuthenticationEntryPoint{

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException auth) throws IOException, ServletException {
        // 401
        setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed");
    }
    
    @ExceptionHandler (value = {AccessDeniedException.class})
    public void commence(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        // 403
        setResponseError(response, HttpServletResponse.SC_FORBIDDEN, String.format("Access Denies: %s", accessDeniedException.getMessage()));
    }
    
    @ExceptionHandler (value = {NotFoundException.class})
    public void commence(HttpServletRequest request, HttpServletResponse response, NotFoundException notFoundException) throws IOException {
        // 404
        setResponseError(response, HttpServletResponse.SC_NOT_FOUND, String.format("Not found: %s", notFoundException.getMessage()));
    }
    
    @ExceptionHandler (value = {Exception.class})
    public void commence(HttpServletRequest request, HttpServletResponse response, Exception exception) throws IOException {
        //logger.error(String.format("An error occurred during request: %s %s error message: %s", 
                     //request.getMethod(), request.getRequestURL(), exception.getMessage()));
        // 500
        setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.format("Internal Server Error: %s", exception.getMessage()));
    }
    
    private void setResponseError(HttpServletResponse response, int errorCode, String errorMessage) throws IOException{
        response.setStatus(errorCode);
        response.getWriter().write(errorMessage);
        response.getWriter().flush();
        response.getWriter().close();
    }
    
    //private final Logger logger = LoggerFactory.getLogger(this.getClass());
}

希望它能帮助你理解403的原因

卫弘义
2023-03-14

你能不能检查一下网关。ip属性是在您的环境中设置的吗?如果是mac,请尝试echo${gateway.ip}。

另一点是,为什么只限制一个ip?有什么具体原因吗?您还可以确认是否删除。hasIpAddress(environment.getProperty(“gateway.ip”))能用吗?

 类似资料:
  • Spring我是新来的。我试图在我的数据库中添加一个新目标。在我添加spring security之前,它是有效的,但现在如果我单击添加新目标,我有一个问题: 出现意外错误(类型=禁止,状态=403)。被禁止的 我的goat-add.html: WebSecurity配置类: 我的控制器: 我读到这个问题可以是如果不使用csrf,但我不明白我怎么能解决它。 所有代码:https://github.

  • 我目前正在实现安全与Spring Boot到我的小API作为一个项目到学校当然没什么大不了的,但我想管理一些角色和东西。我一直在尝试添加. antMatcher(url). hasRole(一些角色)。...更多的蚂蚁匹配器... 当测试登录实际上显示一个错误(类型=禁止,状态=403)。 下面是一些代码 只是一个控制器,显示我的控制面板CRUD我的动物: p 我希望你们能帮助我,我是新来的。

  • 我正在做一个spring boot项目,其中包括thymeleaf,spring security。当我执行以下操作时效果很好:显示产品列表、显示产品详细信息、添加新产品、更新现有产品。 但当我执行-删除产品时,会出现以下错误: 白标错误页面 此应用程序没有/error的显式映射,因此您将其视为一种回退。 18 16:59:16BDT 2019 出现意外错误(类型=禁止,状态=403)。 被禁止的

  • 我在负载平衡器后面有web服务器,系统成功地将我重定向到OKTA登录页面,当我输入凭据时,并在OKTA服务器执行回调操作时单击登录按钮,使用 我得到一个错误: 403-禁止:拒绝访问。您没有使用提供的凭据查看此目录或页的权限。 我在Startup.cs文件中使用下面的代码,我在Blazor服务器上的应用程序

  • 我在Heroku上托管了一个Springboot应用程序。构建和部署工作得非常好。然而,每当我想访问该方法时,我都会看到这个错误<代码>出现意外错误(类型=错误请求,状态=400) 如果我使用loclhost,但使用Heroku的应用程序时抛出错误,那么它在Postman上运行得非常好。 这是控制器的样子。我猜这就是问题的来源。 . 你认为我能做些什么让api在Heroku上工作?

  • 我已经将我的一个api配置为受保护,当我试图访问它时,它给我一个拒绝访问的错误消息,我不知道是什么原因。请注意,我正在传递有效的访问令牌。 我的场景:基本上我已经在授权服务器中创建了logout rest api,我希望允许带有有效令牌的请求访问这个api。 请求: 回应: 我发现下面的方法返回false,因此它引发了访问拒绝错误。 下面是我通过框架调试捕获的屏幕截图。还请检查评论中提到的图像。