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

无法暂时禁用Spring安全(403禁止)

卞浩漫
2023-03-14

我想暂时禁用整个应用程序的Spring Security性,但我总是被403禁止

删除控制器中的@PreAuthorize注释不会给出任何结果。未使用此注释标记的endpoint也会丢弃我 403 禁止 我不需要基本身份验证 我不需要身份验证

我的Spring Security配置:(/,/api/**,/**,**不工作,我总是得到403禁止)

package com.project.webstation.Config;

import com.project.webstation.Services.CustomUserDetailsService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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 org.springframework.security.crypto.password.PasswordEncoder;
@AllArgsConstructor
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final CustomUserDetailsService userDetailsService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http
//                .csrf().disable()
//                .authorizeRequests()
//                .antMatchers(HttpMethod.POST,"/api/user/").permitAll()
//                .anyRequest()
//                .authenticated()
//                .and()
//                .httpBasic();
        http.csrf().disable().authorizeRequests().antMatchers("/").permitAll();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder(12);
    }

    @Bean
    protected DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(getPasswordEncoder());
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        return daoAuthenticationProvider;
    }
}

我的一个控制者:

@Slf4j
@RestController
@RequestMapping("/api/user/")
@AllArgsConstructor
public class UserController {

    private final UserMap userMap;

    private final UserService userService;


    //@PreAuthorize("hasAuthority('user:read')")
    @ApiOperation(value = "Getting  user by the id")
    @GetMapping(value = "{id}")
    public ResponseEntity<UserResponse> getUser(@PathVariable("id") long Id) {
        User user = userService.findById(Id);
        UserResponse userResponse = userMap.userToResponse(user);
        return new ResponseEntity<>(userResponse, HttpStatus.OK);
    }

    @ApiOperation(value = "getting  user data from request body and saving it to database")
    @PostMapping(value = "")
    public ResponseEntity<UserSaveResponse> saveUser(@RequestBody UserRequest userRequest) {
        User user = userService.save(userRequest);
        UserSaveResponse userSaveResponse = userMap.userToSaveResponse(user);
        return new ResponseEntity<>(userSaveResponse, HttpStatus.CREATED);
    }

    @PreAuthorize("hasAuthority('user:write')")
    @ApiOperation(value = "getting  user data from request body and updating it in database(Admin method, can do it for all users)")
    @PutMapping(value = "/{id}")
    public ResponseEntity<UserResponse> updateUser(@AuthenticationPrincipal SecurityUser user, @RequestBody UserEditRequest userEditRequest, @PathVariable("id") int id) {
        User updatedUser = userService.update(id, userEditRequest,user);
        UserResponse userResponse = userMap.userToResponse(updatedUser);
        return new ResponseEntity<>(userResponse, HttpStatus.CREATED);
    }


    @PreAuthorize("hasAuthority('user:write')")
    @ApiOperation(value = "Deleting user by id from the database")
    @DeleteMapping(value = "{id}")
    public ResponseEntity<UserResponse> deleteUser(@AuthenticationPrincipal SecurityUser authenticatedUser,@PathVariable("id") int id) {
        userService.delete(id,authenticatedUser);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PreAuthorize("hasAuthority('user:read')")
    @ApiOperation(value = "Getting all the Users from the database")
    @PostMapping(value = "get")
    public ResponseEntity<List<UserResponse>> findAllWithFilters(@RequestBody UserFilterProperties userFilterProperties) {
        return new ResponseEntity<>(userService.getAllWithFilters(userFilterProperties),HttpStatus.OK);
    }


    @PreAuthorize("hasAuthority('user:read')")
    @ApiOperation(value = "Subscribe on user")
    @PutMapping(value = "{id}/subscribe")
    public ResponseEntity<UserResponse> subscribe(@RequestBody UserSubscriptionRequest userSubscriptionRequest, @AuthenticationPrincipal SecurityUser user, @PathVariable("id") Long id) {
         userService.subscribe(id,user,userSubscriptionRequest);
         return new ResponseEntity<>(HttpStatus.OK);
    }


     @PreAuthorize("hasAuthority('user:read')")
        @ApiOperation(value = "Unsubscribe from user")
        @PutMapping(value = "{id}/unsubscribe")
        public ResponseEntity<UserResponse> unsubscribe(@RequestBody UserSubscriptionRequest userSubscriptionRequest,@AuthenticationPrincipal SecurityUser user, @PathVariable("id") Long id) {
            userService.unsubscribe(user,id,userSubscriptionRequest);
            return new ResponseEntity<>(HttpStatus.OK);
        }
        @PreAuthorize("hasAuthority('user:read')")
        @ApiOperation(value = "Getting all user's subscribers")
        @GetMapping(value = "{id}/subscribers")
        public ResponseEntity<Set<UserResponse>> getSubscribers(@PathVariable("id") Long Id) {
            return new ResponseEntity<>(userService.getSubscribers(Id),HttpStatus.OK);
        }
    
        @PreAuthorize("hasAuthority('user:read')")
        @ApiOperation(value = "Getting all user's subscriptions")
        @GetMapping(value = "{id}/subscriptions")
        public ResponseEntity<Set<UserResponse>> getSubscriptions(@PathVariable("id") Long Id) {
            return new ResponseEntity<>(userService.getSubscriptions(Id),HttpStatus.OK);
        }
@PreAuthorize("hasAuthority('user:write')")
    @ApiOperation(value = "upload file attached to the user")
    @PostMapping(value = "{userId}/upload")
    public ResponseEntity<User> uploadImage(@PathVariable("userId") Long id,
                                            @RequestParam("file") MultipartFile file,
                                            @AuthenticationPrincipal SecurityUser user) throws IOException
                                                {
        userService.saveImageForUser(id,file,user);
        return new ResponseEntity<>(HttpStatus.OK);
    }

共有1个答案

吕德业
2023-03-14

将其添加到您的SecurityConfig类以完全忽略指定的url模式…

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/**");
}
 类似资料:
  • 我正在尝试使用Spring security保护我的网站,但我一直收到

  • 我有一个简单的web应用程序,其中用户名和密码(在登录页面中输入)使用Spring Security根据LDAP进行身份验证。 这里几乎一切都是配置。我可以张贴所有的配置。文件,如果必要的话。 为了演示/测试等目的,我需要一种暂时禁用此身份验证的方法。理想情况下,如果登录页面上存在“不验证”复选框,则应绕过身份验证。 当然我可以删除所有Spring Security的东西。B 最简单/最好的方法是

  • 我在Spring实现了WebSocket。一切正常,但最近我决定实施SpringSecurity。 我的MessageBroker看起来像: 我的JS客户看起来像这样: Spring Security配置: 通过我的JS客户端订阅后,我收到: 所以我决定在安全配置中添加此代码: 但在那之后我收到这种错误: 我不知道如何定义这样的bean,所以我创建了以下类: 但在编译期间,我收到这种错误: 我真的

  • 我有我的spring boot应用程序,我正在尝试添加Spring Security性,但当我通过postman发出请求时,我不断收到一个403 Forbbiden,联机时我发现我应该在我的配置中添加:“.csrf().disable()”,但它不起作用(如果我在permitAll()中放置路径为:“person/**”的方法,则所有操作都有效) 这是我的代码: 我的用户控制器: My perso

  • 我有一个以前使用 Spring Boot 1 运行测试的应用程序,并且已更新到 2.0.9.RELEASE。 Spring Security现在有问题。我知道情况是这样的,因为如果我删除 测试仍然成功。测试基本上是去一个项目控制器'Home计数器',然后从那里去一个服务,并使用一个雷斯特模板来执行各种操作。实际上,这是一个不同的应用程序,如果我从头开始编写它,我可能会做一个wiremck,但现在这

  • 当我使用security.basic.enabled=false在具有以下依赖项的Spring Boot项目上禁用安全性时: 为了修复此异常,我必须添加属性-management.security.enabled=false。我的理解是,当执行器在类路径中时,应该将security.basic.enabled=false和management.security.enabled=false设置为禁用