尽管具有管理员角色,但访问被拒绝
Access Denied in spite of having admin role
我有这个配置class:
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
它让我访问被拒绝。
我不明白为什么。任何帮助表示赞赏。谢谢
我已经自己解决了这个问题。
显然,Spring 的密码编码器存在问题。
我必须通过在密码前添加 {noop}
来显式取消 Spring 中的默认编码操作,如下所示:
builder.inMemoryAuthentication().withUser("myname").password("{noop}abcd")
.roles("ADMIN");
通过这种方式,密码是纯文本 "abcd"
(不带引号)。
因此,当我输入我的凭据并且一切正常时,这就匹配了。
我有这个配置class:
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
它让我访问被拒绝。
我不明白为什么。任何帮助表示赞赏。谢谢
我已经自己解决了这个问题。
显然,Spring 的密码编码器存在问题。
我必须通过在密码前添加 {noop}
来显式取消 Spring 中的默认编码操作,如下所示:
builder.inMemoryAuthentication().withUser("myname").password("{noop}abcd")
.roles("ADMIN");
通过这种方式,密码是纯文本 "abcd"
(不带引号)。
因此,当我输入我的凭据并且一切正常时,这就匹配了。