403禁止页面Spring Security

wmvff8tz  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(192)

我似乎找不到403错误问题,当我发送一个json请求在postman中注册时,我得到了403禁止错误,没有消息。 Postman 截图
secureconfig.java
这是配置文件。

@EnableWebSecurity
@AllArgsConstructor
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsService userDetailsService;

    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/api/auth/**")
                .permitAll()
                .anyRequest()
                .authenticated();

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

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

authconroller
这是要验证的项目的控制器,当我注册新用户成功添加到数据库时,它随后使用mailtrap向假邮件发送邮件验证”https://mailtrap.io " . 但是当我请求接收身份验证令牌和用户名时,我收到了错误。

@RestController
@AllArgsConstructor
@RequestMapping(value = "/api/auth", consumes = MediaType.APPLICATION_JSON_VALUE)
public class AuthController {

    private final AuthService authService;

    @PostMapping("/signup")
    public ResponseEntity<String> signup(@RequestBody RegisterRequest registerRequest ) {
        authService.signup(registerRequest);
        return new ResponseEntity<>("User's Registration was successful", HttpStatus.OK);

    }

    @GetMapping("accountVerification/{token}")
    public ResponseEntity<String> verifyAccount(@PathVariable String token){
        authService.verifyAccount(token);
        return new ResponseEntity<>("Account created successfully", HttpStatus.OK);
    }

    @PostMapping("/")
    public String login(@RequestBody LoginRequest loginRequest){
        return authService.login(loginRequest);

    }

}

授权服务
这是自动认证服务。

@Service
@AllArgsConstructor
public class AuthService {

    private final PasswordEncoder passwordEncoder;
    private final UserRepository userRepository;
    private final VerificationTokenRepository verificationTokenRepository;
    private final MailService mailService;
    private final AuthenticationManager authenticationManager;
    private final JwtProvider jwtProvider;

    public void signup(RegisterRequest registerRequest){
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setEmail(registerRequest.getEmail());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setEnabled(false);
        user.setCreated(Instant.now());
        userRepository.save(user);

        String token = generetedVerificationToken(user);
        mailService.sendMail(new NotificationEmail("Please " +
                "Activate Your Account", user.getEmail(), "Thanks " +
                "for signing up. Click on the link below to go home: " +
                "http://localhost:8080/api/auth/accountVerification/" + token));
    }
    private String generetedVerificationToken(User user){
        String token = UUID.randomUUID().toString();
        VerificationToken verificationToken = new VerificationToken();
        verificationToken.setToken(token);
        verificationToken.setUser(user);

        verificationTokenRepository.save(verificationToken);
        return token;

    }

    public void verifyAccount(String token) {
        Optional<VerificationToken> verificationToken = verificationTokenRepository.findByToken(token);
        fetchUserAndEnable(verificationToken.orElseThrow(() -> new SpringRedditException("Invalid Token")));

    }

    private void fetchUserAndEnable(VerificationToken verificationToken){
        String username = verificationToken.getUser().getUsername();
        Optional<org.springframework.security.core.userdetails.User> v = userRepository.findByUsername(username);
        UserDetails user = userRepository.findByUsername(username).orElseThrow(() -> new SpringRedditException("User not found with name - " + username));
        User s = (User) user;
        s.setEnabled(true);
        userRepository.save(s);

    }

    public String encodePassword(String password) { return passwordEncoder.encode(password);}

    public String login(LoginRequest loginRequest){
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                loginRequest.getUsername(),
                loginRequest.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return jwtProvider.generatedToken(authentication);
    }
}

jwtprovider
此类用于为每个用户生成令牌。我没有使用我在教程中找到的jks,因为它提供了一个错误。

@Service
public class JwtProvider {

//    private KeyStore keyStore;
    private Key key;
    @PostConstruct
    public void init() {
        key = Keys.secretKeyFor(SignatureAlgorithm.HS512);
    }
        public String generatedToken(Authentication authentication){
            org.springframework.security.core.userdetails.User principal =
                    (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
            return Jwts.builder()
                    .setSubject(principal.getUsername())
                    .signWith(key)
                    .compact();
        }
}

userdetailsserviceimpl
下面是授予用户连接权限的实现:

@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username)  {
        Optional<User> userOptional = userRepository.findByUsername(username);
        User user = userOptional.orElseThrow(() -> new UsernameNotFoundException("No such user" +
                "with username : " + username));
        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(), user.isEnabled(), true,
                true, true,
                getAuthorities("USER"));
    }

    private Collection<? extends GrantedAuthority> getAuthorities(String role){
        return singletonList(new SimpleGrantedAuthority(role));
    }
}

最后
授权响应
在dto文件中,我们有这个类,以便以json格式接收postman中的AuthenticateToken和用户名。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthenticationResponse {
    private String authenticationToken;
    private String username;
}

添加后 logging.level.org.springframework.security=DEBUGapplication.properties 文件,我设法在下图中看到了出现此错误的原因。
调试结果屏幕截图

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题