Spring Security禁用默认登录页面

时间:2017-06-19 11:24:11

标签: java spring spring-mvc

我想在我的rest API中集成Spring Security。我有问题,因为我的汇款集中了所有路线。

我的配置:

@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");
    }
}

当我希望GET http://localhost:8080/春天返回登录表单

<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?

3 个答案:

答案 0 :(得分:2)

发现下一个:

  

使用permitAll时,它表示每个经过身份验证的用户,但是您禁用了匿名访问权限,以便无法正常工作。

尝试this

这适用于我,添加示例:

http.csrf().disable()
                .anonymous().authorities("ROLE_ANONYMOUS")
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(HttpMethod.GET, appConfigHolder.getSecurity().getLoginUrl()).permitAll()

编辑:

问题出在Spring版本中。用v1.4.3.REALESE没问题。

答案 1 :(得分:0)

Spring引导用户,您可以通过扩展WebSecurityConfigurerAdapter类来禁用默认登录页面,并提供对“ / login”页面和Get请求的访问许可。

@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();
    }
}

答案 2 :(得分:0)

要禁用默认登录页面(从而禁用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