Spring Boot Sping Boot 基本身份验证

ih99xse1  于 2023-05-06  发布在  Spring
关注(0)|答案(3)|浏览(273)

我正在使用Sping Boot Security来帮助我进行身份验证...

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>


@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .cors().and().csrf().disable().authorizeRequests()
        .anyRequest().authenticated().and().httpBasic();
    }
}

我有一个休息服务,使登录(在我的控制器),这是一个职位的要求,我发送电子邮件和密码,我喜欢使用这个服务,使身份验证...
但我是spring-boot / java的新手。。有谁能帮我走这条正确的路吗?
谢谢

abithluo

abithluo1#

您需要允许访问登录端点(至少)。例如:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/login", "/error").permitAll()
            .antMatchers("/**").authenticated().and().exceptionHandling()
            .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
}

如果我是你,我也会删除@EnableWebSecurity(让Sping Boot 来完成它的工作)。然后在登录端点中,您需要设置安全上下文,例如

@PostMapping
public void authenticate(@RequestParam Map<String, String> map,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    Authentication result = authService.authenticate(map.get("username"), map.get("password"));
    SecurityContextHolder.getContext().setAuthentication(result);
    handler.onAuthenticationSuccess(request, response, result);
}

如果用户不能通过身份验证,authService应该抛出BadCredentialsException。以下是我在博客中使用过的示例应用程序:https://github.com/dsyer/mustache-sample/blob/7be8459173d0b65b6d44d05f86e581d358ea9b2e/src/main/java/com/example/DemoApplication.java#L177

nsc4cvqm

nsc4cvqm2#

在www.example.com中修改add方法SpringSecurityConfig.java,如下所示

@Configuration
    @EnableWebSecurity
    public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserAuthenticationService userAuthenticationService;

    @Autowired
    private CustomAuthenticationProvider authenticationProvider;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(this.authenticationProvider).userDetailsService(this.userAuthenticationService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .cors().and().csrf().disable().authorizeRequests()
        .anyRequest().authenticated().and().httpBasic();
    }}

创建CustomAuthenticationProvider。

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserAuthenticationService userAuthenticationService;

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String emailId = authentication.getName();
        String password = (String) authentication.getCredentials();
        UserDetails user = this.userAuthenticationService.loadUserByUsername(emailId);
        if (user == null) {
            throw new UsernameNotFoundException("Username not found.");
        }
        //Your password encoder here
        if (!password.equals(user.getPassword())) {
            throw new UsernameNotFoundException("Wrong password.");
        }
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }}

创建自定义UserService

@Service
public class UserAuthenticationService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userRepository.findByEmailAddressWithRole(email);
        if (user == null) {
            throw new UsernameNotFoundException("Username not found for " + email);
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        for (Role roles : user.getRoles()) {
            grantedAuthorities.add(new SimpleGrantedAuthority(roles.getRoleName()));
        }
        return new UserAuthenticationWrapperDto(user.getId(), user.getEmailAddress(), user.getPassword(),
                user.getUserType(), user.getCompany().getId(), grantedAuthorities,user.getName());
    }}
1cosmwyk

1cosmwyk3#

WebSecurityConfigurerAdaptor现在已弃用。
使用Spring Security 6和Sping Boot 3,我实现了如下基本身份验证:

@Configuration
@EnableWebSecurity
public class Config {
    

    @Autowired private MyBasicAuthenticationEntryPoint authenticationEntryPoint;

    @Bean
    UserDetailsService uds(PasswordEncoder pe) {
        UserDetails user1 = User.withUsername("mohit")
                .password(pe.encode("m123"))
                .authorities("USER")
                .build();
        UserDetails user2 = User.withUsername("john").password(pe.encode("m123")).authorities("USER").build();
        return new InMemoryUserDetailsManager(user1,user2);
    }
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
        .authorizeHttpRequests()
            .requestMatchers("/securityNone")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .authenticationEntryPoint(authenticationEntryPoint);
        
        //http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
        return http.build();
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
}

MyAuthenticationEntryPoint如下所示:

@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) 
      throws IOException {
        response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() );
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 - " + authEx.getMessage());
    }

    @Override
    public void afterPropertiesSet() {
        setRealmName("MyApplication");
        super.afterPropertiesSet();
    }
}

相关问题