springsecurity设置接口为所有人可登录
时间: 2023-12-11 21:02:35 浏览: 26
要将Spring Security配置为允许所有用户访问您的接口,您可以在配置类中使用以下代码:
```java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll() // 允许所有用户访问所有URL
.anyRequest().authenticated() // 除了以上的URL,其他的URL都需要身份认证
.and()
.formLogin()
.loginPage("/login") // 指定登录页面的URL路径
.permitAll() // 允许任何用户访问此登录页面
.and()
.logout()
.permitAll(); // 允许任何用户访问登出URL
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER"); // 在内存中创建一个用户,用户名为user,密码为password,角色为USER
}
}
```
在上面的代码中,`configure()`方法允许所有用户访问所有URL。`configureGlobal()`方法定义了一个在内存中的用户,用户名为`user`,密码为`password`,并且具有`USER`角色。在这个例子中,我们还指定了一个登录页面的URL路径为`/login`,并允许任何用户访问它。最后,我们还定义了一个登出URL并允许任何用户访问它。