英文:
AuthenticationManagerBuilder in java
问题
@Configuration
@EnableWebSecurity
//@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll()
.anyRequest().authenticated() // any other request requires authentication
.and()
.addFilterBefore(new LoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("{noop}password").roles("USER").and().withUser("admin")
.password("{noop}password").roles("ADMIN");
//// here I want to add all my users from the database
}
}
请注意,您想要从数据库中添加所有用户并为其生成令牌的部分需要根据您的数据库结构和认证逻辑进行自定义实现。这部分的代码不在您提供的示例中,您需要编写一个适合您的数据库和用户认证的逻辑来实现此功能。
英文:
I trying to set up an authentication with angular/ Java. for the java part I have all the filters working so I only can go to /login without a token. The only thing that is not working is checking users passwords and handing out Tokens for others than the inMemoryAuthentication for now this are 1 user and 1 admin. How can I link my Users entity (i have users server dao controller etc...) so I can give tokens to all my users in the database after checking there passwords.
this is what I have now :
@Configuration
@EnableWebSecurity
//@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll()
.anyRequest().authenticated() // cualquier otra peticion requiere autenticacion
.and()
.addFilterBefore(new LoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("{noop}password").roles("USER").and().withUser("admin")
.password("{noop}password").roles("ADMIN");
//// here I want to add all my users from the database
}
}
答案1
得分: 1
你可以使用JDBCAuthentication Builder来将所有用户存储和从数据库中检索出来。
首先定义要使用的模式 schema.sql
-
CREATE TABLE users (
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
enabled TINYINT NOT NULL DEFAULT 1,
PRIMARY KEY (username)
);
CREATE TABLE authorities (
username VARCHAR(50) NOT NULL,
authority VARCHAR(50) NOT NULL,
FOREIGN KEY (username) REFERENCES users(username)
);
CREATE UNIQUE INDEX ix_auth_username
ON authorities (username, authority);
然后是一些示例数据 data.sql
-
INSERT INTO users (username, password, enabled)
VALUES ('user',
'$2a$10$8.UnVuG9HHgffUDAlk8qfOuVGkqRzgVymGe07xd00DMxs.AQubh4a',
1);
INSERT INTO authorities (username, authority)
VALUES ('user', 'ROLE_USER');
更新你的应用程序属性以指向正确的数据库 -
# MySQL
#spring.datasource.url=jdbc:mysql://localhost:3306/test
#spring.datasource.username=dbuser
#spring.datasource.password=dbpass
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
同时告诉 Hibernate 你不在使用默认模式,因此你应该禁用 ddl-auto
属性 -
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=none
然后,你可以按以下方式更新安全配置 -
@Configuration
@EnableWebSecurity
//@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
// 与数据库建立的数据源连接
@Autowired
DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll()
.anyRequest().authenticated() // 任何其他请求需要认证
.and()
.addFilterBefore(new LoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 告诉 Spring 使用基于数据库的认证。
auth.jdbcAuthentication()
.dataSource(dataSource);
}
}
英文:
You can use the JDBCAuthentication Builder to store and retrieve all the users from DB.
First define the schema to be used schema.sql
-
CREATE TABLE users (
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
enabled TINYINT NOT NULL DEFAULT 1,
PRIMARY KEY (username)
);
CREATE TABLE authorities (
username VARCHAR(50) NOT NULL,
authority VARCHAR(50) NOT NULL,
FOREIGN KEY (username) REFERENCES users(username)
);
CREATE UNIQUE INDEX ix_auth_username
on authorities (username,authority);
Then some sample data data.sql
-
INSERT INTO users (username, password, enabled)
values ('user',
'$2a$10$8.UnVuG9HHgffUDAlk8qfOuVGkqRzgVymGe07xd00DMxs.AQubh4a',
1);
INSERT INTO authorities (username, authority)
values ('user', 'ROLE_USER');
Update your application properties to point to the correct DB -
# MySQL
#spring.datasource.url=jdbc:mysql://localhost:3306/test
#spring.datasource.username=dbuser
#spring.datasource.password=dbpass
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
Also tell hibernate that your are not using default schema, so you should disable the ddl-auto
property
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=none
Then you can update your security configuration as follows -
@Configuration
@EnableWebSecurity
//@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
//DataSource connection to your DB
@Autowired
DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll()
.anyRequest().authenticated() // cualquier otra peticion requiere autenticacion
.and()
.addFilterBefore(new LoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//Telling spring to use DB based authentication.
auth.jdbcAuthentication()
.dataSource(dataSource);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论