我想将 Spring Security 集成到我的 REST API 中。我有问题,因为我的配置阻塞了所有路由。
我的配置:
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers(HttpMethod.POST,"/api/getNews").hasRole("ADMIN");
}
}
当我想在 http://localhost:8080/
上 GET
时,spring 返回登录表单
<html>
<head>
<title>Login Page</title>
</head>
<body onload='document.f.username.focus();'>
<h3>Login with Username and Password</h3>
<form name='f' action='/login' method='POST'>
<table>
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
<input name="_csrf" type="hidden" value="5453a3c5-2573-4861-b777-d008b04863c3" />
</table>
</form>
</body>
</html>
但是我有一个允许 /
的规则。为什么我无权访问我的 API?
最佳答案
要禁用默认登录页面(从而禁用 Spring 的基本安全功能),请确保您的 @SpringBootApplication 注释如下所示:
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class MyApp{
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
重要的部分是:@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
。这会禁用 Spring 安全功能的自动配置。
我发现这很有帮助:https://www.baeldung.com/spring-boot-security-autoconfiguration
关于java - Spring Security 禁用默认登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44629289/