角色在Spring安全性中无法正常工作

时间:2019-07-04 14:51:18

标签: spring authentication spring-security authorization

我正在开发一个基于Spring Security的Web应用程序,在该应用程序中,我想根据登录用户是否具有ADMIN或USER角色来限制侧栏上的项目。就身份验证而言,一切正常,但角色未按预期工作。

Following this post

例如-

<security:authorize access="hasRole('ADMIN')">
            <li class=" nav-item"><a href="<c:url value = "/mapview/list"/>"><i
                    class="fa fa-map-marker"></i><span class="menu-title" data-i18n="">MapView</span></a>
            </li>
            </security:authorize>

即使我以ADMIN身份登录,上述元素也永远不会可见。

有人可以在这里帮助我了解发生了什么事吗

安全配置

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Bean
    public AuthenticationProvider authProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(new BCryptPasswordEncoder());
        return provider;
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {


        httpSecurity
                .authorizeRequests().antMatchers("/login", "/resource/**").permitAll()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll()
                .loginProcessingUrl("/doLogin").successForwardUrl("/postLogin").failureUrl("/loginFailed").and()
                .logout().logoutUrl("/doLogout").logoutSuccessUrl("/logout").permitAll().and().csrf().disable();
    }


}

UserDetailsImpl

public class UserDetailsImpl implements UserDetails {

    private static final long serialVersionUID = 1L;
    private Collection<SimpleGrantedAuthority> authorities;
    private String username;
    private String password;
    private Boolean enabled = true;

    public void setAuthorities(Collection<SimpleGrantedAuthority> authorities) {
        this.authorities = authorities;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }
    @Override
    public String getPassword() {
        return password;
    }
    @Override
    public String getUsername() {
        return username;
    }
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return enabled;
    }

UserDetailsS​​ervice

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    private Converter<User, UserDetails> userUserDetailsConverter;

    @Autowired
    @Qualifier(value = "userToUserDetails")
    public void setUserUserDetailsConverter(Converter<User, UserDetails> userUserDetailsConverter) {
        this.userUserDetailsConverter = userUserDetailsConverter;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userUserDetailsConverter.convert(userService.findByUserName(username));
    }
}

UserToUserDetails

@Component
public class UserToUserDetails implements Converter<User, UserDetails>{
     @Override
        public UserDetails convert(User user) {
            UserDetailsImpl userDetails = new UserDetailsImpl();
            if (user != null) {
                userDetails.setUsername(user.getUsername());
                userDetails.setPassword(user.getEncryptedPassword());
                userDetails.setEnabled(user.getEnabled());
                Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
                user.getRoles().forEach(role -> {
                    authorities.add(new SimpleGrantedAuthority(role.getName()));
                });
                userDetails.setAuthorities(authorities);
            }
            return userDetails;
        }
    }

控制器

@SessionAttributes({ "currentUser" })
@Controller
public class HomeController {
  //skipping other mappings
@RequestMapping(value = "/postLogin", method = RequestMethod.POST)
    public String postLogin(Model model, HttpSession session) {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        validatePrinciple(authentication.getPrincipal());
        String username = ((UserDetailsImpl) authentication.getPrincipal()).getUsername();
        model.addAttribute("currentUser", username);
        return "redirect:/dashboard";
    }

}

UsernamePasswordAuthenticationToken authentication in controller

用户

@Entity
public class User extends Auditable<String> {

//skipping other details
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "user_role",
            joinColumns = { @JoinColumn(name = "user_id") },
            inverseJoinColumns = { @JoinColumn(name = "role_id") })
    private Set<Role> roles = new HashSet<>();

}

在db-

中创建的表
user
role
user_role

编辑1

只需将此映射添加到我的控制器中,登录后,如果在浏览器上单击/ test,则两个布尔值均显示 false 。我不知道为什么不设置角色。:-(

@GetMapping(value = "/test")
    public void test(SecurityContextHolderAwareRequestWrapper request) {
        boolean b = request.isUserInRole("ADMIN");
        System.out.println("ROLE_ADMIN=" + b);

        boolean c = request.isUserInRole("USER");
        System.out.println("ROLE_USER=" + c);
    }

编辑2

但是,与此同时,以下代码显示了ADMIN的角色

public void test(SecurityContextHolderAwareRequestWrapper request) {

        for (GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
            String userRole = authority.getAuthority();
            System.out.println(userRole);
        }
    }

Admin Role

1 个答案:

答案 0 :(得分:0)

这似乎在从数据库检索到返回响应给浏览器之间的信息丢失了(很明显)。拥有调试器是一件好事,因此,我将首先跟踪访问数据库数据的每个步骤,直到返回该信息为止。遵循每个步骤,直到找到丢失的位置,然后将其缩小到单个位置再发回。如果不是,也许我们可以开始查看您的html / script / template引擎,但是只有在我们确定信息已到达浏览器之后。