Custom Authentication Manager with Spring Security and Java Configuration

前端 未结 4 1317
渐次进展
渐次进展 2020-12-01 01:31

I am using Spring Security with SpringMVC to create a web application (I will refer to this as the WebApp for clarity) that speaks to an existing application (I will refer t

4条回答
  •  孤街浪徒
    2020-12-01 01:58

    Take a look at my sample below. You have to return an UsernamePasswordAuthenticationToken. It contains the principal and the GrantedAuthorities. Hope I could help :)

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getPrincipal() + "";
        String password = authentication.getCredentials() + "";
    
        User user = userRepo.findOne(username);
        if (user == null) {
            throw new BadCredentialsException("1000");
        }
        if (!encoder.matches(password, user.getPassword())) {
            throw new BadCredentialsException("1000");
        }
        if (user.isDisabled()) {
            throw new DisabledException("1001");
        }
        List userRights = rightRepo.getUserRights(username);
        return new UsernamePasswordAuthenticationToken(username, null, userRights.stream().map(x -> new SimpleGrantedAuthority(x.getName())).collect(Collectors.toList()));
    }
    

    PS: userRepo and rightRepo are Spring-Data-JPA Repositories which access my custom User-DB

    SpringSecurity JavaConfig:

    @Configuration
    @EnableWebMvcSecurity
    public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
    
    public MySecurityConfiguration() {
        super(false);
    }
    
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return new ProviderManager(Arrays.asList((AuthenticationProvider) new AuthProvider()));
    }
    
    }
    

提交回复
热议问题