我想使用Spring安全性,但我之前从未使用它。我想从我的表(用户,角色和user_roles)中检索用户和角色。我调查了用户 - 用户名-query 即可。在所有示例中都与以下示例相同。
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select username,password, enabled from users where username=?"
authorities-by-username-query=
"select username, role from user_roles where username =? " />
</authentication-provider>
</authentication-manager>
但我想使用 id_user 和 id_role 代替用户名和角色。可能吗 ?我必须更改登录页面字段名称吗? 提前致谢
答案 0 :(得分:8)
这是一种常见情况。
首先,正如我在评论中建议的那样,使用别名重命名代表用户名,密码和用户启用与否的字段。就像这样:
users-by-username-query=
"select user.user_login as username, user.user_pwd as password, user.user_enabled as enabled
from user where user.user_login=?"
然后,通常也会让authorities
在不同的表中以某种方式与user
表相关联。这是一个常见的情况:
用户与n-to-n
关系中的角色相关。
在这种情况下,authorities-by-username-query
应该是这样的
authorities-by-username-query=
"SELECT users.name as username, roles.role as role
FROM users
INNER JOIN user_role ON users.id_user = user_role.id_user
INNER JOIN roles ON user_role.id_role = roles.id_role
WHERE users.name = ? "
作为测试,对于包含此数据的一组表:
用户:
作用:
USER_ROLE
对于收到的用户名 jlumietu ,结果应为:
最后,我有一些案例,我已经扩展org.springframework.security.authentication.dao.DaoAuthenticationProvider,但我认为这是进行此类处理的最简单方法
答案 1 :(得分:0)
对于字符串启动2,它的工作方式是这样
package com.gkatzioura.spring.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class PasswordEncodedSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
//.passwordEncoder(new BCryptPasswordEncoder())
.passwordEncoder(passwordEncoder())
.usersByUsernameQuery("select username,password,enabled from users where username =?")
.authoritiesByUsernameQuery(" select u.username, r.name from users u join user_role ur on u.id = ur.user_id " +
" join role r on ur.role_id = r.id where u.username =?");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/public").permitAll()
.anyRequest().authenticated()
.and().formLogin().permitAll()
.and().logout() .permitAll();
}
@Bean
public PasswordEncoder passwordEncoder(){
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder;
}
}