带 Spring Boot 的 spring security

h43kikqp  于 2023-01-26  发布在  Spring
关注(0)|答案(4)|浏览(155)

我正在尝试创建Sping Boot REST应用程序。当我部署应用程序时,它需要身份验证,并且要求我输入用户名和密码。如何绕过此操作,或者如何添加用户名和密码进行身份验证?
我需要删除pom中的安全条目吗?

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

uurity8g1#

如果您根本不想使用身份验证,则应删除依赖项:

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

请参见 Spring Boot 参考指南:
如果SpringSecurity位于类路径上,那么默认情况下,Web应用程序将在所有HTTP端点上使用“基本”身份验证。

kjthegm6

kjthegm62#

不需要删除pom.xml的安全性。在您的项目中,您可以尝试以下操作。尝试创建SecurityConfig,它将扩展WebSecurityConfigurerAdapter,并提供一些用户名和密码,稍后您可以自定义它。

import org.springframework.context.annotation.Configuration;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user")
                    .password("user")
                    .roles("USER")
                    .and()
                .withUser("user2")
                    .password("secret2")
                    .roles("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().fullyAuthenticated();
        http
            .httpBasic();
        http
            .csrf().disable();
    }
}
public @interface EnableWebMvcSecurity {

}
vuktfyat

vuktfyat3#

除了其他两个答案-默认用户名是'user'和密码将打印在控制台每次启动您的服务器如下-

2019-08-31 23:58:16.417  INFO 12528 --- [  restartedMain] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: 1ab46edf-332a-42de-ae11-70dc138c65db

只需使用这些凭据即可登录。

注意-如果微调日志记录配置,请确保将org.springframework.boot.autoconfigure.security类别设置为记录INFO级别的消息。否则,不会打印默认口令。

pcww981p

pcww981p4#

如果要配置所选用户名/密码,则可以在application.properties文件中进行配置。
spring.security.user.name=用户名
spring.安全性.用户.密码=密码
现在spring security不会在每次 Boot 应用程序时生成新密码。
注意:使用 Postman 发送申请时,请进入授权〉选择“基本授权”〉输入用户名和密码,以便在每次申请沿着发送认证详情。如果使用浏览器,应该有一个登录页面。

相关问题