gpt4 book ai didi

java - 如何允许匿名访问@RequestMapping?

转载 作者:行者123 更新时间:2023-12-02 12:44:39 27 4
gpt4 key购买 nike

如何定义 @RequestMapping 方法来显式允许匿名(未经授权)访问?

以下方法不起作用,总是收到 401 Unauthorized:

@RequestMapping("/test")
@Secured(value={"ROLE_ANONYMOUS"})
public String test() {
return "OK";
}

一般来说,整个应用程序使用 spring-boot 进行如下保护:

security.basic.enabled=true

@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
}

最佳答案

您可以重写 configure(HttpSecurity httpSecurity) 方法并在那里定义您的规则:

@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception
{
httpSecurity.authorizeRequests()
.antMatchers("/test")
.permitAll();
super.configure(http);
}
}

关于java - 如何允许匿名访问@RequestMapping?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44818653/

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