Spring Boot Security登录成功但始终返回禁止。

huangapple go评论56阅读模式
英文:

Spring Boot Security login success but always return forbidden

问题

I was use Spring Boot Security for my application, and the user role infomation is saved in mysql database. But after user success that always return 403 forbidden, no matter what kind authority user that I has been logined.

Here is my test data record:

id, user_name, password, role, authority, is_enabled
1, "Hedworth", "123", "USER", 1, 1
2, "Geoffrey", "123", "ADMIN", 1, 1

Here is my MySQL entity java bean:

public class TbUser implements Serializable, UserDetails {

    private static final long serialVersionUID = 213034465413641992L;

    private String id;

    private String userName;

    private String password;

    private String role;

    private String authority;

    private Integer isEnabled;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        String[] roles = role.split(",");
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }

    @Override
    public String getUsername() {
        return this.userName;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.isEnabled == 1;
    }

}

The security user role infomation query.

public class TbUserServiceImpl implements TbUserService {

    @Resource
    private TbUserDao tbUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return tbUserDao.queryByName(username);
    }
}

My Security configuration.

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private TbUserService tbUserService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(tbUserService)
                .passwordEncoder(new CustomPwdEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/api/user/**").hasRole("USER")
                .antMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}
英文:

I was use Spring Boot Security for my application, and the user role infomation is saved in mysql database. But after user success that always return 403 forbidden, no matter what kind authority user that I has been logined.

Here is my test data record:

id, user_name, password, role, authority, is_enabled
1, &quot;Hedworth&quot;, &quot;123&quot;, &quot;USER&quot;, 1, 1
2, &quot;Geoffrey&quot;, &quot;123&quot;, &quot;ADMIN&quot;, 1, 1

Here is my MySQL entity java bean:

public class TbUser implements Serializable, UserDetails {

    private static final long serialVersionUID = 213034465413641992L;

    private String id;

    private String userName;

    private String password;

    private String role;

    private String authority;

    private Integer isEnabled;

    @Override
    public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {
        String[] roles = role.split(&quot;,&quot;);
        List&lt;SimpleGrantedAuthority&gt; authorities = new ArrayList&lt;&gt;();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }

    @Override
    public String getUsername() {
        return this.userName;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.isEnabled == 1;
    }

}

The security user role infomation query.

public class TbUserServiceImpl implements TbUserService {

    @Resource
    private TbUserDao tbUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return tbUserDao.queryByName(username);
    }
}

My Security configuration.

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private TbUserService tbUserService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(tbUserService)
                .passwordEncoder(new CustomPwdEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers(&quot;/api/user/**&quot;).hasRole(&quot;USER&quot;)
                .antMatchers(&quot;/api/admin/**&quot;).hasRole(&quot;ADMIN&quot;)
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}

答案1

得分: 0

403 Forbidden出现时,意味着您的用户已被验证,但他没有足够的权限。

在您的情况下,您在配置中混合了角色/权限。

角色是一种权限,可以翻译为权限,使用"ROLE_"前缀。例如:(角色:USER)->(权限:ROLE_USER)或(角色:ADMIN)->(权限:ROLE_ADMIN)。

您有两个选择:

  • 仅使用权限。将.antMatchers("/api/user/**").hasRole("USER") 更改为.antMatchers("/api/user/**").hasAuthority("USER")

  • 翻译您的角色。将authorities.add(new SimpleGrantedAuthority(role)) 更改为authorities.add(new SimpleGrantedAuthority("ROLE_" + role))
英文:

When 403 Forbidden occurs, it means that your user is authenticated but he doesn't have enough permissions.

In your case, you are mixing roles/authorities in your configuration.

A role is an authority and can be translated to an authority, prefixing the role with "ROLE_". For example: (Role: USER) -> (Authority: ROLE_USER) or (Role: ADMIN) -> (Authority: ROLE_ADMIN).

You have two choices:

  • Use authorities only. Change .antMatchers(&quot;/api/user/**&quot;).hasRole(&quot;USER&quot;) to .antMatchers(&quot;/api/user/**&quot;).hasAuthority(&quot;USER&quot;)

OR

  • Translate your roles. Change authorities.add(new SimpleGrantedAuthority(role)) to authorities.add(new SimpleGrantedAuthority(&quot;ROLE_&quot; + role))

huangapple
  • 本文由 发表于 2023年4月17日 15:46:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定