Spring Security使用sql查询验证管理员

时间:2018-02-08 14:20:26

标签: java sql spring-security

我一直在尝试实现管理员服务spring安全性提供,但我发现很难,所有我的标准用户都可以使用webapp但我似乎无法计算出验证用户有一个&#34所需的sql ; ADMIN"允许他们查看某些页面的角色。

任何帮助建议都会非常感激,因为我是新手。 (注意:我的控制台中没有错误,只有403用户名/密码被拒绝页面)

我的WebSecurityConfig文件:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
       UserLoginRepository userLoginRepository;


    //http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")

     @Autowired
     DataSource dataSource;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
                    .anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
                    .permitAll();
            http.exceptionHandling().accessDeniedPage("/403");
            http.csrf().disable();
            //disable csrf to allow communication (we also dont need for this fyp as its not live)
        }



    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        //authorities at the moment is the manager i.e. 'Manager' from user_login

//       String userByMailQuery = "SELECT user_type FROM user_login WHERE user_type = ?;";

           auth.jdbcAuthentication().dataSource(dataSource)
          .usersByUsernameQuery("select user_name,password,user_status from user_login where user_name=?")
       .authoritiesByUsernameQuery("select user_login_id, roles_id, role from user_login_roles, role where user_login_id=?");          




}

    }

.authoritiesByUsernameQuery是我挣扎的查询。逻辑是检查用户是否具有值为" ADMIN"的角色。

我的UserLogin课程:

@Entity
public class UserLogin {


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private Long phone;
private String userName;
private String address;
private String password;
private boolean userStatus;
private String userType;
private String position;


@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public Set<Role> roles;

@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
 public Set<PlayerSeasonStat> playerStats;

public UserLogin()
{

}

public UserLogin(Long id, String firstName, String lastName, Long phone,
        String userName, String address, String password,
        boolean userStatus, String userType, String position,
        Set<Role> roles, Set<PlayerSeasonStat> playerStats) {
    super();
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.phone = phone;
    this.userName = userName;
    this.address = address;
    this.password = password;
    this.userStatus = userStatus;
    this.userType = userType;
    this.position = position;
    this.roles = roles;
    this.playerStats = playerStats;
}




public Set<Role> getRoles() {
    if (roles==null)
        roles = new HashSet<>();


    return roles;
}

public void setRole(Set<Role> roles) {
    this.roles = roles;
}

public void addRole(Role role){

    getRoles().add(role);
}

我的角色类:

@Entity
public class Role {


    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String role;


    public Role()
    {

    }


    public Role(Long id, String role) {
        super();
        this.id = id;
        this.role = role;
    }


    public Long getId() {
        return id;
    }


    public void setId(Long id) {
        this.id = id;
    }


    public String getRole() {
        return role;
    }


    public void setRole(String role) {
        this.role = role;
    }



}

1 个答案:

答案 0 :(得分:1)

您可以使用HandlerInterceptor,您可以在其中检查登录角色是否为admin。使用HandlerInterceptor接口的prehandle()方法可以处理请求并检查角色,如果登录角色不匹配,可以将请求发送到403页面

登录后将角色对象添加到会话request.getSession().setAttribute("LOGGEDIN_USER_ROLE",roleObject),您可以使用HandlerInterceptorAdapter

public class SecurityInterceptor extends HandlerInterceptorAdapter {


  @Override
  public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Interceptor: Pre-handle");

    // Avoid a redirect loop for some urls
    if(request.getRequestURI().equals("/admin-page")){
          Role  role = (Role) request.getSession().getAttribute("LOGGEDIN_USER_ROLE");
          if(!role.getRole().equalsIgnoreCase("ADMIN")){
             response.sendRedirect("/403/");
            return false;
       }   
      }

    return true;
}

 @Override
 public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {

  }

 }