Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在RESTAPI中获取记录的用户id_Java_Rest_Authentication_Spring Security - Fatal编程技术网

Java 如何在RESTAPI中获取记录的用户id

Java 如何在RESTAPI中获取记录的用户id,java,rest,authentication,spring-security,Java,Rest,Authentication,Spring Security,我已经用RESTAPI约定构建了一个Java应用程序。我正在处理端点,该端点仅当对象通过数据库中的公共id(manytone注释)与用户连接时才返回对象。为了实现这一点,我需要当前记录的用户id,以便将其与对象的用户id进行比较。如果id相同,端点将返回数据。我知道解决方案是“主体”或“身份验证”类,但它们提供除“id”之外的所有内容。我使用SpringSecurityHTTPBasic进行身份验证。 我的身份验证类: @Component public class CustomAuthent

我已经用RESTAPI约定构建了一个Java应用程序。我正在处理端点,该端点仅当对象通过数据库中的公共id(manytone注释)与用户连接时才返回对象。为了实现这一点,我需要当前记录的用户id,以便将其与对象的用户id进行比较。如果id相同,端点将返回数据。我知道解决方案是“主体”或“身份验证”类,但它们提供除“id”之外的所有内容。我使用SpringSecurityHTTPBasic进行身份验证。 我的身份验证类:


@Component
public class CustomAuthenticator implements AuthenticationProvider {

    private final UserRepository userRepository;

    private final PasswordEncoder passwordEncoder;

    @Autowired
    public CustomAuthenticator(UserRepository userRepository, @Lazy PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String login = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = userRepository.findByLogin(login).orElseThrow(() -> new EntityNotFoundException("User not found"));
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new BadCredentialsException("Bad credentials");
        }

        return new UsernamePasswordAuthenticationToken(login, password, convertAuthorities(user.getRoles()));

    }

    private Set<GrantedAuthority> convertAuthorities(Set<UserRole> userRoles) {
        Set<GrantedAuthority> authorities = new HashSet<>();
        for (UserRole ur : userRoles) {
            authorities.add(new SimpleGrantedAuthority(ur.getRole().toString()));
        }
        return authorities;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}


有人知道如何解决这个问题吗

您可以使用
UserDetails
类并为
username
字段设置id,该类由spring security提供

如果您不需要该解决方案,可以创建一个
子类extend UserDetails
类并决定一个id字段。接收请求时,将主体解析为
UserDetails
子类extenseduserdetails
以获取id

例:


这是一个完美的答案。我从我的项目中添加了一些代码,您仍然确定YOUR解决方案适合我的审慎方法吗?如果您使用spring安全性,您可以在
UserDetails
类中管理
user profile
。首选:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final CustomAuthenticator customAuthenticator;

    public SecurityConfig(CustomAuthenticator customAuthenticator) {
        this.customAuthenticator = customAuthenticator;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return passwordEncoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/api").permitAll()
                .antMatchers("/api/register").permitAll()
                //TODO everybody now has access to database, change it later
                .antMatchers("/h2-console/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();

        http
                .csrf().disable()
                .headers().frameOptions().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticator);
    }
}

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails userPrincipal = (UserDetails)authentication.getPrincipal();