使用Java配置进行n因子身份验证
问题内容:
在使用 spring security* 的 spring mvc 应用程序中,我想使用自定义来检查除默认值和之外的 n个
其他字段。我正在尝试使用Java配置。我应该如何设置? AuthenticationProvider
***username``password
问题答案:
使用java config进行n因子身份验证的最简单方法是从使用Java
config的单因子身份验证(用户名和密码)的工作示例开始。然后,您只需要进行一些非常小的更改:假设您具有使用Java配置的可运行的单因素身份验证应用程序,则步骤很简单:
首先,定义分层角色,每个因素一个角色。如果只有两要素身份验证,请在数据库中保留现有的一个角色,然后创建仅在运行时分配的具有完全访问权限的第二个角色。因此,当用户登录时,他们将登录到存储在数据库中的最小角色,并且仅向该最小角色授予对一个视图的访问权限,该视图是一种形式,允许他们输入您的控制器刚刚发送给他们的PIN码。通过文本或电子邮件或其他方法。这些分层角色在中定义SecurityConfig.java
,如下所示:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/getpin")
.usernameParameter("j_username")
.passwordParameter("j_password")
.loginProcessingUrl("/j_spring_security_check")
.failureUrl("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.and()
.authorizeRequests()
.antMatchers("/getpin").hasAuthority("get_pin")
.antMatchers("/securemain/**").hasAuthority("full_access")
.antMatchers("/j_spring_security_check").permitAll()
.and()
.userDetailsService(userDetailsService);
}
}
其次,添加代码,以在将正确的密码成功输入到处理密码输入表单的控制器代码后,将用户的角色升级为完全访问权限POST
。在控制器中手动分配完全访问权限的代码为:
Role rl2 = new Role();rl2.setRole("full-access");//Don't save this one because we will manually assign it on login.
Set<Role> rls = new HashSet<Role>();
rls.add(rl2);
CustomUserDetailsService user = new CustomUserDetailsService(appService);
Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities(rls));
SecurityContextHolder.getContext().setAuthentication(authentication);
return "redirect:/securemain";
之后,您可以添加任意多个图层/getpin
。您还可以支持多个授权角色,并使其变得更复杂。但这答案给出了使它与java config一起运行的最简单方法。