当前位置: 首页 > 知识库问答 >
问题:

Spring Security 401 with Postman的注册问题

苍恩
2023-03-14

当我尝试注册一个新用户并在邮递员中测试时,我在Spring安全方面遇到了问题,它总是给我一个401未经授权的响应。

我检查了所有的过滤器,控制,服务仓库和一切,我已经检查了这里的所有问题,甚至在谷歌上搜索了很多,但没有答案,我希望有人有答案。

这是下面的代码:

这是安全配置:

package app.gym.v1.Utility.Config;

import app.gym.v1.Utility.Filter.JwtAccessDeniedHandler;
import app.gym.v1.Utility.Filter.JwtAuthenticationEntryPoint;
import app.gym.v1.Utility.Filter.JwtAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import static app.gym.v1.Utility.Constant.SecurityConstant.*;
import static org.springframework.security.config.http.SessionCreationPolicy.*;

public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private JwtAuthorizationFilter jwtAuthorizationFilter;
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    private UserDetailsService userDetailsService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    public SecurityConfig(
            JwtAuthorizationFilter jwtAuthorizationFilter,
            JwtAccessDeniedHandler jwtAccessDeniedHandler,
            JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint,
            @Qualifier("userDetailsService")UserDetailsService userDetailsService,
            BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.jwtAuthorizationFilter = jwtAuthorizationFilter;
        this.jwtAccessDeniedHandler = jwtAccessDeniedHandler;
        this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().and()
                .sessionManagement().sessionCreationPolicy(STATELESS)
                .and().authorizeRequests().antMatchers(PUBLIC_URLS).permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().accessDeniedHandler(jwtAccessDeniedHandler)
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and()
                .addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
    }

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

这是资源代码:

package app.gym.v1.Resource;

import app.gym.v1.Model.User;
import app.gym.v1.Service.UserService;
import app.gym.v1.Utility.Exception.Domain.*;
import app.gym.v1.Utility.Exception.ExceptionHandling;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

import static org.springframework.http.HttpStatus.OK;

@RestController
@RequestMapping(path = {"/","/user"})
public class UserControl extends ExceptionHandling {
    private UserService userService;

    @Autowired
    public UserControl(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public ResponseEntity<User> register(@RequestBody User user) throws UserNotFoundException, UsernameExistException, EmailExistException, IOException {
        User newUser = userService.register(user.getUsername(), user.getEmail(), user.getPassword(), user.getRole());
        return new ResponseEntity<>(newUser,  OK);
    }
}

这是用户实现服务:

package app.gym.v1.Utility.Impl;

import app.gym.v1.Model.User;
import app.gym.v1.Model.UserPrincipal;
import app.gym.v1.Repo.UserRepo;
import app.gym.v1.Service.UserService;
import app.gym.v1.Utility.Exception.Domain.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.transaction.Transactional;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import static app.gym.v1.Utility.Constant.UserImplConstant.*;
import static app.gym.v1.Utility.Enums.Role.*;
import static org.apache.commons.lang3.StringUtils.*;

@Service
@Transactional
@Qualifier("UserDetailsService")
public class UserServiceImpl implements UserService, UserDetailsService {
    private Logger LOGGER = LoggerFactory.getLogger(getClass());
    private UserRepo userRepo;
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserRepo userRepo, BCryptPasswordEncoder passwordEncoder) {
        this.userRepo = userRepo;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepo.findUserByUsername(username);
        if (user == null) {
            LOGGER.error("User with this phone number does not exist: " + username);
            throw new UsernameNotFoundException("User with this phone number does not exist: " + username);
        }else {
            user.setLastLoginDateDisplay(user.getLastLoginDate());
            user.setLastLoginDate(new Date());
            userRepo.save(user);
            UserPrincipal userPrincipal = new UserPrincipal(user);
            LOGGER.info("Retrieving user with this phone number" + username);
            return userPrincipal;
        }
    }

    @Override
    public User register(String username, String email, String password, String role) throws UserNotFoundException, UsernameExistException, EmailExistException {
        validateNewUsernameAndEmail(EMPTY, username, email);
        User user = new User();
        user.setUserId(generateUserId());
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(encodePassword(password));
        user.setRole(USER.name());
        user.setAuthorities(USER.getAuthorities());
        user.setJoinDate(new Date());
        user.setActive(true);
        user.setNotLocked(true);
        userRepo.save(user);
        return user;
    }

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

    private String generateUserId() {
        return RandomStringUtils.randomNumeric(20);
    }


    private String generatePassword() {
        return RandomStringUtils.randomAlphanumeric(20);
    }

    private User validateNewUsernameAndEmail(String currentUsername, String newUsername, String newEmail) throws UserNotFoundException, UsernameExistException, EmailExistException {
        User userByNewUsername = findUserByUsername(newUsername);
        User userByNewEmail = findUserByEmail(newEmail);
        if(isNotBlank(currentUsername)) {
            User currentUser = findUserByUsername(currentUsername);
            if(currentUser == null) {
                throw new UserNotFoundException(NO_USER_FOUND_BY_USERNAME + currentUsername);
            }
            if(userByNewUsername != null && !currentUser.getId().equals(userByNewUsername.getId())) {
                throw new UsernameExistException(USERNAME_ALREADY_EXISTS);
            }
            if(userByNewEmail != null && !currentUser.getId().equals(userByNewEmail.getId())) {
                throw new EmailExistException(EMAIL_ALREADY_EXISTS);
            }
            return currentUser;
        } else {
            if(userByNewUsername != null) {
                throw new UsernameExistException(USERNAME_ALREADY_EXISTS);
            }
            if(userByNewEmail != null) {
                throw new EmailExistException(EMAIL_ALREADY_EXISTS);
            }
            return null;
        }
    }
}

问题在于注册我的路由是(本地主机:8080/用户/注册)或(本地主机:8080/注册)。

我为他们放了一个常量来制作一个公共URL。

共有1个答案

微生曾琪
2023-03-14

您需要使用@配置注释您的SecurityConfig类,否则它不会被拾取。

如果您没有正确设置自定义安全配置,应用程序将使用默认的 Spring 引导自动配置,该配置会限制对所有endpoint的访问。

 类似资料:
  • 注册与访问 打开后台-会员-注册与访问 1.注册类型:普通注册/邮箱注册/手机注册 如开启邮箱和手机注册,请在通知系统功能中进行邮箱与短信通知配置,游客在注册时通过验证后方能注册成功 2.后台验证码是否开启:开启后显示 商城验证码是否开启:开启后显示 3.是否允许注册会员:设置为不允许则游客无法注册成为站点会员 4.错误多次后显示:配置该项后,开启验证码后验证码默认不显示,在登录错误次数达到设置值

  • 问题内容: 我已经使用GCM很长时间了。有一天,它突然破裂了。问题是我发送的第一个推送获得了成功状态,但该应用程序未收到任何推送。我发送的第二次推送失败,并显示NotRegistered错误。我重新安装该应用程序:成功(未收到通知),失败(未注册)->循环。我不知道发生了什么变化。Google支持非常无助,需要花费大量时间来回答简单的问题,无论是GCM问题,APNs问题还是客户问题。如果以前有人遇

  • 我正在尝试使用以下命令公开docker注册表: 来源:https://docs . open shift . com/container-platform/3.3/install _ config/registry/securing _ and _ exposure _ registry . html # access-unsecured-registry-by-exposure-route 但是

  • Q:如何注册? A:您可以点击右上角注册按钮,通过填写手机号码,获取验证码,填写验证码后注册爱客服,注册后您可以使用手机号码+密码登录爱客服,体验全新的智能客服系统,我们为您提供7天免费试用时间,您可以在系统中体验完整的各项各项功能。如需其他帮助请联系 400 005 0025。 Q:为什么我的账号无法登录爱客服? A:您可以使用您的注册手机号登录爱客服系统,请检查您的账号或者密码是否正确,网络可

  • 我正在尝试将一个图像推送到我的docker私有存储库: Docker告诉我: push引用存储库[living-registry.com:5000/busybox]Get https://living-registry.com:5000/v1/_ping:read tcp 195.83.122.16:39714->195.83.122.16:5000:read:对等体重置连接 这些命令正在Core

  • POST /users 输入 名称 类型 描述 name 字符串 必须,用户名 phone 字符串 如果 verifiable_type 为 sms 则必须, 手机号码。 email String 如果 verifiable_type 为 mail 则必须, E-Mail。 password String 可选,密码,如果不输入密码,允许用户无密码注册。 verifiable_type 枚举: