在Spring REST应用程序中成功验证后,为什么Principal为null?

问题描述 投票:0回答:1

我现在正在Spring rest应用程序中实现身份验证,所以我从Electron.js应用程序发送请求,Spring处理所有内容。

所以现在如果我通过浏览器登录它会保存我的对象并成功返回Principal。但是,如果我登录并尝试通过Electron.js应用程序发送返回该Principal的请求,则会抛出NullException。

@GetMapping("/user")
public String user(Principal principal)
{
    return principal.getName(); // null via rest app (electron app), not null via browser (authenticated)
}

@GetMapping("/loginRequest") // this is method that requires user's credentials
public UserModel login(Principal principal)
{
   return userDAO.findByUsername(principal.getName()); // signs in on both (browser and rest app), returns json object
}

配置看起来像这样:

    @Autowired
    private MongoUserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception
    {
        http.cors().and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/loginRequest").authenticated()
                .and()
                .httpBasic();
    }

    @Override
    public void configure(AuthenticationManagerBuilder builder) throws Exception
    {
        builder.userDetailsService(userDetailsService);
    }

    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

来自Electron.js的请求

axios(API + 'loginRequest', {
          method: 'GET',
          auth: {
            username: this.username, // Both username & pass are taken from fields
            password: this.password
          }
        })
        .then(response => {
          this.userObject = response.data;
        }).catch(err => this.showError('Username or password is invalid', 2));

先感谢您!

java spring spring-boot spring-security
1个回答
0
投票

我可以想到两个选择:

第一种选择:

将使用记住我为你提供弹簧,使用JSESSIONID cookie管理,在这里我给你一个教程,它解释得非常好,而且很简单:

https://www.baeldung.com/spring-security-remember-me

第二种选择:

正如您在评论中所说的那样使用OAuth2,但实现起来要贵一些,需要更多依赖项,让第三方验证令牌并且配置更长。

这是一个指南:

https://www.baeldung.com/rest-api-spring-oauth2-angular

© www.soinside.com 2019 - 2024. All rights reserved.