尽管具有管理员角色,但访问被拒绝

时间:2018-07-19 12:38:07

标签: spring spring-boot spring-security roles

我有这个配置类:

package com.practice.springbootdemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class MyConfiguration extends WebSecurityConfigurerAdapter{

    @Autowired
    public void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.inMemoryAuthentication().withUser("myname").password("abcd")
                .roles("ADMIN");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/home")
                .hasRole("ADMIN")
                .and()
                .formLogin();
    }
}

但是,当我查询“ / home”并提供凭据时:

username: myname
password: abcd

它使我无法访问。

我不明白为什么。任何帮助表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题。

显然,Spring的密码编码器存在问题。 我必须通过在密码前添加{noop}来明确取消Spring中的默认编码操作,如下所示:

builder.inMemoryAuthentication().withUser("myname").password("{noop}abcd")
            .roles("ADMIN");

通过这种方式,密码为纯文本"abcd"(不带引号)。 因此,当我输入我的凭据时,这匹配了,并且一切正常。

相关问题