spring-boot - Spring Boot 基本身份验证

标签 spring-boot spring-security basic-authentication

我正在使用 Spring Boot Security 来帮助我进行身份验证...

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



@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .cors().and().csrf().disable().authorizeRequests()
        .anyRequest().authenticated().and().httpBasic();
    }
}

我有一个休息服务来进行登录(在我的 Controller 上),这是一个我发送电子邮件和密码的发布请求,我喜欢使用此服务来进行身份验证...

但是我是 spring-boot/java 的新手...有人可以帮助我以正确的方式实现这一点吗?

谢谢。

最佳答案

您需要(至少)允许访问登录端点。例如。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/login", "/error").permitAll()
            .antMatchers("/**").authenticated().and().exceptionHandling()
            .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
}

如果我是你,我也会删除 @EnableWebSecurity (并让 Spring Boot 完成它的工作)。然后在登录端点中,您需要设置安全上下文,例如

@PostMapping
public void authenticate(@RequestParam Map<String, String> map,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    Authentication result = authService.authenticate(map.get("username"), map.get("password"));
    SecurityContextHolder.getContext().setAuthentication(result);
    handler.onAuthenticationSuccess(request, response, result);
}

如果用户无法通过身份验证,authService 应抛出 BadCredentialsException。这是我曾经在博客中使用过的示例应用程序:https://github.com/dsyer/mustache-sample/blob/7be8459173d0b65b6d44d05f86e581d358ea9b2e/src/main/java/com/example/DemoApplication.java#L177

关于spring-boot - Spring Boot 基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46065063/

相关文章:

java - Hibernate Java - 无法反序列化/无效流头错误

java - 使用 Spring Boot 禁用 AppClassLoader AspectJ 日志记录

spring-security - 多个@EnableGlobalMethodSecurity 注解

java - 向 Spring MVC session 添加新属性

python - Flask 基本身份验证不接受用户名和密码

java - org.hibernate.Session 的 Save 方法未将数据保存在数据库中

java - 在关机时停止所有 Spring 批处理作业 (CTRL-C)

spring-security - Spring Security 使用通配符授权访问角色

rest - 基本 HTTP 和不记名 token 身份验证

Apache 2.4 如何仅对特定主机要求有效用户