java身份验证_使用Java配置进行n因子身份验证

小编典典

使用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 rls = new HashSet();

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一起运行的最简单方法。

2020-06-01

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值