gpt4 book ai didi

java - Spring Security 使用 sql 查询对管理员进行身份验证

转载 作者:行者123 更新时间:2023-12-02 11:39:28 24 4
gpt4 key购买 nike

我一直在尝试实现 spring security 提供的管理员服务,但我发现这很困难,我所有的标准用户都可以使用 webapp,但我似乎无法计算出验证用户拥有“ADMIN”所需的 sql角色以允许他们查看某些页面。

任何帮助建议将不胜感激,因为我是新手。(注意:我在控制台中没有收到任何错误,只有 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;
}



}

最佳答案

您可以使用 HandlerInterceptor 来检查登录角色是否为管理员。使用HandlerInterceptor接口(interface)的prehandle()方法,您可以处理请求并检查角色,如果登录角色不匹配,您可以将请求分派(dispatch)到403页面

登录后将角色对象添加到 session 中,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 {

}

}

关于java - Spring Security 使用 sql 查询对管理员进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48687694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com