简体   繁体   English

如何配置 spring-boot-security 以使用登录页面对所有页面中的用户进行身份验证

[英]How to config spring-boot-security to authenticate the users in all pages with a login page

I have a basic spring boot application which shows a table of a database and allows you to do the basic CRUD operations using angular.我有一个基本的 spring 引导应用程序,它显示了一个数据库表,并允许您使用 angular 执行基本的 CRUD 操作。

My task is to make the app secured using spring-boot-security.我的任务是使用 spring-boot-security 使应用程序安全。 I've already implemented te following security config.我已经实现了以下安全配置。

    @Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {


    private final PasswordEncoder passwordEncoder;

    @Autowired
    public ApplicationSecurityConfig(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and
                ().httpBasic();

    }

    @Override
    @Bean
    protected UserDetailsService userDetailsService() {
         UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder.encode("password"))
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(
                user
        );

    }


}

It works fine, I can access the data with the given credentials using postman.它工作正常,我可以使用 postman 访问具有给定凭据的数据。

The problem occurs when I try to get the data using angular.当我尝试使用 angular 获取数据时出现问题。 I've already created a login component, which authenticates me, and it sends me the response I gave in the controller, which looks like this:我已经创建了一个登录组件,它对我进行身份验证,它会向我发送我在 controller 中给出的响应,如下所示:

@GetMapping("/")
@CrossOrigin(origins = "http://localhost:4200", allowedHeaders = "*")
public String login() {
    return "Authenticated successfully.";
}

The angular service I'm using is this:我正在使用的 angular 服务是这样的:

login(username: string, password:string) {
const headers = new HttpHeaders(
  {
       'Authorization':'Basic '+btoa((username +":"+ password))
  });
  return this._http.get("http://localhost:8080/", {headers, responseType:'text' as 'json'});

} }

In the login component, i have the following login function, which is called when the button is clicked:在登录组件中,我有以下登录 function,单击按钮时会调用它:

 doLogin() {
   let resp = this._service.login(this.username, this.password);
   resp.subscribe(data => {
     console.log(data);
     this._route.navigate(["/movieList"]);
   })   
  }

It gives me the Authenticated Successfully message, and redirects me to the movieList page, but I cant't access the datas, because it also gives me the following error:它给了我 Authenticated Successfully 消息,并将我重定向到 movieList 页面,但我无法访问数据,因为它也给了我以下错误: 在此处输入图像描述

What you are missing here is the usage of JWT token.您在这里缺少的是 JWT 令牌的使用。 The security workflow should be like these steps:安全工作流程应类似于以下步骤:

1- From Angular you send the user's credentials. 1- 从 Angular 您发送用户的凭据。

2- In Spring you verify theses credentials, you generate a JWT token and you send it back to angular. 2- 在 Spring 中验证这些凭据,生成 JWT 令牌并将其发送回 angular。

3- Angular saves the JWT in the local storage and uses it in the future request (as an athaurization param in XHR headers). 3- Angular 将 JWT 保存在本地存储中,并在将来的请求中使用它(作为 XHR 标头中的 athaurization 参数)。

So you should implement JWT service in Spring, Login service and an Interceptor in Angular.所以你应该在 Spring 中实现 JWT 服务,在 Angular 中实现登录服务和拦截器。

the following link explains well how to implement it: SPRING ANGULAR JWT TUTO以下链接很好地解释了如何实现它: SPRING ANGULAR JWT TUTO

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

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