inMemoryAuthentication无效

时间:2016-04-18 14:43:42

标签: spring spring-mvc spring-security

我正在使用spring Security 4.0.4

但是当我将用户名和密码发布到'\ login'时。它总是被拒绝。

我使用java-base config。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");//dba have two roles.
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/", "/index").access("hasRole('ADMIN')")
                .and().formLogin().loginPage("/login")
                .usernameParameter("nickname").passwordParameter("password")
                .and().csrf()
                .and().exceptionHandling().accessDeniedPage("/Access_Denied");

    }
}

和我的login.html

<form class="form-horizontal" ng-controller="loginCtrl" action="/login" method="post">
    <div class="form-group input-login">
        <label  class="control-label sr-only">Email</label>
        <div class="col-md-12">
            <input type="nickname" class="form-control" ng-model="user.username" name="nickname" placeholder="NickName">
        </div>
    </div>
    <div class="form-group input-login">
        <label  class="control-label sr-only">Password</label>
        <div class="col-md-12">
            <input type="password" class="form-control" ng-model="user.password" name="password" placeholder="Password">
        </div>
    </div>
    <div class="form-group sub-login">
        <div class=" col-md-12">
            <button type="submit" class="btn btn-primary btn-login">Login</button>
        </div>
    </div>
</form>

我尝试发布昵称'admin'和密码'root123'。但总是被拒绝。我不知道问题出在哪里。

1 个答案:

答案 0 :(得分:0)

csrf保护可能是它的原因。你可以尝试禁用它(只是为了确保问题与此有关):

http.authorizeRequests()
                .antMatchers("/", "/index").access("hasRole('ADMIN')")
                .and().formLogin().loginPage("/login")
                .usernameParameter("nickname").passwordParameter("password")
                .and().csrf().disable()
                .and().exceptionHandling().accessDeniedPage("/Access_Denied");

如果问题确实是csrf,那么你应该阅读这篇解释如何发送令牌的Spring文档。 https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html