gpt4 book ai didi

java - Spring 安全: log in using roles from database

转载 作者:行者123 更新时间:2023-11-30 05:27:37 25 4
gpt4 key购买 nike

我在数据库中有 3 个表:USER(login,password)ROLE(role_name)USER_ROLE_LINK (user_id, role_id)

我想为具有特定角色的用户授予对特定页面的访问权限。

我在这个类中配置了安全性:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private DataSource dataSource;

@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.usersByUsernameQuery("select login, password, active from USER where login=?")
.authoritiesByUsernameQuery("select ur.user_id, ur.role_id from USER u inner join USER_ROLE_LINK ur on u.id = ur.user_id where u.login=?");
}
}

它工作正常,只有至少拥有一个角色的用户才能访问该应用程序。现在我想为具有特定角色的用户授予对特定页面的访问权限,该怎么做?

我尝试过这个:antMatchers("/mypage").hasRole("MODERATOR"),但它抛出403错误。我应该如何告诉 SpringROLE 表的 role_name 列中查找用户的角色?

最佳答案

It works fine?

不,您在 .authoritiesByUsernameQuery 方法参数中的查询字符串有误。

查询返回类型,即结果集应为用户名和角色

SELECT username, role

如果连接查询结果的结果集列名称如下所示:

enter image description here

您应该修改为如下所示:

enter image description here

通过使用别名SELECT ud.username AS用户名,rm.name AS角色

I've tried this: antMatchers("/mypage").hasRole("MODERATOR") but it throws 403 error

它不会工作,因为您的授权部分不正确。

How should I tell Spring to look for an user's roles from ROLE table's role_name column?

需要完整的认证和授权配置。请参阅下面的内容。

我将举一个可行的例子:

考虑您的要求具有类似的三个表 userdetailsrolemasteruser_role_mapping,如下所示。

enter image description here

那么你的配置将是

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{

@Autowired
DataSource dataSource;

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception
{
//If you want to store plain password you can use NoOpPasswordEncoder
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder())
.usersByUsernameQuery("select username, password, enabled from userdetails where userName=?")
.authoritiesByUsernameQuery(
"SELECT ud.username AS username, rm.name AS role FROM user_role_mapping map " +
"INNER JOIN userdetails ud ON map.userId = ud.id " +
"INNER JOIN rolemaster rm ON map.roleId = rm.id where userName = ?");
}

@Override
protected void configure(final HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.antMatchers("/resources/**", "/", "/login", "/api/**").permitAll()
.antMatchers("/config/**", "/app/admin/**")
.hasRole("ADMIN")
.antMatchers("/app/user/**")
.hasAnyRole("ADMIN", "USER")
.and().exceptionHandling().accessDeniedPage("/403")
.and().formLogin()
.loginPage("/login")
.usernameParameter("userName").passwordParameter("password")
.defaultSuccessUrl("/app/user/dashboard")
.failureUrl("/login?error=true")
.and().logout()
.logoutSuccessHandler(new CustomLogoutSuccessHandler())
.invalidateHttpSession(true)
.and()
.csrf()
.disable();

http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired=true");
}

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

}

授权部分
对存储在 resources 文件夹中的 javascript 和 css 等资源进行绕过授权。

.antMatchers("/resources/**", "/", "/login", "/api/**").permitAll()

对于管理网址

.antMatchers("/config/**", "/app/admin/**").hasRole("ADMIN")

对于可由多个角色访问的网址

.antMatchers("/app/user/**").hasAnyRole("ADMIN", "USER")

.formLogin()配置:

.usernameParameter("userName").passwordParameter("password") 
// Use above line of code if your login form param names are different
// than defaults -> "username" "password"
.defaultSuccessUrl("/app/user/dashboard")
// If defaultSuccessUrl not configured then after login success redirects to "/"

异常处理部分

.exceptionHandling().accessDeniedPage("/403")
//If you want custom denied screen to be displayed.

关于java - Spring 安全: log in using roles from database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252308/

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