【问题标题】:I am trying to implement spring security ive configured everything but still not working我正在尝试实施 spring security 我配置了所有内容但仍然无法正常工作
【发布时间】:2021-12-27 06:46:27
【问题描述】:

spring security 不使用数据库中的详细信息进行身份验证并在控制台中生成密码也不使用我自定义的登录表单。

主类--

package mis.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@ComponentScan({"mis.controller", "mis.services"})
@EntityScan("mis.entity")
@EnableJpaRepositories("mis.dao")
public class BitmisApplication {

    public static void main(String[] args) {
        SpringApplication.run(BitmisApplication.class, args);
    }

}

CustomUserDetails--

package mis.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import mis.entity.Roles;
import mis.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;


public class CustomUserDetails implements UserDetails {
    
    private User user;
    
    public CustomUserDetails(User user) {
        this.user = user;
    }
 
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<Roles> roles = user.getRoles();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
         
        for (Roles role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
         
        return authorities;
    }
 
    @Override
    public String getPassword() {
        return user.getPassword();
    }
 
    @Override
    public String getUsername() {
        return user.getUsername();
    }
 
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
 
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
 
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
 
    @Override
    public boolean isEnabled() {
        return user.isEnabled();
    }
    
}

MyConfig 类--

package mis.config;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;



@Configuration
@EnableAutoConfiguration
@EnableWebSecurity
public class MyConfig extends WebSecurityConfigurerAdapter {
    
    
    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }
     
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
     
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder());
         
        return authProvider;
    }
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/").hasAnyAuthority("USER", "CREATOR", "EDITOR", "ADMIN")
            .antMatchers("/new").hasAnyAuthority("ADMIN", "CREATOR")
            .antMatchers("/admin/**").hasAnyAuthority("ADMIN", "EDITOR")
            .antMatchers("/delete/**").hasAuthority("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout().permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/403")
            ;
    }
}

UserDetailsS​​erviceImpl--

package mis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import mis.entity.User;
import mis.dao.UserRepository;

public class UserDetailsServiceImpl implements UserDetailsService {
    
        @Autowired
        private UserRepository userRepository;
         
        @Override
        public UserDetails loadUserByUsername(String username)
                throws UsernameNotFoundException {
            User user = userRepository.getUserByUsername(username);
          
            if (user == null) {
                throw new UsernameNotFoundException("Could not find user");
            }
             
            return new CustomUserDetails(user);
        }

}

用户存储库--

" 包mis.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import mis.entity.User;

public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.username = :username")
    public User getUserByUsername(@Param("username") String username);
}"

我认为 springboot 无法读取此身份验证文件

【问题讨论】:

  • 你试过设置@ComponentScan({"mis"})吗?
  • 由于你的包结构,东西没有被拾取。不要将您的BitmisApplication 放在mis.main 中,而是将其移至mis。抛弃除@SpringBootApplication 之外的所有注释,一切都会正常工作。
  • 是的,我试过但没用
  • 请不要只发布您的代码并用一句话解释它不起作用。您的日志、重现步骤、您的请求、缺少调试详细信息、被否决并投票关闭。

标签: java spring-boot spring-mvc authentication spring-security


【解决方案1】:

spring 应用程序找不到您的配置,因为您的项目结构有问题并且您添加了错误的自定义配置。

@SpringBootApplication 类将默认扫描它在mis.main 中的包以及该包下的所有包(mis.main...* 等),以查找所有带有 spring 注释的包类并加载它们。

您已将配置文件放在mis.config 中,该文件不在mis.main 的正下方,并且您在mis.entity 中的文件也不在mis.main 的下方。

你也加了

@ComponentScan({"mis.controller", "mis.services"})
@EntityScan("mis.entity")

为了尝试查找配置文件但未能将mis.config指定为要扫描的文件夹。

最简单的解决办法是

  • 删除我上面提到的两个注释。
  • 将主类移入包mis,然后删除包mis.main,使主类位于项目根目录。

其他一些事情:

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService());
    authProvider.setPasswordEncoder(passwordEncoder());
         
    return authProvider;
}
 
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider());
}

不需要并且可以删除,因为您已经将自定义UserDetailsServicePasswordEncoder 声明为bean,它们将被系统自动拾取并包含到spring 中,它会自动为您设置DaoAuthentication。

如果你正在学习,你应该阅读 spring 安全参考文档,所有这些都是在那里提到的。

【讨论】:

  • 感谢它为我工作
猜你喜欢
  • 2023-01-25
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2022-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
相关资源
最近更新 更多