[英]Implement Custom Spring Security Authentication Method
I am building a spring MVC web application, with a user login mechanism. 我正在构建一个带有用户登录机制的Spring MVC Web应用程序。 I have used spring-boot to set up my application. 我已经使用spring-boot来设置我的应用程序。 To authenticate a user with the database, I followed the following tutorial: 要使用数据库对用户进行身份验证,我遵循以下教程:
http://justinrodenbostel.com/2014/05/30/part-5-integrating-spring-security-with-spring-boot-web/ http://justinrodenbostel.com/2014/05/30/part-5-integrating-spring-security-with-spring-boot-web/
Here, spring's inbuilt authentication procedure is used. 在这里,使用spring的内置身份验证过程。 By specifying 通过指定
auth.jdbcAuthentication().dataSource(datasource);
Spring security checks for the user and authorities table and authenticates the user. Spring安全性检查用户和授权表并验证用户身份。
I want to override this default behaviour, as I do not have(do not need) an authentication table. 我想覆盖此默认行为,因为我没有(不需要)身份验证表。 Plus, my user table has a lot more columns than the standard three columns, namely username, password and enabled. 另外,我的用户表中的列比标准的三列(用户名,密码和已启用)多得多。
How do I override the default implementation? 如何覆盖默认实现?
Also, after the user has logged in, how do I get the information about the user? 另外,在用户登录后,如何获取有关该用户的信息?
Thanks! 谢谢!
You can either create a custom AuthenticationProvider
or use DaoAuthenticationProvider
with your custom UserDetailsService
implementation. 您可以创建自定义AuthenticationProvider
或将DaoAuthenticationProvider
与自定义UserDetailsService
实现一起使用。
Here is an example of Spring Java configuration class for the second solution: 这是第二种解决方案的Spring Java配置类示例:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
// ...
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setPasswordEncoder(new ShaPasswordEncoder());
authenticationProvider.setUserDetailsService(userService);
return authenticationProvider;
}
}
Your implementation of UserDetailsService
interface will contain the logic specific to the domain of your project for retrieving users by their username. 您的UserDetailsService
接口的实现将包含特定于您的项目域的逻辑,用于按用户名检索用户。
If you need more detailed examples, leave a comment below and I'll update the answer, but this should give you the general idea. 如果您需要更详细的示例,请在下面留下评论,我将更新答案,但这应该可以为您提供总体思路。
Also i recommend reading through JavaDocs of the aforementioned Spring classes and interfaces. 我也建议您通读上述Spring类和接口的JavaDocs。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.