我正在使用 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/