首页 > 解决方案 > Spring Boot和http认证的简单应用

问题描述

我刚刚开始学习 Web 编程,并且正在尝试使用 Spring Boot 编写我的第一个应用程序,它为 HRM 系统提供了一个 RESTful API。但是我在 HTTP 身份验证方面遇到了困难。我尝试了很多指南,但他们没有帮助。

如果没有安全设置,RESTful API 可以工作,但是如果我为我的 API 包含安全性,我会得到代码 401。我该如何修复它?

链接到源代码

Screenshot_from_REST_client_1
Screenshot_from_REST_client_2
Screenshot_from_REST_client_3
Screenshot_from_REST_client_4

SpringSecurityConfig.java(无包和导入)

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AccessDeniedHandler accessDeniedHandler;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers().permitAll()
                .antMatchers("/**").hasAnyRole("USER")
            .anyRequest()
                .authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll()
                .and()
            .httpBasic()
                .and()
            .exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}


@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication()
            .withUser("user").password("password").roles("USER");
    }

}

PS 英语不是我的母语,所以请善待我的错误。我真的在努力提高我的英语。

标签: javaspring-bootspring-securityhttp-authentication

解决方案


推荐阅读