Java Spring安全禁用默认登录页面
我希望在RESTAPI中集成Spring安全性。我有问题,因为我的配置阻塞了所有路由 我的配置:Java Spring安全禁用默认登录页面,java,spring,spring-mvc,Java,Spring,Spring Mvc,我希望在RESTAPI中集成Spring安全性。我有问题,因为我的配置阻塞了所有路由 我的配置: @Configuration @EnableResourceServer public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception {
@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/
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的权限?下一步:
当使用permitAll
时,它意味着每个经过身份验证的用户,但是您禁用了匿名访问,因此无法使用
试一试
这对我很有用,添加示例:
http.csrf().disable()
.anonymous().authorities("ROLE_ANONYMOUS")
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.GET, appConfigHolder.getSecurity().getLoginUrl()).permitAll()
编辑:
问题出在春季版。使用v1.4.3.REALESE没有问题。Spring boot user,您可以通过扩展WebSecurityConfigureAdapter类禁用默认登录页面,并提供对“/login”页面的访问许可和获取请求
@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers(HttpMethod.OPTIONS,"*/").permitAll()
.antMatchers(HttpMethod.GET,"/login").permitAll();
}
}
要禁用默认登录页面(从而禁用Spring的基本安全功能),请确保@SpringBootApplication注释如下所示:
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class MyApp{
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
重要的部分是:@springbootplication(exclude={SecurityAutoConfiguration.class})
。这将禁用Spring安全功能的自动配置
我发现这很有帮助:可能尝试手动为Get请求.antMatchers(HttpMethod.Get,“/”).permitAll()
不使用它。和.antMatchers(HttpMethod.Get,“/*”).permitAll()
?同样的问题仍然是同样的问题web.ignering().antMatchers(“/”)
我不使用WebSecurity
但HttpSecurity
此代码不可编译。我尝试这样做http.anonymous().authorities(“ROLE_anonymous”).and().authorizeRequests().antMatchers(“/”.permitAll()代码>但它不起作用。我添加了你的代码,但仍然是相同的错误。我用的是Spring Boot 1.5.4,对我来说不适用。弹簧靴启动器2.1.5和弹簧靴安全启动器2.1.5