Check extra parameters with Spring Security

白昼怎懂夜的黑 提交于 2020-01-11 11:45:06

问题



Please give a hint in Spring Security, how can I check additional parameters during user login.
For example, to check not only "username" and "password", but also if he confirmed his registration with email link;
All data is stored in DB and i can get it easily with my implementation of UserDetailsService;
But how to make the security service to pay attention to the additional parameter "isValidated"?
I'm using Spring 3.2.0 now;


回答1:


One way to achieve this is to create a custom AuthenticationProvider or to extend an existing one. In your case it might be sufficient to extend for instance the DaoAuthenticationProvider and put the logic for checking whether the account is confirmed in additionalAuthenticationChecks() method.

Here is an example:

public class CustomAuthenticationProvider extends DaoAuthenticationProvider {

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        // Perform the checks from the super class
        super.additionalAuthenticationChecks(userDetails, authentication);

        // Cast the UserDetails to the implementation you use
        User user = (User) userDetails;

        // Check the confirmed status
        if (!user.isAccountConfirmed()) {
            throw new AccountNotConfirmedException("Account is not confirmed yet.");
        }
    }

    public static class AccountNotConfirmedException extends AuthenticationException {
        public AccountNotConfirmedException(String message) {
            super(message);
        }
    }

}

Your implementation of UserDetails should contain the information about account confirmation status. You can map this information in your implementation of UserDetailsService.

Option 2

Edit: Now that I look at it, the first solution is a bit overcomplicated. You can easily solve this problem without using custom AuthenticationProvider. Just make sure that isEnabled() of your UserDetails implementation returns false if the account is not confirmed. If the enabled property is false authentication will not be allowed (this is automatically taken care of by Spring Security).

The first solution might still be useful if you want explicitly handle the AccountNotConfirmedException in AuthenticationFailureHandler for instance.



来源:https://stackoverflow.com/questions/27658030/check-extra-parameters-with-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!