Spring Security的授权

问题描述 投票:0回答:1

当我输入已注册并输入数据库的正确数据时,Spring Security 写入数据不正确

谁可以帮忙,我用的是spring security 6,我刚开始学习,从数据库输入数据时,我写用户名和密码不正确

我不知道为什么它不起作用。感谢您的帮助!

在此输入图片描述

Web安全配置

package com.example.function_module.config;

import com.example.function_module.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class WebSecurityConfig{


    @Autowired
    private UserServiceImpl userService;


    @Autowired
    private CustomAuthenticationProvider authProvider;

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


    @Autowired
    public WebSecurityConfig(UserServiceImpl userService) {
        this.userService = userService;
    }

    @Bean
    public AuthenticationManager authManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder =
                http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.authenticationProvider(authProvider);
        return authenticationManagerBuilder.build();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws  Exception{
        return http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(auth ->
                        auth.requestMatchers("/registration", "/css/**")
                                .permitAll()
                        .requestMatchers("/api/all").authenticated())
                .formLogin((form) -> form
                        .loginPage("/login")
                        .loginProcessingUrl("/login")
                        .permitAll())
                .build();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
        auth.setUserDetailsService(userService);
        auth.setPasswordEncoder(passwordEncoder());
        return auth;
    }
}

package com.example.function_module.config;


import com.example.function_module.entity.User;
import com.example.function_module.service.UserService;
import com.example.function_module.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import javax.naming.AuthenticationException;
import java.util.ArrayList;
import java.util.List;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserServiceImpl userService;

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

        User user = userService.findByLogin(username);

        if (user == null || !password.equals(user.getPassword())) {
            throw new BadCredentialsException("Invalid username or password");
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return new UsernamePasswordAuthenticationToken(username, password, authorities);
    }


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

用户服务实现

package com.example.function_module.service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import com.example.function_module.dto.UserRegisterDto;
import com.example.function_module.entity.Role;
import com.example.function_module.entity.User;
import com.example.function_module.repository.RoleRepository;
import com.example.function_module.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepo;
    private final RoleRepository roleRepo;

    private final PasswordEncoder passwordEncoder;
    @Autowired
    public UserServiceImpl(UserRepository userRepo,
                           RoleRepository roleRepo,
                           PasswordEncoder passwordEncoder) {
        this.userRepo = userRepo;
        this.roleRepo = roleRepo;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        User user = userRepo.findByLogin(login);
        if (user == null){
            throw new UsernameNotFoundException("Invalid");
        }

        return new org.springframework.security.core.userdetails.User(
                user.getLogin(),
                user.getPassword(),
                mapRolesToAuthorities(user.getRoles())
        );
    }

    public List<User> allUsers() {
        return userRepo.findAll();
    }

    @Override
    public void save(UserRegisterDto userRegDto) {
        User user = new User();
        user.setNickname(userRegDto.getNickname());
        user.setLogin(userRegDto.getLogin());
        user.setPassword(passwordEncoder.encode(userRegDto.getPassword()));
        Role role= roleRepo.findByName("ROLE_USER");
        user.setRoles(Arrays.asList(role));
        userRepo.save(user);
    }
    private Collection < ? extends GrantedAuthority > mapRolesToAuthorities(Collection < Role > roles) {
        return roles.stream().map(role-> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
    }


}

登录.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/springsecurity6">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" th:href="@{/css/registration.css}">
    <title>Вход</title>
</head>
<body>

    <form method="post" th:action="@{/login}">
    <div class="container">
        <h1>Authorization</h1>
        <div th:if="${param.error}" class="error">
            Invalid username or password.
        </div>
        <!-- logout message -->
        <div th:if="${param.logout}">
            You have been logged out.
        </div>

        <label for="login"><b>Login</b></label>
        <input
                type="text"
                placeholder="Enter login"
                class = "form-control"
                name="login"
                id="login"
        />

        <label for="password"><b>Password</b></label>
        <input
                type="password"
                placeholder="Enter Password"
                class = "form-control"
                name="password"
                id="password"
        />

        <!-- submit button -->
        <button type="submit" value="Log in">Sign in</button>
        <div class="form-group">
                    <span>New user? <a href="/" th:href="@{/registration}">
                Register
                  here</a></span>
        </div>

    </div>
</form>

</body>
</html>


spring spring-boot spring-mvc spring-data-jpa
1个回答
0
投票

在身份验证方法中,您应该使用 BCryptPasswordEncoder 来验证密码匹配。但是您使用的是简单的字符串比较。 示例:

if (user == null || !password.equals(user.getPassword())) {
throw new BadCredentialsException("Invalid username or password");

}

尝试一下,如果这可以解决您的问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.