Участник безопасности Spring, возвращающий null на сервере аутентификации - PullRequest
0 голосов
/ 09 июля 2020

Я изучаю, как использовать фреймворк Spring, и для этого у меня есть чрезвычайно простой однопользовательский сервер аутентификации как часть процесса обучения. Пока я могу получить токен доступа без проблем, как только я отправлю токен тому, что станет userinfouri сервера ресурсов, я всегда получаю пустой вывод, дальнейшие исследования показывают, что возвращаемый принципал пуст, даже если в Теоретически существует только один пользователь, который всегда вошел в систему. Проверяя несколько руководств, я чувствую, что то, что я делаю, правильно, поэтому я не совсем уверен, что я делаю неправильно.

userinfouri находится на следующем контроллере:

package com.example.demo;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
@EnableResourceServer
@RestController
public class UserController {

@RequestMapping ("/validateUser")
public Principal user(Principal principal) {
        System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        System.out.println(principal.getName());
                return principal;
        }}

Пользователь аутентифицируется в памяти следующим образом при запуске:

package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@Order(1)
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Value("${user.username}")
    private String username;
    @Value("${user.password}")
    private String password;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser(username)
                .password(passwordEncoder().encode(password))
                .roles("USER");

    }
    @Override
protected void configure(HttpSecurity security) throws Exception {
     .... http pattern configurations here -----
}
    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    };
    
}

Когда я вызываю по умолчанию путь «oauth / token» с информацией, которую я успешно получаю токен для этого пользователя, поэтому теоретически отправка запроса с токеном-носителем в вызов "validateUser" должна возвращать информацию о пользователе, связанном с этим токеном, верно?

Я могу опубликовать дополнительный код, если необходимо, но, насколько я понимаю, это соответствующие фрагменты

...