繁体   English   中英

在 Spring Boot JPA 中使用 spring 安全 BCrypt 时出现 401 未授权

[英]401 unauthorized when using spring security BCrypt in Spring Boot JPA

我正在尝试对 hash 密码实施Bcrypt 但我面临的问题是 Spring Security 默认启用所有端点的身份验证。 但我不希望我只想注册一个用户并简单地为密码生成 hash。 但我不能这样做,因为当我从 Postman 发出Post请求时,它显示401 Unauthorized .4

我在主 class 中尝试了以下操作:

1-

@EnableWebSecurity

2-

@EnableAutoConfiguration

3-

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

4-

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors(); 
        return http.build();
    }

5-

我尝试使用org.mindrot:jbcrypt:0.4但是当我尝试在我的服务 function 中使用BCrypt时,它不会从mindrot导入它

我想在以后使用 spring 安全性进行身份验证和授权,但首先我需要注册一个用户和 hash 他的密码。

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.0.1'
    id 'io.spring.dependency-management' version '1.1.0'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '19'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.mysql:mysql-connector-j'
    annotationProcessor 'org.projectlombok:lombok'
    implementation 'org.mindrot:jbcrypt:0.4'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

主 class

package com.example.bcrypt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class BcryptApplication {

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

}

用户回购

package com.example.bcrypt.repository.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.bcrypt.entity.User;

public interface UserRepository extends JpaRepository<User,Integer>{
    
}

用户服务

package com.example.bcrypt.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.example.bcrypt.entity.User;
import com.example.bcrypt.repository.dao.UserRepository;


@Service
public class UserService {
    @Autowired
    private UserRepository userRepo;

    public User create(User body){

        BCryptPasswordEncoder bcrypt=new BCryptPasswordEncoder();

        String hashedpassword=bcrypt.encode(body.getPassword());

        body.setPassword(hashedpassword);

        User res=userRepo.save(body);

        System.out.println(res);

        return res;
    }
    
}

用户控制器

package com.example.bcrypt.controller;

import org.springframework.beans.factory.annotation.Autowired;
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 com.example.bcrypt.entity.User;
import com.example.bcrypt.service.UserService;

@RestController()
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public User create(@RequestBody User body){
        User res=userService.create(body);

        System.out.println(res);

        return res;
    }
}

由于 spring 安全性,您的请求失败。 您可以通过提供一个简单的@Bean添加异常或完全禁用它。

@Bean
public SecurityWebFilterChain securityFilterChain(ServerHttpSecurity http) {
  return http
    .csrf()
    .disable()
    .authorizeExchange(authorizeExchangeSpec -> authorizeExchangeSpec.anyExchange().permitAll())
    .build();
}

我从你的代码中可以看出你正在调用什么端点,所以在上面的例子中我允许了任何请求。 请注意,您不应在生产环境中这样做。

编辑:

对不起,我给了你一个用于 webflux 的 bean。

您应该能够改用这个 bean 并使其全部正常工作。 我通常创建一个配置 class ex:

安全配置.java

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.cors().disable()
                .csrf().disable()
                .authorizeHttpRequests().requestMatchers("/users/register").permitAll().and()
                .build();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM