Как настроить UserDetailsService в весенней безопасности?

Я использую конфигурацию Java для настройки безопасности Spring, а также использую интерфейс UserDetailsService - проблема, из-за которой мне отказывают в доступе при попытке перейти к конкретному запросу.

вот код:

MainCofig.class

@Configuration
@ComponentScan("com.telephoenic.tca")
@Import({ WebMvcConfig.class, SecurityConfig.class})

public class MainConfig {

private static final String MESSAGE_SOURCE1 = "classpath:com/telephoenic/tca/languages/Labels";
private static final String MESSAGE_SOURCE2 = "classpath:com/telephoenic/tca/languages/Messages";

@Bean(name = "messageSource")
public MessageSource configureMessageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasenames(MESSAGE_SOURCE1, MESSAGE_SOURCE2);
    messageSource.setUseCodeAsDefaultMessage(true);
    messageSource.setDefaultEncoding("UTF-8");
    messageSource.setCacheSeconds(0);
    return messageSource;
}
}

SecurityConfig.class

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

JpaTransactionManager telephoenicTrxManger;

@Autowired
private BeanFactory  beanFactory;

@Autowired 
private UserDetailsService userDetailService;


@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    telephoenicTrxManger = (JpaTransactionManager)beanFactory.getBean("telephoenicTrxManger");
            auth.userDetailsService(userDetailService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/home").authenticated()
    .and().csrf().disable();

}



@Bean
public PasswordEncoder passwordEncoder() {
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    return encoder;
}

@Bean
public UserDetailsService userDetailService() {
    return new SecurityUserDetailService();
}   


}

Initializer.class

public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { MainConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

}

SecurityIitializer.class

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

}

SecurityUserDetailsService.class

@Service
@Transactional
public class SecurityUserDetailService implements UserDetailsService{

private UserService userService;

private static UserPrivilegeService userPrivilegeService;

public UserPrivilegeService getUserPrivilege() {
    return userPrivilegeService;
}

@Autowired
public void setUserPrivilege(UserPrivilegeService userPrivilegeService) {
    userPrivilegeService.setEntityClass(UserPrivilege.class);
    SecurityUserDetailService.userPrivilegeService = userPrivilegeService;
}

public UserService getUserService() {
    return userService;
}

@Autowired
public void setUserService(UserService userService) {
    userService.setEntityClass(User.class);
    this.userService = userService;
}


@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    try {
        User loggedInUser = userService.findByUserName(userName);
        List<GrantedAuthority> authorities = getAuthorities(loggedInUser);
        boolean enabled = loggedInUser.getStatus() == ApplicationConstant.ACTIVE ? true
                : (loggedInUser.getStatus() == ApplicationConstant.ACTIVE ? true
                        : false);
        boolean accountNonExpired = loggedInUser.getStatus() == ApplicationConstant.ACTIVE ? true
                : (loggedInUser.getStatus() == ApplicationConstant.ACTIVE ? true
                        : false);
        boolean credentialsNonExpired = loggedInUser.getStatus() == ApplicationConstant.ACTIVE ? true
                : (loggedInUser.getStatus() == ApplicationConstant.ACTIVE ? true
                        : false);
        boolean accountNonLocked = loggedInUser.getStatus() == ApplicationConstant.ACTIVE ? true
                : (loggedInUser.getStatus() == ApplicationConstant.ACTIVE ? true
                        : false);

        if (!enabled) {
            throw new AccessDeniedException("login.accessdenied.warnmsg");
        }

        if (authorities.size() == 0) {
            throw new AccessDeniedException(
                    "login.accessdenied.permissions.warnmsg");
        }

        return new org.springframework.security.core.userdetails.User(
                loggedInUser.getUsername(),
                loggedInUser.getPassword().toLowerCase(),
                enabled,
                accountNonExpired,
                credentialsNonExpired,
                accountNonLocked,
                authorities);
    } catch (Exception e) {
        throw new UsernameNotFoundException(
                "login.accessdenied.badcredentials.warnmsg");
    }
}

 private static List<GrantedAuthority> getAuthorities(User user) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        List<Function> functions = userPrivilegeService.findFunctionsByProfileId(user.getProfile().getId());
        for (Function function : functions) {
            authorities.add(new SimpleGrantedAuthority(function.getName()));
        }
        return authorities;
    }


    }

и когда я пытаюсь войти в систему, я получаю HTTP Status 403 - Доступ запрещен, хотя пользователь авторизован

1 ответ

В вашей конфигурации безопасности вы должны добавить это:

@Autowired
    private securityUserDetailService securityUserDetailService ;

@Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
    builder.userDetailsService(securityUserDetailService );
}
Другие вопросы по тегам