手动身份验证抛出CustomAuthenticationProvider(Spring MVC)

时间:2015-08-04 04:35:59

标签: spring spring-mvc spring-security

我尝试使用Spring MVC手动登录用户名和密码

我有CustomSessionAuthenticationProvider:

  public class CustomSessionAuthenticationStrategy implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        User user = userService.loadUserByUsername(username);

        if (user == null) {
            throw new BadCredentialsException("Username not found.");
        }

        if (!password.equals(user.getPassword())) {
            throw new BadCredentialsException("Wrong password.");
        }

        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();

        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}

我将它包含在安全配置中:

 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

我不明白如何手动验证,如果我有控制器用户名和密码,并从中获取sessionId和令牌。

方法在输入需要身份验证时进行身份验证,但我需要登录和密码。

1 个答案:

答案 0 :(得分:0)

您不需要用于手动身份验证的控制器,Spring安全性会自动在/ login中为post方法注册控制器,并为您进行身份验证(如果已正确配置)。请查看此博客文章以获取示例或弹簧安全手册:http://kielczewski.eu/2014/12/spring-boot-security-application/