Spring Boot - 显示OTP页面,限制使用其URL访问其他页面(在登录页面上成功验证后)

时间:2015-08-31 11:04:35

标签: spring spring-security spring-boot

我创建了一个Spring Boot Web应用程序,在成功登录后,我必须将用户发送到OTP页面。

我的问题是:当用户进入OTP页面时,他可以绕过它更改URL,这样他就可以访问任何页面(即很大的安全风险),因为用户已经从登录页面进行了身份验证。

如何在登录页面(使用Spring boot-security)上的OTP页面上重写URL更改,因此用户只有在通过OTP进行身份验证后才能进入。

2 个答案:

答案 0 :(得分:0)

一种常见的方法是,在成功进行身份验证后 - 即在登录屏幕上输入的凭据得到验证 - 用户可以有限地访问该应用程序。此受限访问仅允许访问OTP页面。一旦OTP得到验证,用户将获得他们有权获得的全套授权角色。

可以使用概述此方法的博客here

答案 1 :(得分:0)

创建AuthenticationSuccessHandler

如果用户需要一次性密码,请删除其权限,并为其提供一个新密码,例如ROLE_OTPROLE_OTP只能使用OTP网址,而不能使用其他任何内容。

public void onAuthenticationSuccess(
    HttpServletRequest request,  
    HttpServletResponse response, 
    Authentication sourceAuthentication
) throws IOException, ServletException {

    UserDetails sourceUser = (UserDetails) sourceAuthentication.getPrincipal();

    List<GrantedAuthority> targetAuthorities = new ArrayList<GrantedAuthority>( Arrays.asList( new SimpleGrantedAuthority("ROLE_OTP") ) );

    UserDetails targetUser = new User( sourceUser.getUsername() , "", targetAuthorities);

    UsernamePasswordAuthenticationToken targetAuthentication = new UsernamePasswordAuthenticationToken(targetUser, null, targetAuthorities);

    targetAuthentication.setDetails( sourceAuthentication.getDetails() );

    SecurityContextHolder.getContext().setAuthentication(targetAuthentication);

    response.sendRedirect("/otp-url");
}

如果他们通过OTP,请使用loadUserByUsername()重新加载他们的真实角色

Authentication sourceAuthentication = SecurityContextHolder.getContext().getAuthentication();

UserDetails sourceUser = (UserDetails) sourceAuthentication.getPrincipal();

UserDetails targetUser = userDetailsManager.loadUserByUsername(sourceUser.getUsername());

UsernamePasswordAuthenticationToken targetAuthentication = new UsernamePasswordAuthenticationToken(targetUser, null, targetUser.getAuthorities());

targetAuthentication.setDetails( sourceAuthentication.getDetails() );

SecurityContextHolder.getContext().setAuthentication(targetAuthentication);