gpt4 book ai didi

java - Spring Security配置问题

转载 作者:行者123 更新时间:2023-12-01 16:23:47 25 4
gpt4 key购买 nike

我刚刚开始与 Spring 的冒险,请提供帮助。

我尝试在 Spring Boot 应用程序上配置 Spring Security,如下所示:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Value("${spring.queries.users-query}")
private String usersQuery;

@Value("${spring.queries.roles-query}")
private String rolesQuery;

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
/* auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.passwordEncoder(passwordEncoder());*/

auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("user"))
.authorities("ROLE_USER");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET,"/create").permitAll()
.anyRequest()
.authenticated();
http.csrf().disable();
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

我的 Controller 是:

@RestController
public class LoginController {

@Autowired
private UserService userService;

@GetMapping("/users")
public String login() {
return "working";
}

@GetMapping("/create")
public User create() {
User user = new User();
user.setPassword("user1");
user.setEmail("user1@wp.pl");
user.setName("user1");
userService.save(user);
return user;
}
}

和我的运行类(class):

@ComponentScan(basePackages = "main.service, main.repository")
@SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
public class HomeworkApplication {
public static void main(String[] args) {
SpringApplication.run(HomeworkApplication.class, args);
}
}

我使用 POSTMAN 来测试我的端点,但每次都会收到 401。

有人可以帮我解决这个问题。我花了很多时间,但没有找到解决方案。

谢谢!

编辑!!! enter image description here

最佳答案

请从 HomeworkApplication 中删除 @ComponentScan(basePackages = "main.service, main.repository")。它覆盖了 SpringBootApplication 的默认组件扫描。

如果您需要扫描特定包,请添加如下配置类,

@ComponentScan(basePackages = "main.service, main.repository")
@Configuration
public class AppConfig{
}

关于java - Spring Security配置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62200952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com